text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * $RCSfile: ControlContainerDescriptor.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-07-13 14:31:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_TOOLPANEL_CONTROL_CONTAINER_DESCRIPTOR_HXX #define SD_TOOLPANEL_CONTROL_CONTAINER_DESCRIPTOR_HXX #include "ILayoutableWindow.hxx" #include "TitleBar.hxx" #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef SD_WINDOW_HXX #include <vcl/window.hxx> #endif #include <memory> class Window; namespace sd { namespace toolpanel { class ControlContainer; /** Collection of information the describes entries of the tool panel. A descriptor owns the control it is associated with. */ class ControlContainerDescriptor : public ::Window, public virtual ILayoutableWindow { public: /** Create a new descriptor for the given control. @param rContainer The container to inform about selection (caused by mouse clicks or keyboard.) @param pParent The parent window of the new descriptor. @param pControl The control that is shown when being in the expanded state. @param rTitle String that is shown as title in the title area above the control. @param eType Type of the title bar. This specifies how the title bar will be formated. For more information see TitleBar. */ ControlContainerDescriptor ( ControlContainer& rContainer, ::Window* pParent, ::std::auto_ptr<ILayoutableWindow> pControl, const String& rTitle, TitleBar::TitleBarType eType); virtual ~ControlContainerDescriptor (void); virtual Size GetPreferredSize (void); virtual int GetPreferredWidth (int nHeight); virtual int GetPreferredHeight (int nWidth); virtual bool IsResizable (void); virtual ::Window* GetWindow (void); virtual void Resize (void); virtual void GetFocus (void); virtual void LoseFocus (void); virtual void MouseButtonUp (const MouseEvent& rMouseEvent); virtual void KeyInput (const KeyEvent& rEvent); void Select (bool bExpansionState); // const Rectangle& GetTitleBarBox (void) const; Window* GetControl (void) const; const String& GetTitle (void) const; void Expand (bool bExpanded = true); void Collapse (void); bool IsExpanded (void) const; /** Ownership of the given data remains with the caller. The data is thus not destroyed when the destructor of this class is called. */ void SetUserData (void* pUserData); void* GetUserData (void) const; bool IsVisible (void) const; void SetVisible (bool bVisible); private: ControlContainer& mrContainer; ::std::auto_ptr<TitleBar> mpTitleBar; ::std::auto_ptr<ILayoutableWindow> mpControl; String msTitle; bool mbExpanded; bool mbVisible; void* mpUserData; bool mnVisible; /// Do not use! Assignment operator is not supported. const ControlContainerDescriptor& operator= ( const ControlContainerDescriptor& aDescriptor); void UpdateStates (void); DECL_LINK(WindowEventListener, VclSimpleEvent*); }; } } // end of namespace ::sd::toolpanel #endif <commit_msg>INTEGRATION: CWS impress36 (1.2.248); FILE MERGED 2005/02/24 17:27:57 af 1.2.248.1: #i43335# Moved ILayoutableWindow.hxx to ../inc/taskpane.<commit_after>/************************************************************************* * * $RCSfile: ControlContainerDescriptor.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-03-18 16:54:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_TASKPANE_CONTROL_CONTAINER_DESCRIPTOR_HXX #define SD_TASKPANE_CONTROL_CONTAINER_DESCRIPTOR_HXX #include "taskpane/ILayoutableWindow.hxx" #include "TitleBar.hxx" #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef SD_WINDOW_HXX #include <vcl/window.hxx> #endif #include <memory> class Window; namespace sd { namespace toolpanel { class ControlContainer; /** Collection of information the describes entries of the tool panel. A descriptor owns the control it is associated with. */ class ControlContainerDescriptor : public ::Window, public virtual ILayoutableWindow { public: /** Create a new descriptor for the given control. @param rContainer The container to inform about selection (caused by mouse clicks or keyboard.) @param pParent The parent window of the new descriptor. @param pControl The control that is shown when being in the expanded state. @param rTitle String that is shown as title in the title area above the control. @param eType Type of the title bar. This specifies how the title bar will be formated. For more information see TitleBar. */ ControlContainerDescriptor ( ControlContainer& rContainer, ::Window* pParent, ::std::auto_ptr<ILayoutableWindow> pControl, const String& rTitle, TitleBar::TitleBarType eType); virtual ~ControlContainerDescriptor (void); virtual Size GetPreferredSize (void); virtual int GetPreferredWidth (int nHeight); virtual int GetPreferredHeight (int nWidth); virtual bool IsResizable (void); virtual ::Window* GetWindow (void); virtual void Resize (void); virtual void GetFocus (void); virtual void LoseFocus (void); virtual void MouseButtonUp (const MouseEvent& rMouseEvent); virtual void KeyInput (const KeyEvent& rEvent); void Select (bool bExpansionState); // const Rectangle& GetTitleBarBox (void) const; Window* GetControl (void) const; const String& GetTitle (void) const; void Expand (bool bExpanded = true); void Collapse (void); bool IsExpanded (void) const; /** Ownership of the given data remains with the caller. The data is thus not destroyed when the destructor of this class is called. */ void SetUserData (void* pUserData); void* GetUserData (void) const; bool IsVisible (void) const; void SetVisible (bool bVisible); private: ControlContainer& mrContainer; ::std::auto_ptr<TitleBar> mpTitleBar; ::std::auto_ptr<ILayoutableWindow> mpControl; String msTitle; bool mbExpanded; bool mbVisible; void* mpUserData; bool mnVisible; /// Do not use! Assignment operator is not supported. const ControlContainerDescriptor& operator= ( const ControlContainerDescriptor& aDescriptor); void UpdateStates (void); DECL_LINK(WindowEventListener, VclSimpleEvent*); }; } } // end of namespace ::sd::toolpanel #endif <|endoftext|>
<commit_before>// Copyright (c) 2015 Pierre MOULON. // 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 "openMVG/sfm/sfm.hpp" #include "openMVG/exif/exif_IO_EasyExif.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #ifdef HAVE_BOOST #include <boost/system/error_code.hpp> #include <boost/filesystem.hpp> #endif #include <string> #include <vector> using namespace openMVG; using namespace openMVG::sfm; /** * @brief Update all viewID referenced in the observation of each landmark according * to the provided mapping. * * @param[in,out] landmarks The landmarks to update. * @param[in] oldIdToNew The mapping between the old ID and the reconmputed UID. */ void updateStructureWithNewUID(Landmarks &landmarks, const std::map<std::size_t, std::size_t> &oldIdToNew) { // update the id in the visibility of each 3D point for(auto &iter : landmarks) { Landmark& currentLandmark = iter.second; // the new observations where to copy the existing ones // (needed as the key of the map is the idview) Observations newObservations; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; newObservations.emplace(oldIdToNew.at(idview), obs); } assert(currentLandmark.obs.size() == newObservations.size()); currentLandmark.obs.swap(newObservations); } } /** * @brief Recompute the UID from the metadata of the original input images and * modify the ID if it's not the same. * * @param[in,out] sfmdata The sfmdata scene for which to recompute the UID. * @param[out] oldIdToNew A map that holds the mapping between the old ID and the * reconmputed UID. * @param[in] sanityCheck Enable a sanity check at the end to assure that the * observations of 3D points and the control points have been correctly updated. */ void regenerateUID(sfm::SfM_Data &sfmdata, std::map<std::size_t, std::size_t> &oldIdToNew, bool sanityCheck = false) { // if the views are empty, nothing to be done. if(sfmdata.GetViews().empty()) return; Views newViews; for(auto const &iter : sfmdata.views) { const View& currentView = *iter.second.get(); const auto &imageName = currentView.s_Img_path; exif::Exif_IO_EasyExif exifReader(imageName); // compute the view UID const std::size_t uid = exif::computeUID(exifReader, imageName); // update the mapping assert(oldIdToNew.count(currentView.id_view) == 0); oldIdToNew.emplace(currentView.id_view, uid); // add the view to the new map using the uid as key and change the id assert(newViews.count(uid) == 0); newViews.emplace(uid, iter.second); newViews[uid]->id_view = uid; } assert(newViews.size() == sfmdata.GetViews().size()); sfmdata.views.swap(newViews); // update the id in the visibility of each 3D point updateStructureWithNewUID(sfmdata.structure, oldIdToNew); // update the id in the visibility of each 3D point updateStructureWithNewUID(sfmdata.control_points, oldIdToNew); if(!sanityCheck) return; // sanity check for(auto &iter : sfmdata.structure) { Landmark& currentLandmark = iter.second; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; // there must be a view with that id (in the map) and the view must have // the same id (the member) assert(sfmdata.views.count(idview) == 1); assert(sfmdata.views.at(idview)->id_view == idview); } } // sanity check for(auto &iter : sfmdata.control_points) { Landmark& currentLandmark = iter.second; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; // there must be a view with that id (in the map) and the view must have // the same id (the member) assert(sfmdata.views.count(idview) == 1); assert(sfmdata.views.at(idview)->id_view == idview); } } } // Convert from a SfM_Data format to another int main(int argc, char **argv) { CmdLine cmd; std::string sSfM_Data_Filename_In; std::string sSfM_Data_Filename_Out; #ifdef HAVE_BOOST std::string matchDir; #endif cmd.add(make_option('i', sSfM_Data_Filename_In, "input_file")); cmd.add(make_switch('V', "VIEWS")); cmd.add(make_switch('I', "INTRINSICS")); cmd.add(make_switch('E', "EXTRINSICS")); cmd.add(make_switch('S', "STRUCTURE")); cmd.add(make_switch('O', "OBSERVATIONS")); cmd.add(make_switch('C', "CONTROL_POINTS")); cmd.add(make_switch('u', "regenerateUID")); cmd.add(make_option('o', sSfM_Data_Filename_Out, "output_file")); #ifdef HAVE_BOOST cmd.add(make_option('m', matchDir, "matchDirectory")); #endif try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] path to the input SfM_Data scene\n" << "[-o|--output_file] path to the output SfM_Data scene\n" << "\t .json, .bin, .xml, .ply, .baf" #if HAVE_ALEMBIC ", .abc" #endif "\n" << "\n[Options to export partial data (by default all data are exported)]\n" << "\nUsable for json/bin/xml format\n" << "[-V|--VIEWS] export views\n" << "[-I|--INTRINSICS] export intrinsics\n" << "[-E|--EXTRINSICS] export extrinsics (view poses)\n" << "[-S|--STRUCTURE] export structure\n" << "[-O|--OBSERVATIONS] export 2D observations associated with 3D structure\n" << "[-C|--CONTROL_POINTS] export control points\n" << "[-u|--uid] (re-)compute the unique ID (UID) for the views\n" #ifdef HAVE_BOOST << "[-m|--matchDirectory] the directory containing the features used for the\n" " reconstruction. If provided along the -u option, it creates symbolic\n" " links to the .desc and .feat with the new UID as name. This can be\n" " for legacy reconstructions that were not made using UID" #endif << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (sSfM_Data_Filename_In.empty() || sSfM_Data_Filename_Out.empty()) { std::cerr << "Invalid input or output filename." << std::endl; return EXIT_FAILURE; } // OptionSwitch is cloned in cmd.add(), // so we must use cmd.used() instead of testing OptionSwitch.used int flags = (cmd.used('V') ? VIEWS : 0) | (cmd.used('I') ? INTRINSICS : 0) | (cmd.used('E') ? EXTRINSICS : 0) | (cmd.used('O') ? OBSERVATIONS : 0) | (cmd.used('S') ? STRUCTURE : 0); flags = (flags) ? flags : ALL; const bool recomputeUID = cmd.used('u'); // Load input SfM_Data scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename_In, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \"" << sSfM_Data_Filename_In << "\" cannot be read." << std::endl; return EXIT_FAILURE; } if(recomputeUID) { std::cout << "Recomputing the UID of the views..." << std::endl; std::map<std::size_t, std::size_t> oldIdToNew; regenerateUID(sfm_data, oldIdToNew); #ifdef HAVE_BOOST if(!matchDir.empty()) { std::cout << "Generating alias for .feat and .desc with the UIDs" << std::endl; for(const auto& iter : oldIdToNew) { const auto oldID = iter.first; const auto newID = iter.second; const auto oldFeatfilename = stlplus::create_filespec(matchDir, std::to_string(oldID), ".feat"); const auto newFeatfilename = stlplus::create_filespec(matchDir, std::to_string(newID), ".feat"); const auto oldDescfilename = stlplus::create_filespec(matchDir, std::to_string(oldID), ".desc"); const auto newDescfilename = stlplus::create_filespec(matchDir, std::to_string(newID), ".desc"); if(!(stlplus::is_file(oldFeatfilename) && stlplus::is_file(oldDescfilename))) { std::cerr << "Cannot find the features file for view ID " << oldID << std::endl; return EXIT_FAILURE; } boost::system::error_code ec; boost::filesystem::create_symlink(oldFeatfilename, newFeatfilename, ec); if(ec) { std::cerr << "Error while creating " << newFeatfilename << ": " << ec.message() << std::endl; return EXIT_FAILURE; } boost::filesystem::create_symlink(oldDescfilename, newDescfilename, ec); if(ec) { std::cerr << "Error while creating " << newDescfilename << ": " << ec.message() << std::endl; return EXIT_FAILURE; } } } #endif } // Export the SfM_Data scene in the expected format if (!Save(sfm_data, sSfM_Data_Filename_Out, ESfM_Data(flags))) { std::cerr << std::endl << "An error occured while trying to save \"" << sSfM_Data_Filename_Out << "\"." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>[software] check if(oldID == newID) do not create alias<commit_after>// Copyright (c) 2015 Pierre MOULON. // 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 "openMVG/sfm/sfm.hpp" #include "openMVG/exif/exif_IO_EasyExif.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #ifdef HAVE_BOOST #include <boost/system/error_code.hpp> #include <boost/filesystem.hpp> #endif #include <string> #include <vector> using namespace openMVG; using namespace openMVG::sfm; /** * @brief Update all viewID referenced in the observation of each landmark according * to the provided mapping. * * @param[in,out] landmarks The landmarks to update. * @param[in] oldIdToNew The mapping between the old ID and the reconmputed UID. */ void updateStructureWithNewUID(Landmarks &landmarks, const std::map<std::size_t, std::size_t> &oldIdToNew) { // update the id in the visibility of each 3D point for(auto &iter : landmarks) { Landmark& currentLandmark = iter.second; // the new observations where to copy the existing ones // (needed as the key of the map is the idview) Observations newObservations; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; newObservations.emplace(oldIdToNew.at(idview), obs); } assert(currentLandmark.obs.size() == newObservations.size()); currentLandmark.obs.swap(newObservations); } } /** * @brief Recompute the UID from the metadata of the original input images and * modify the ID if it's not the same. * * @param[in,out] sfmdata The sfmdata scene for which to recompute the UID. * @param[out] oldIdToNew A map that holds the mapping between the old ID and the * reconmputed UID. * @param[in] sanityCheck Enable a sanity check at the end to assure that the * observations of 3D points and the control points have been correctly updated. */ void regenerateUID(sfm::SfM_Data &sfmdata, std::map<std::size_t, std::size_t> &oldIdToNew, bool sanityCheck = false) { // if the views are empty, nothing to be done. if(sfmdata.GetViews().empty()) return; Views newViews; for(auto const &iter : sfmdata.views) { const View& currentView = *iter.second.get(); const auto &imageName = currentView.s_Img_path; exif::Exif_IO_EasyExif exifReader(imageName); // compute the view UID const std::size_t uid = exif::computeUID(exifReader, imageName); // update the mapping assert(oldIdToNew.count(currentView.id_view) == 0); oldIdToNew.emplace(currentView.id_view, uid); // add the view to the new map using the uid as key and change the id assert(newViews.count(uid) == 0); newViews.emplace(uid, iter.second); newViews[uid]->id_view = uid; } assert(newViews.size() == sfmdata.GetViews().size()); sfmdata.views.swap(newViews); // update the id in the visibility of each 3D point updateStructureWithNewUID(sfmdata.structure, oldIdToNew); // update the id in the visibility of each 3D point updateStructureWithNewUID(sfmdata.control_points, oldIdToNew); if(!sanityCheck) return; // sanity check for(auto &iter : sfmdata.structure) { Landmark& currentLandmark = iter.second; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; // there must be a view with that id (in the map) and the view must have // the same id (the member) assert(sfmdata.views.count(idview) == 1); assert(sfmdata.views.at(idview)->id_view == idview); } } // sanity check for(auto &iter : sfmdata.control_points) { Landmark& currentLandmark = iter.second; for(const auto &iterObs : currentLandmark.obs) { const auto idview = iterObs.first; const Observation &obs = iterObs.second; // there must be a view with that id (in the map) and the view must have // the same id (the member) assert(sfmdata.views.count(idview) == 1); assert(sfmdata.views.at(idview)->id_view == idview); } } } // Convert from a SfM_Data format to another int main(int argc, char **argv) { CmdLine cmd; std::string sSfM_Data_Filename_In; std::string sSfM_Data_Filename_Out; #ifdef HAVE_BOOST std::string matchDir; #endif cmd.add(make_option('i', sSfM_Data_Filename_In, "input_file")); cmd.add(make_switch('V', "VIEWS")); cmd.add(make_switch('I', "INTRINSICS")); cmd.add(make_switch('E', "EXTRINSICS")); cmd.add(make_switch('S', "STRUCTURE")); cmd.add(make_switch('O', "OBSERVATIONS")); cmd.add(make_switch('C', "CONTROL_POINTS")); cmd.add(make_switch('u', "regenerateUID")); cmd.add(make_option('o', sSfM_Data_Filename_Out, "output_file")); #ifdef HAVE_BOOST cmd.add(make_option('m', matchDir, "matchDirectory")); #endif try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] path to the input SfM_Data scene\n" << "[-o|--output_file] path to the output SfM_Data scene\n" << "\t .json, .bin, .xml, .ply, .baf" #if HAVE_ALEMBIC ", .abc" #endif "\n" << "\n[Options to export partial data (by default all data are exported)]\n" << "\nUsable for json/bin/xml format\n" << "[-V|--VIEWS] export views\n" << "[-I|--INTRINSICS] export intrinsics\n" << "[-E|--EXTRINSICS] export extrinsics (view poses)\n" << "[-S|--STRUCTURE] export structure\n" << "[-O|--OBSERVATIONS] export 2D observations associated with 3D structure\n" << "[-C|--CONTROL_POINTS] export control points\n" << "[-u|--uid] (re-)compute the unique ID (UID) for the views\n" #ifdef HAVE_BOOST << "[-m|--matchDirectory] the directory containing the features used for the\n" " reconstruction. If provided along the -u option, it creates symbolic\n" " links to the .desc and .feat with the new UID as name. This can be\n" " for legacy reconstructions that were not made using UID" #endif << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (sSfM_Data_Filename_In.empty() || sSfM_Data_Filename_Out.empty()) { std::cerr << "Invalid input or output filename." << std::endl; return EXIT_FAILURE; } // OptionSwitch is cloned in cmd.add(), // so we must use cmd.used() instead of testing OptionSwitch.used int flags = (cmd.used('V') ? VIEWS : 0) | (cmd.used('I') ? INTRINSICS : 0) | (cmd.used('E') ? EXTRINSICS : 0) | (cmd.used('O') ? OBSERVATIONS : 0) | (cmd.used('S') ? STRUCTURE : 0); flags = (flags) ? flags : ALL; const bool recomputeUID = cmd.used('u'); // Load input SfM_Data scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename_In, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \"" << sSfM_Data_Filename_In << "\" cannot be read." << std::endl; return EXIT_FAILURE; } if(recomputeUID) { std::cout << "Recomputing the UID of the views..." << std::endl; std::map<std::size_t, std::size_t> oldIdToNew; regenerateUID(sfm_data, oldIdToNew); #ifdef HAVE_BOOST if(!matchDir.empty()) { std::cout << "Generating alias for .feat and .desc with the UIDs" << std::endl; for(const auto& iter : oldIdToNew) { const auto oldID = iter.first; const auto newID = iter.second; // nothing to do if the ids are the same if(oldID == newID) continue; const auto oldFeatfilename = stlplus::create_filespec(matchDir, std::to_string(oldID), ".feat"); const auto newFeatfilename = stlplus::create_filespec(matchDir, std::to_string(newID), ".feat"); const auto oldDescfilename = stlplus::create_filespec(matchDir, std::to_string(oldID), ".desc"); const auto newDescfilename = stlplus::create_filespec(matchDir, std::to_string(newID), ".desc"); if(!(stlplus::is_file(oldFeatfilename) && stlplus::is_file(oldDescfilename))) { std::cerr << "Cannot find the features file for view ID " << oldID << std::endl; return EXIT_FAILURE; } boost::system::error_code ec; boost::filesystem::create_symlink(oldFeatfilename, newFeatfilename, ec); if(ec) { std::cerr << "Error while creating " << newFeatfilename << ": " << ec.message() << std::endl; return EXIT_FAILURE; } boost::filesystem::create_symlink(oldDescfilename, newDescfilename, ec); if(ec) { std::cerr << "Error while creating " << newDescfilename << ": " << ec.message() << std::endl; return EXIT_FAILURE; } } } #endif } // Export the SfM_Data scene in the expected format if (!Save(sfm_data, sSfM_Data_Filename_Out, ESfM_Data(flags))) { std::cerr << std::endl << "An error occured while trying to save \"" << sSfM_Data_Filename_Out << "\"." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** @file * * @ingroup dspSoundFileLib * * @brief Tests for the #TTSoundfile class * * @details Tests the core functions of the TTSoundfile class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, it is important to change the TESTFILE definitions in this file to match a local absolute address. The related TEST definitions should also be set to match the attribution of the file which can be obtained via your sound file editor of choice. * * @authors Nathan Wolek * * @copyright Copyright © 2013 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfile.h" #include "TTUnitTest.h" /* */ #define TESTFILE "/Volumes/Storage/Audio/200604femf15/pitched/ding_b2.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 39493 #define TESTDURATIONINSECONDS 0.89553288 #define TESTTITLE "" #define TESTARTIST "Nathan Wolek" #define TESTDATE "2006" #define TESTANNOTATION "Yo Mama" #define TENTHSAMPLE -0.03125 /* */ /* #define TESTFILE "/Volumes/Storage/Audio/200604femf15/ambience/street.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 4750848 #define TESTDURATIONINSECONDS 107.728980 #define TESTTITLE "UF Street" #define TESTARTIST "MPG" #define TESTDATE "2006" #define TESTANNOTATION "" */ TTErr TTSoundfile::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; { TTTestLog("\n"); TTTestLog("Testing TTSoundfile Basics..."); TTSoundfilePtr soundfile = NULL; TTErr err; // TEST 0: instantiate the object to a pointer TTBoolean result0 = { TTObjectBaseInstantiate("soundfile", (TTObjectBasePtr*)&soundfile, kTTValNONE) == kTTErrNone}; TTTestAssertion("instantiates successfully", result0, testAssertionCount, errorCount); // TEST 1: set the filepath TTBoolean result1 = { soundfile->setFilePath(TT(TESTFILE)) == kTTErrNone }; TTTestAssertion("setFilePath operates successfully", result1, testAssertionCount, errorCount); // TEST 2: reports correct number of channels TTRowID return2 = soundfile->getNumChannels(); TTBoolean result2 = { return2 == TESTNUMCHANNELS }; TTTestAssertion("reports the correct number of channels", result2, testAssertionCount, errorCount); if(!result2) { TTTestLog("Expected a value of %i, but returned value was %i", TESTNUMCHANNELS, return2); } // TEST 3: reports correct sample rate TTFloat64 return3 = soundfile->getSampleRate(); TTBoolean result3 = TTTestFloatEquivalence(return3, TESTSAMPLERATE, true, 0.0000001); TTTestAssertion("reports the correct sample rate", result3, testAssertionCount, errorCount); if(!result3) { TTTestLog("Expected a value of %f, but returned value was %f", TESTSAMPLERATE, return3); } // TEST 4: reports correct duration in samples TTColumnID return4 = soundfile->getDurationInSamples(); TTBoolean result4 = { return4 == TESTDURATIONINSAMPLES }; TTTestAssertion("reports the correct duration in samples", result4, testAssertionCount, errorCount); if(!result4) { TTTestLog("Expected a value of %i, but returned value was %i", TESTDURATIONINSAMPLES, return4); } // TEST 5: reports correct duration in seconds TTFloat64 return5 = soundfile->getDurationInSeconds(); TTBoolean result5 = TTTestFloatEquivalence(return5, TESTDURATIONINSECONDS, true, 0.0000001); TTTestAssertion("reports the correct duration in seconds", result5, testAssertionCount, errorCount); if(!result5) { TTTestLog("Expected a value of %f, but returned value was %f", TESTDURATIONINSECONDS, return5); } TTTestLog("\n"); TTTestLog("Testing TTSoundfile Metadata..."); // TEST 6: reports correct title from metadata TTSymbol return6 = soundfile->getTitle(); TTTestLog("Expected metadata title:"); TTTestLog(TESTTITLE); TTTestLog("Returned metadata title:"); TTTestLog(return6); // TEST 7: reports correct artist from metadata TTSymbol return7 = soundfile->getArtist(); TTTestLog("Expected metadata artist:"); TTTestLog(TESTARTIST); TTTestLog("Returned metadata artist:"); TTTestLog(return7); // TEST 8: reports correct title from metadata TTSymbol return8 = soundfile->getDate(); TTTestLog("Expected metadata date:"); TTTestLog(TESTDATE); TTTestLog("Returned metadata date:"); TTTestLog(return8); // TEST 9: reports correct artist from metadata TTSymbol return9 = soundfile->getAnnotation(); TTTestLog("Expected metadata comment:"); TTTestLog(TESTANNOTATION); TTTestLog("Returned metadata comment:"); TTTestLog(return9); TTTestLog("\n"); TTTestLog("Testing peek method..."); TTSampleValue return10; TTErr error10; for (int n=0;n<10;n++) { error10 = soundfile->peek(n,0,return10); if (error10 == kTTErrNone) { TTTestLog("peek executed without error and returned the value %f", return10); } else { TTTestLog("peek returned an error"); } } } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <commit_msg>TTsoundfile::peek() value ARE right. issue was Max bug, not problem with code.<commit_after>/** @file * * @ingroup dspSoundFileLib * * @brief Tests for the #TTSoundfile class * * @details Tests the core functions of the TTSoundfile class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, it is important to change the TESTFILE definitions in this file to match a local absolute address. The related TEST definitions should also be set to match the attribution of the file which can be obtained via your sound file editor of choice. * * @authors Nathan Wolek * * @copyright Copyright © 2013 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfile.h" #include "TTUnitTest.h" /* */ #define TESTFILE "/Volumes/Storage/Audio/200604femf15/pitched/ding_b2.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 39493 #define TESTDURATIONINSECONDS 0.89553288 #define TESTTITLE "" #define TESTARTIST "Nathan Wolek" #define TESTDATE "2006" #define TESTANNOTATION "Yo Mama" #define TENTHSAMPLE -0.03125 /* */ /* #define TESTFILE "/Volumes/Storage/Audio/200604femf15/ambience/street.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 4750848 #define TESTDURATIONINSECONDS 107.728980 #define TESTTITLE "UF Street" #define TESTARTIST "MPG" #define TESTDATE "2006" #define TESTANNOTATION "" */ TTErr TTSoundfile::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; { TTTestLog("\n"); TTTestLog("Testing TTSoundfile Basics..."); TTSoundfilePtr soundfile = NULL; TTErr err; // TEST 0: instantiate the object to a pointer TTBoolean result0 = { TTObjectBaseInstantiate("soundfile", (TTObjectBasePtr*)&soundfile, kTTValNONE) == kTTErrNone}; TTTestAssertion("instantiates successfully", result0, testAssertionCount, errorCount); // TEST 1: set the filepath TTBoolean result1 = { soundfile->setFilePath(TT(TESTFILE)) == kTTErrNone }; TTTestAssertion("setFilePath operates successfully", result1, testAssertionCount, errorCount); // TEST 2: reports correct number of channels TTRowID return2 = soundfile->getNumChannels(); TTBoolean result2 = { return2 == TESTNUMCHANNELS }; TTTestAssertion("reports the correct number of channels", result2, testAssertionCount, errorCount); if(!result2) { TTTestLog("Expected a value of %i, but returned value was %i", TESTNUMCHANNELS, return2); } // TEST 3: reports correct sample rate TTFloat64 return3 = soundfile->getSampleRate(); TTBoolean result3 = TTTestFloatEquivalence(return3, TESTSAMPLERATE, true, 0.0000001); TTTestAssertion("reports the correct sample rate", result3, testAssertionCount, errorCount); if(!result3) { TTTestLog("Expected a value of %f, but returned value was %f", TESTSAMPLERATE, return3); } // TEST 4: reports correct duration in samples TTColumnID return4 = soundfile->getDurationInSamples(); TTBoolean result4 = { return4 == TESTDURATIONINSAMPLES }; TTTestAssertion("reports the correct duration in samples", result4, testAssertionCount, errorCount); if(!result4) { TTTestLog("Expected a value of %i, but returned value was %i", TESTDURATIONINSAMPLES, return4); } // TEST 5: reports correct duration in seconds TTFloat64 return5 = soundfile->getDurationInSeconds(); TTBoolean result5 = TTTestFloatEquivalence(return5, TESTDURATIONINSECONDS, true, 0.0000001); TTTestAssertion("reports the correct duration in seconds", result5, testAssertionCount, errorCount); if(!result5) { TTTestLog("Expected a value of %f, but returned value was %f", TESTDURATIONINSECONDS, return5); } TTTestLog("\n"); TTTestLog("Testing TTSoundfile Metadata..."); // TEST 6: reports correct title from metadata TTSymbol return6 = soundfile->getTitle(); TTTestLog("Expected metadata title:"); TTTestLog(TESTTITLE); TTTestLog("Returned metadata title:"); TTTestLog(return6); // TEST 7: reports correct artist from metadata TTSymbol return7 = soundfile->getArtist(); TTTestLog("Expected metadata artist:"); TTTestLog(TESTARTIST); TTTestLog("Returned metadata artist:"); TTTestLog(return7); // TEST 8: reports correct title from metadata TTSymbol return8 = soundfile->getDate(); TTTestLog("Expected metadata date:"); TTTestLog(TESTDATE); TTTestLog("Returned metadata date:"); TTTestLog(return8); // TEST 9: reports correct artist from metadata TTSymbol return9 = soundfile->getAnnotation(); TTTestLog("Expected metadata comment:"); TTTestLog(TESTANNOTATION); TTTestLog("Returned metadata comment:"); TTTestLog(return9); TTTestLog("\n"); TTTestLog("Testing peek method..."); TTSampleValue return10; TTErr error10; for (int n=0;n<10;n++) { error10 = soundfile->peek(n,0,return10); if (error10 == kTTErrNone) { TTTestLog("peek sample %i returned the value %f", n, return10); } else { TTTestLog("peek returned an error for sample %i", n); } } } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bmp.cxx,v $ * $Revision: 1.18 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <stdio.h> #include <signal.h> #include <vector> using namespace std; #include <vcl/svapp.hxx> #include "svtools/solar.hrc" #include "filedlg.hxx" #include "bmpcore.hxx" #include "bmp.hrc" // ---------- // - BmpApp - // ---------- class BmpApp : public BmpCreator { private: String aOutputFileName; BYTE cExitCode; BOOL GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam ); BOOL GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams ); void SetExitCode( BYTE cExit ) { if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) ) cExitCode = cExit; } void ShowUsage(); virtual void Message( const String& rText, BYTE cExitCode ); public: BmpApp(); ~BmpApp(); int Start( const ::std::vector< String >& rArgs ); }; // ----------------------------------------------------------------------------- BmpApp::BmpApp() { } // ----------------------------------------------------------------------------- BmpApp::~BmpApp() { } // ----------------------------------------------------------------------- BOOL BmpApp::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam ) { BOOL bRet = FALSE; for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ ) { String aTestStr( '-' ); for( int n = 0; ( n < 2 ) && !bRet; n++ ) { aTestStr += rSwitch; if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL ) { bRet = TRUE; if( i < ( nCount - 1 ) ) rParam = rArgs[ i + 1 ]; else rParam = String(); } if( 0 == n ) aTestStr = '/'; } } return bRet; } // ----------------------------------------------------------------------- BOOL BmpApp::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams ) { BOOL bRet = FALSE; for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ ) { String aTestStr( '-' ); for( int n = 0; ( n < 2 ) && !bRet; n++ ) { aTestStr += rSwitch; if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL ) { if( i < ( nCount - 1 ) ) rParams.push_back( rArgs[ i + 1 ] ); else rParams.push_back( String() ); break; } if( 0 == n ) aTestStr = '/'; } } return( rParams.size() > 0 ); } // ----------------------------------------------------------------------- void BmpApp::Message( const String& rText, BYTE cExit ) { if( EXIT_NOERROR != cExit ) SetExitCode( cExit ); ByteString aText( rText, RTL_TEXTENCODING_UTF8 ); aText.Append( "\r\n" ); fprintf( stderr, aText.GetBuffer() ); } // ----------------------------------------------------------------------------- void BmpApp::ShowUsage() { Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmp srs_inputfile output_dir lang_dir lang_num -i input_dir [-i input_dir ][-f err_file]" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( " -i ... name of directory to be searched for input files [multiple occurence is possible]" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( " -f name of file, output should be written to" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmp /home/test.srs /home/out enus 01 -i /home/res -f /home/out/bmp.err" ) ), EXIT_NOERROR ); } // ----------------------------------------------------------------------------- int BmpApp::Start( const ::std::vector< String >& rArgs ) { String aOutName; cExitCode = EXIT_NOERROR; if( rArgs.size() >= 6 ) { LangInfo aLangInfo; USHORT nCurCmd = 0; const String aSrsName( rArgs[ nCurCmd++ ] ); ::std::vector< String > aInDirVector; ByteString aLangDir; aOutName = rArgs[ nCurCmd++ ]; aLangDir = ByteString( rArgs[ nCurCmd++ ], RTL_TEXTENCODING_ASCII_US ); aLangInfo.mnLangNum = static_cast< sal_uInt16 >( rArgs[ nCurCmd++ ].ToInt32() ); memcpy( aLangInfo.maLangDir, aLangDir.GetBuffer(), aLangDir.Len() + 1 ); GetCommandOption( rArgs, 'f', aOutputFileName ); GetCommandOptions( rArgs, 'i', aInDirVector ); Create( aSrsName, aInDirVector, aOutName, aLangInfo ); } else { ShowUsage(); cExitCode = EXIT_COMMONERROR; } if( ( EXIT_NOERROR == cExitCode ) && aOutputFileName.Len() && aOutName.Len() ) { SvFileStream aOStm( aOutputFileName, STREAM_WRITE | STREAM_TRUNC ); ByteString aStr( "Successfully generated ImageList(s) in: " ); aOStm.WriteLine( aStr.Append( ByteString( aOutName, RTL_TEXTENCODING_UTF8 ) ) ); aOStm.Close(); } return cExitCode; } // -------- // - Main - // -------- int main( int nArgCount, char* ppArgs[] ) { #ifdef UNX static char aDisplayVar[ 1024 ]; strcpy( aDisplayVar, "DISPLAY=" ); putenv( aDisplayVar ); #endif ::std::vector< String > aArgs; BmpApp aBmpApp; InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() ); for( int i = 1; i < nArgCount; i++ ) aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) ); return aBmpApp.Start( aArgs ); } <commit_msg>INTEGRATION: CWS aw033 (1.17.60); FILE MERGED 2008/05/14 15:16:38 aw 1.17.60.3: RESYNC: (1.17-1.18); FILE MERGED 2007/08/13 15:29:48 aw 1.17.60.2: #i39532# changes after resync 2007/06/29 10:37:31 aw 1.17.60.1: changes after resyc<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bmp.cxx,v $ * $Revision: 1.19 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #ifndef INCLUDED_RTL_MATH_HXX #include <rtl/math.hxx> #endif #include <math.h> #include <stdio.h> #include <signal.h> #include <vector> using namespace std; #include <vcl/svapp.hxx> #include "svtools/solar.hrc" #include "filedlg.hxx" #include "bmpcore.hxx" #include "bmp.hrc" // ---------- // - BmpApp - // ---------- class BmpApp : public BmpCreator { private: String aOutputFileName; BYTE cExitCode; BOOL GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam ); BOOL GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams ); void SetExitCode( BYTE cExit ) { if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) ) cExitCode = cExit; } void ShowUsage(); virtual void Message( const String& rText, BYTE cExitCode ); public: BmpApp(); ~BmpApp(); int Start( const ::std::vector< String >& rArgs ); }; // ----------------------------------------------------------------------------- BmpApp::BmpApp() { } // ----------------------------------------------------------------------------- BmpApp::~BmpApp() { } // ----------------------------------------------------------------------- BOOL BmpApp::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam ) { BOOL bRet = FALSE; for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ ) { String aTestStr( '-' ); for( int n = 0; ( n < 2 ) && !bRet; n++ ) { aTestStr += rSwitch; if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL ) { bRet = TRUE; if( i < ( nCount - 1 ) ) rParam = rArgs[ i + 1 ]; else rParam = String(); } if( 0 == n ) aTestStr = '/'; } } return bRet; } // ----------------------------------------------------------------------- BOOL BmpApp::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams ) { BOOL bRet = FALSE; for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ ) { String aTestStr( '-' ); for( int n = 0; ( n < 2 ) && !bRet; n++ ) { aTestStr += rSwitch; if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL ) { if( i < ( nCount - 1 ) ) rParams.push_back( rArgs[ i + 1 ] ); else rParams.push_back( String() ); break; } if( 0 == n ) aTestStr = '/'; } } return( rParams.size() > 0 ); } // ----------------------------------------------------------------------- void BmpApp::Message( const String& rText, BYTE cExit ) { if( EXIT_NOERROR != cExit ) SetExitCode( cExit ); ByteString aText( rText, RTL_TEXTENCODING_UTF8 ); aText.Append( "\r\n" ); fprintf( stderr, aText.GetBuffer() ); } // ----------------------------------------------------------------------------- void BmpApp::ShowUsage() { Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmp srs_inputfile output_dir lang_dir lang_num -i input_dir [-i input_dir ][-f err_file]" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( " -i ... name of directory to be searched for input files [multiple occurence is possible]" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( " -f name of file, output should be written to" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR ); Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmp /home/test.srs /home/out enus 01 -i /home/res -f /home/out/bmp.err" ) ), EXIT_NOERROR ); } // ----------------------------------------------------------------------------- int BmpApp::Start( const ::std::vector< String >& rArgs ) { String aOutName; cExitCode = EXIT_NOERROR; if( rArgs.size() >= 6 ) { LangInfo aLangInfo; USHORT nCurCmd = 0; const String aSrsName( rArgs[ nCurCmd++ ] ); ::std::vector< String > aInDirVector; ByteString aLangDir; aOutName = rArgs[ nCurCmd++ ]; aLangDir = ByteString( rArgs[ nCurCmd++ ], RTL_TEXTENCODING_ASCII_US ); aLangInfo.mnLangNum = static_cast< sal_uInt16 >( rArgs[ nCurCmd++ ].ToInt32() ); memcpy( aLangInfo.maLangDir, aLangDir.GetBuffer(), aLangDir.Len() + 1 ); GetCommandOption( rArgs, 'f', aOutputFileName ); GetCommandOptions( rArgs, 'i', aInDirVector ); Create( aSrsName, aInDirVector, aOutName, aLangInfo ); } else { ShowUsage(); cExitCode = EXIT_COMMONERROR; } if( ( EXIT_NOERROR == cExitCode ) && aOutputFileName.Len() && aOutName.Len() ) { SvFileStream aOStm( aOutputFileName, STREAM_WRITE | STREAM_TRUNC ); ByteString aStr( "Successfully generated ImageList(s) in: " ); aOStm.WriteLine( aStr.Append( ByteString( aOutName, RTL_TEXTENCODING_UTF8 ) ) ); aOStm.Close(); } return cExitCode; } // -------- // - Main - // -------- int main( int nArgCount, char* ppArgs[] ) { #ifdef UNX static char aDisplayVar[ 1024 ]; strcpy( aDisplayVar, "DISPLAY=" ); putenv( aDisplayVar ); #endif ::std::vector< String > aArgs; BmpApp aBmpApp; InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() ); for( int i = 1; i < nArgCount; i++ ) aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) ); return aBmpApp.Start( aArgs ); } <|endoftext|>
<commit_before>/** * @file Libyang.hpp * @author Mislav Novakovic <mislav.novakovic@sartura.hr> * @brief Class implementation for libyang C header libyang.h. * * Copyright (c) 2017 Deutsche Telekom AG. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #ifndef LIBYANG_H #define LIBYANG_H #include <iostream> #include <memory> #include <exception> #include <vector> #include "Internal.hpp" extern "C" { #include "libyang.h" } /* defined */ class Context; class Error; class Set; /* used */ class Module; class Submodule; class Data_Node; class Schema_Node; class Schema_Node; class Xml_Elem; class Deleter; class Error { /* add custom deleter for Context class */ public: Error() { libyang_err = ly_errno; libyang_vecode = ly_vecode; libyang_errmsg = ly_errmsg(); libyang_errpath = ly_errpath(); libyang_errapptag = ly_errapptag(); }; ~Error() {}; LY_ERR err() throw() {return libyang_err;}; LY_VECODE vecode() throw() {return libyang_vecode;}; const char *errmsg() const throw() {return libyang_errmsg;}; const char *errpath() const throw() {return libyang_errpath;}; const char *errapptag() const throw() {return libyang_errapptag;}; private: LY_ERR libyang_err; LY_VECODE libyang_vecode; const char *libyang_errmsg; const char *libyang_errpath; const char *libyang_errapptag; }; class Context { public: Context(struct ly_ctx *ctx, S_Deleter deleter); Context(const char *search_dir = nullptr, int options = 0); Context(const char *search_dir, const char *path, LYD_FORMAT format, int options = 0); Context(const char *search_dir, LYD_FORMAT format, const char *data, int options = 0); ~Context(); int set_searchdir(const char *search_dir) {return ly_ctx_set_searchdir(ctx, search_dir);}; void unset_searchdirs(int idx) {return ly_ctx_unset_searchdirs(ctx, idx);}; std::vector<std::string> *get_searchdirs(); void set_allimplemented() {return ly_ctx_set_allimplemented(ctx);}; void unset_allimplemented() {return ly_ctx_unset_allimplemented(ctx);}; S_Data_Node info(); std::vector<S_Module> *get_module_iter(); std::vector<S_Module> *get_disabled_module_iter(); S_Module get_module(const char *name, const char *revision = nullptr, int implemented = 0); S_Module get_module_older(S_Module module); S_Module load_module(const char *name, const char *revision = nullptr); S_Module get_module_by_ns(const char *ns, const char *revision = nullptr, int implemented = 0); S_Submodule get_submodule(const char *module, const char *revision = nullptr, const char *submodule = nullptr, const char *sub_revision = nullptr); S_Submodule get_submodule2(S_Module main_module, const char *submodule = nullptr); S_Schema_Node get_node(S_Schema_Node start, const char *data_path, int output = 0); void clean(); /* functions */ S_Data_Node parse_mem(const char *data, LYD_FORMAT format, int options = 0); S_Data_Node parse_fd(int fd, LYD_FORMAT format, int options = 0); S_Data_Node parse_data_path(const char *path, LYD_FORMAT format, int options = 0); S_Data_Node parse_xml(S_Xml_Elem elem, int options = 0); S_Module parse_path(const char *path, LYS_INFORMAT format); friend Data_Node; friend Deleter; private: struct ly_ctx *ctx; S_Deleter deleter; }; class Set { public: Set(struct ly_set *set, S_Deleter); Set(); ~Set(); unsigned int size() {return set->size;}; unsigned int number() {return set->number;}; std::vector<S_Data_Node> *data(); std::vector<S_Schema_Node> *schema(); /* functions */ S_Set dup(); int add(S_Data_Node node, int options = 0); int add(S_Schema_Node node, int options = 0); int contains(S_Data_Node node); int contains(S_Schema_Node node); int clean(); int rm(S_Data_Node node); int rm(S_Schema_Node node); int rm_index(unsigned int index); private: struct ly_set *set; S_Deleter deleter; }; #endif <commit_msg>C++: add explicit to Context constructor<commit_after>/** * @file Libyang.hpp * @author Mislav Novakovic <mislav.novakovic@sartura.hr> * @brief Class implementation for libyang C header libyang.h. * * Copyright (c) 2017 Deutsche Telekom AG. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #ifndef LIBYANG_H #define LIBYANG_H #include <iostream> #include <memory> #include <exception> #include <vector> #include "Internal.hpp" extern "C" { #include "libyang.h" } /* defined */ class Context; class Error; class Set; /* used */ class Module; class Submodule; class Data_Node; class Schema_Node; class Schema_Node; class Xml_Elem; class Deleter; class Error { /* add custom deleter for Context class */ public: Error() { libyang_err = ly_errno; libyang_vecode = ly_vecode; libyang_errmsg = ly_errmsg(); libyang_errpath = ly_errpath(); libyang_errapptag = ly_errapptag(); }; ~Error() {}; LY_ERR err() throw() {return libyang_err;}; LY_VECODE vecode() throw() {return libyang_vecode;}; const char *errmsg() const throw() {return libyang_errmsg;}; const char *errpath() const throw() {return libyang_errpath;}; const char *errapptag() const throw() {return libyang_errapptag;}; private: LY_ERR libyang_err; LY_VECODE libyang_vecode; const char *libyang_errmsg; const char *libyang_errpath; const char *libyang_errapptag; }; class Context { public: Context(struct ly_ctx *ctx, S_Deleter deleter); explicit Context(const char *search_dir = nullptr, int options = 0); Context(const char *search_dir, const char *path, LYD_FORMAT format, int options = 0); Context(const char *search_dir, LYD_FORMAT format, const char *data, int options = 0); ~Context(); int set_searchdir(const char *search_dir) {return ly_ctx_set_searchdir(ctx, search_dir);}; void unset_searchdirs(int idx) {return ly_ctx_unset_searchdirs(ctx, idx);}; std::vector<std::string> *get_searchdirs(); void set_allimplemented() {return ly_ctx_set_allimplemented(ctx);}; void unset_allimplemented() {return ly_ctx_unset_allimplemented(ctx);}; S_Data_Node info(); std::vector<S_Module> *get_module_iter(); std::vector<S_Module> *get_disabled_module_iter(); S_Module get_module(const char *name, const char *revision = nullptr, int implemented = 0); S_Module get_module_older(S_Module module); S_Module load_module(const char *name, const char *revision = nullptr); S_Module get_module_by_ns(const char *ns, const char *revision = nullptr, int implemented = 0); S_Submodule get_submodule(const char *module, const char *revision = nullptr, const char *submodule = nullptr, const char *sub_revision = nullptr); S_Submodule get_submodule2(S_Module main_module, const char *submodule = nullptr); S_Schema_Node get_node(S_Schema_Node start, const char *data_path, int output = 0); void clean(); /* functions */ S_Data_Node parse_mem(const char *data, LYD_FORMAT format, int options = 0); S_Data_Node parse_fd(int fd, LYD_FORMAT format, int options = 0); S_Data_Node parse_data_path(const char *path, LYD_FORMAT format, int options = 0); S_Data_Node parse_xml(S_Xml_Elem elem, int options = 0); S_Module parse_path(const char *path, LYS_INFORMAT format); friend Data_Node; friend Deleter; private: struct ly_ctx *ctx; S_Deleter deleter; }; class Set { public: Set(struct ly_set *set, S_Deleter); Set(); ~Set(); unsigned int size() {return set->size;}; unsigned int number() {return set->number;}; std::vector<S_Data_Node> *data(); std::vector<S_Schema_Node> *schema(); /* functions */ S_Set dup(); int add(S_Data_Node node, int options = 0); int add(S_Schema_Node node, int options = 0); int contains(S_Data_Node node); int contains(S_Schema_Node node); int clean(); int rm(S_Data_Node node); int rm(S_Schema_Node node); int rm_index(unsigned int index); private: struct ly_set *set; S_Deleter deleter; }; #endif <|endoftext|>
<commit_before>#include <QtGui> #include <list> #include "Backends.h" #include "DTIDESplash.h" #include "DTIDEXMLProject.h" #include "DTIDE.h" extern "C" { #include <osutil.h> #include <bstring.h> #include <debug.h> #include <iio.h> #include <version.h> } int main(int argc, char** argv) { QApplication app(argc, argv); // Some set up required for toolchain to work. debug_setlevel(LEVEL_VERBOSE); osutil_setarg0(bautofree(bfromcstr(argv[0]))); isetmode(IMODE_BIG); // Show version information. version_print(bautofree(bfromcstr("IDE"))); // Project management. DTIDEXMLProject* p = new DTIDEXMLProject(); std::list<Toolchain*> toolchains; toolchains.insert(toolchains.end(), new DCPUToolchain()); if(argc == 2) p->read(argv[1]); else p->read("project.xml"); if(!p->loaded) { DTIDESplash* splash = new DTIDESplash(toolchains); if(!splash->exec()) return 0; p->setTitle(splash->projectTitle); p->addFile(splash->fileName, true); p->setToolchain(new DCPUToolchain()); } // Now start the IDE. DTIDE mainWindow(p); mainWindow.show(); int returncode = app.exec(); return returncode; } <commit_msg>Automatically append filename if user doesn't supply one<commit_after>#include <QtGui> #include <list> #include "Backends.h" #include "DTIDESplash.h" #include "DTIDEXMLProject.h" #include "DTIDE.h" extern "C" { #include <osutil.h> #include <bstring.h> #include <debug.h> #include <iio.h> #include <version.h> } int main(int argc, char** argv) { QApplication app(argc, argv); // Some set up required for toolchain to work. debug_setlevel(LEVEL_VERBOSE); osutil_setarg0(bautofree(bfromcstr(argv[0]))); isetmode(IMODE_BIG); // Show version information. version_print(bautofree(bfromcstr("IDE"))); // Project management. DTIDEXMLProject* p = new DTIDEXMLProject(); std::list<Toolchain*> toolchains; toolchains.insert(toolchains.end(), new DCPUToolchain()); if(argc == 2) p->read(argv[1]); else p->read("project.xml"); if(!p->loaded) { DTIDESplash* splash = new DTIDESplash(toolchains); if(!splash->exec()) return 0; QString fileName = splash->fileName; QStringList parts = fileName.split("."); if(parts.count() < 2) { fileName.append(".dasm"); } p->setTitle(splash->projectTitle); p->addFile(fileName, true); p->setToolchain(new DCPUToolchain()); } // Now start the IDE. DTIDE mainWindow(p); mainWindow.show(); int returncode = app.exec(); return returncode; } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/micro/micro_error_reporter.h" #include "tensorflow/lite/micro/micro_string.h" namespace tflite { namespace { constexpr int kMaxLogLen = 256; } // namespace int MicroErrorReporter::Report(const char* format, va_list args) { char log_buffer[kMaxLogLen]; MicroVsnprintf(log_buffer, kMaxLogLen, format, args); DebugLog(log_buffer); DebugLog("\r\n"); return 0; } } // namespace tflite <commit_msg>Extra ifdefs to be more confident that we do not have unnecessary bloat.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/micro/micro_error_reporter.h" #ifndef TF_LITE_STRIP_ERROR_STRINGS #include "tensorflow/lite/micro/micro_string.h" #endif namespace tflite { int MicroErrorReporter::Report(const char* format, va_list args) { #ifndef TF_LITE_STRIP_ERROR_STRINGS // Only pulling in the implementation of this function for builds where we // expect to make use of it to be extra cautious about not increasing the code // size. static constexpr int kMaxLogLen = 256; char log_buffer[kMaxLogLen]; MicroVsnprintf(log_buffer, kMaxLogLen, format, args); DebugLog(log_buffer); DebugLog("\r\n"); #endif return 0; } } // namespace tflite <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkItkImageFileReader.h" #include "mitkConfig.h" #include <itkImageFileReader.h> #include <itksys/SystemTools.hxx> #include <itksys/Directory.hxx> #include <itkImage.h> //#include <itkImageSeriesReader.h> #include <itkImageFileReader.h> #include <itkImageIOFactory.h> #include <itkImageIORegion.h> //#include <itkImageSeriesReader.h> //#include <itkDICOMImageIO2.h> //#include <itkDICOMSeriesFileNames.h> //#include <itkGDCMImageIO.h> //#include <itkGDCMSeriesFileNames.h> //#include <itkNumericSeriesFileNames.h> void mitk::ItkImageFileReader::GenerateData() { mitk::Image::Pointer image = this->GetOutput(); const unsigned int MINDIM = 2; const unsigned int MAXDIM = 4; std::cout << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl; // Check to see if we can read the file given the name or prefix if ( m_FileName == "" ) { itkWarningMacro( << "File Type not supported!" ); return ; } if ( m_FileName == "--no-server" ) { return ; } itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( m_FileName.c_str(), itk::ImageIOFactory::ReadMode ); if ( imageIO.IsNull() ) { itkWarningMacro( << "File Type not supported!" ); return ; } // Got to allocate space for the image. Determine the characteristics of // the image. imageIO->SetFileName( m_FileName.c_str() ); imageIO->ReadImageInformation(); unsigned int ndim = imageIO->GetNumberOfDimensions(); if ( ndim < MINDIM || ndim > MAXDIM ) { itkWarningMacro( << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D." ); ndim = MAXDIM; } itk::ImageIORegion ioRegion( ndim ); itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize(); itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); unsigned int dimensions[ MAXDIM ]; dimensions[ 0 ] = 0; dimensions[ 1 ] = 0; dimensions[ 2 ] = 0; dimensions[ 3 ] = 0; float spacing[ MAXDIM ]; spacing[ 0 ] = 1.0f; spacing[ 1 ] = 1.0f; spacing[ 2 ] = 1.0f; spacing[ 3 ] = 1.0f; Point3D origin; origin.Fill(0); for ( unsigned int i = 0; i < ndim ; ++i ) { ioStart[ i ] = 0; ioSize[ i ] = imageIO->GetDimensions( i ); if(i<MAXDIM) { dimensions[ i ] = imageIO->GetDimensions( i ); spacing[ i ] = imageIO->GetSpacing( i ); if(spacing[ i ] <= 0) spacing[ i ] = 1.0f; } if(i<3) { origin[ i ] = imageIO->GetOrigin( i ); } } ioRegion.SetSize( ioSize ); ioRegion.SetIndex( ioStart ); std::cout << "ioRegion: " << ioRegion << std::endl; imageIO->SetIORegion( ioRegion ); void* buffer = malloc( imageIO->GetImageSizeInBytes() ); imageIO->Read( buffer ); //mitk::Image::Pointer image = mitk::Image::New(); if((ndim==4) && (dimensions[3]<=1)) ndim = 3; if((ndim==3) && (dimensions[2]<=1)) ndim = 2; #if ITK_VERSION_MAJOR == 2 || ( ITK_VERSION_MAJOR == 1 && ITK_VERSION_MINOR > 6 ) mitk::PixelType pixelType( imageIO->GetComponentTypeInfo(), imageIO->GetNumberOfComponents() ); image->Initialize( pixelType, ndim, dimensions ); #else if ( imageIO->GetNumberOfComponents() > 1) itkWarningMacro(<<"For older itk versions, only scalar images are supported!"); mitk::PixelType pixelType( imageIO->GetPixelType() ); image->Initialize( pixelType, ndim, dimensions ); #endif image->SetVolume( buffer ); image->GetSlicedGeometry()->SetOrigin( origin ); image->GetSlicedGeometry()->SetSpacing( spacing ); image->GetTimeSlicedGeometry()->InitializeEvenlyTimed(image->GetSlicedGeometry(), image->GetDimension(3)); free( buffer ); buffer = NULL; std::cout << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl; // mitk::DataTreeNode::Pointer node = this->GetOutput(); // node->SetData( image ); // add level-window property //if ( image->GetPixelType().GetNumberOfComponents() == 1 ) //{ // SetDefaultImageProperties( node ); //} std::cout << "...finished!" << std::endl; } bool mitk::ItkImageFileReader::CanReadFile(const std::string filename, const std::string /*filePrefix*/, const std::string /*filePattern*/) { // First check the extension if( filename == "" ) return false; itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( filename.c_str(), itk::ImageIOFactory::ReadMode ); if ( imageIO.IsNull() ) return false; return true; } mitk::ItkImageFileReader::ItkImageFileReader() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") { } mitk::ItkImageFileReader::~ItkImageFileReader() { } <commit_msg>added: check if image is serie<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkItkImageFileReader.h" #include "mitkConfig.h" #include <itkImageFileReader.h> #include <itksys/SystemTools.hxx> #include <itksys/Directory.hxx> #include <itkImage.h> //#include <itkImageSeriesReader.h> #include <itkImageFileReader.h> #include <itkImageIOFactory.h> #include <itkImageIORegion.h> //#include <itkImageSeriesReader.h> //#include <itkDICOMImageIO2.h> //#include <itkDICOMSeriesFileNames.h> //#include <itkGDCMImageIO.h> //#include <itkGDCMSeriesFileNames.h> //#include <itkNumericSeriesFileNames.h> void mitk::ItkImageFileReader::GenerateData() { mitk::Image::Pointer image = this->GetOutput(); const unsigned int MINDIM = 2; const unsigned int MAXDIM = 4; std::cout << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl; // Check to see if we can read the file given the name or prefix if ( m_FileName == "" ) { itkWarningMacro( << "File Type not supported!" ); return ; } if ( m_FileName == "--no-server" ) { return ; } itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( m_FileName.c_str(), itk::ImageIOFactory::ReadMode ); if ( imageIO.IsNull() ) { itkWarningMacro( << "File Type not supported!" ); return ; } // Got to allocate space for the image. Determine the characteristics of // the image. imageIO->SetFileName( m_FileName.c_str() ); imageIO->ReadImageInformation(); unsigned int ndim = imageIO->GetNumberOfDimensions(); if ( ndim < MINDIM || ndim > MAXDIM ) { itkWarningMacro( << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D." ); ndim = MAXDIM; } itk::ImageIORegion ioRegion( ndim ); itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize(); itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); unsigned int dimensions[ MAXDIM ]; dimensions[ 0 ] = 0; dimensions[ 1 ] = 0; dimensions[ 2 ] = 0; dimensions[ 3 ] = 0; float spacing[ MAXDIM ]; spacing[ 0 ] = 1.0f; spacing[ 1 ] = 1.0f; spacing[ 2 ] = 1.0f; spacing[ 3 ] = 1.0f; Point3D origin; origin.Fill(0); for ( unsigned int i = 0; i < ndim ; ++i ) { ioStart[ i ] = 0; ioSize[ i ] = imageIO->GetDimensions( i ); if(i<MAXDIM) { dimensions[ i ] = imageIO->GetDimensions( i ); spacing[ i ] = imageIO->GetSpacing( i ); if(spacing[ i ] <= 0) spacing[ i ] = 1.0f; } if(i<3) { origin[ i ] = imageIO->GetOrigin( i ); } } ioRegion.SetSize( ioSize ); ioRegion.SetIndex( ioStart ); std::cout << "ioRegion: " << ioRegion << std::endl; imageIO->SetIORegion( ioRegion ); void* buffer = malloc( imageIO->GetImageSizeInBytes() ); imageIO->Read( buffer ); //mitk::Image::Pointer image = mitk::Image::New(); if((ndim==4) && (dimensions[3]<=1)) ndim = 3; if((ndim==3) && (dimensions[2]<=1)) ndim = 2; #if ITK_VERSION_MAJOR == 2 || ( ITK_VERSION_MAJOR == 1 && ITK_VERSION_MINOR > 6 ) mitk::PixelType pixelType( imageIO->GetComponentTypeInfo(), imageIO->GetNumberOfComponents() ); image->Initialize( pixelType, ndim, dimensions ); #else if ( imageIO->GetNumberOfComponents() > 1) itkWarningMacro(<<"For older itk versions, only scalar images are supported!"); mitk::PixelType pixelType( imageIO->GetPixelType() ); image->Initialize( pixelType, ndim, dimensions ); #endif image->SetVolume( buffer ); image->GetSlicedGeometry()->SetOrigin( origin ); image->GetSlicedGeometry()->SetSpacing( spacing ); image->GetTimeSlicedGeometry()->InitializeEvenlyTimed(image->GetSlicedGeometry(), image->GetDimension(3)); free( buffer ); buffer = NULL; std::cout << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl; // mitk::DataTreeNode::Pointer node = this->GetOutput(); // node->SetData( image ); // add level-window property //if ( image->GetPixelType().GetNumberOfComponents() == 1 ) //{ // SetDefaultImageProperties( node ); //} std::cout << "...finished!" << std::endl; } bool mitk::ItkImageFileReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern) { // First check the extension if( filename == "" ) return false; // check if image is serie if( filePattern != "" && filePrefix != "" ) return false; itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( filename.c_str(), itk::ImageIOFactory::ReadMode ); if ( imageIO.IsNull() ) return false; return true; } mitk::ItkImageFileReader::ItkImageFileReader() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") { } mitk::ItkImageFileReader::~ItkImageFileReader() { } <|endoftext|>
<commit_before>#pragma once #include "Skeleton.h" namespace DEM::Anim { void CSkeleton::SetRootNode(Scene::CSceneNode* pNode) { if (_Nodes.empty()) { if (pNode) _Nodes.push_back(pNode); } else _Nodes[0] = pNode; //!!!could rebind instead of invalidating! //!!!to rebind, needs to remember name+parent when port is created! for (size_t i = 1; i < _Nodes.size(); ++i) _Nodes[i] = nullptr; } //--------------------------------------------------------------------- U16 CSkeleton::BindNode(CStrID NodeID, U16 ParentPort) { // Return root port is no parent is specified if (ParentPort == InvalidPort) return _Nodes.empty() ? InvalidPort : 0; const Scene::CSceneNode* pParent = _Nodes[ParentPort].Get(); if (!pParent) return InvalidPort; Scene::CSceneNode* pNode = pParent->GetChild(NodeID); if (!pNode) return InvalidPort; // Check if this node is already bound to some port auto It = std::find(_Nodes.cbegin(), _Nodes.cend(), pNode); if (It != _Nodes.cend()) return static_cast<U16>(std::distance(_Nodes.cbegin(), It)); // Create new port, if not _Nodes.push_back(pNode); return static_cast<U16>(_Nodes.size() - 1); } //--------------------------------------------------------------------- bool CSkeleton::IsPortActive(U16 Port) const { return _Nodes.size() > Port && _Nodes[Port] && _Nodes[Port]->IsActive(); } //--------------------------------------------------------------------- void CSkeleton::SetScale(U16 Port, const vector3& Scale) { _Nodes[Port]->SetLocalScale(Scale); } //--------------------------------------------------------------------- void CSkeleton::SetRotation(U16 Port, const quaternion& Rotation) { _Nodes[Port]->SetLocalRotation(Rotation); } //--------------------------------------------------------------------- void CSkeleton::SetTranslation(U16 Port, const vector3& Translation) { _Nodes[Port]->SetLocalPosition(Translation); } //--------------------------------------------------------------------- void CSkeleton::SetTransform(U16 Port, const Math::CTransformSRT& Tfm) { _Nodes[Port]->SetLocalTransform(Tfm); } //--------------------------------------------------------------------- } <commit_msg>Binding nodes by path from root if no parent is defined (for animated nodes with not animated parents)<commit_after>#pragma once #include "Skeleton.h" namespace DEM::Anim { void CSkeleton::SetRootNode(Scene::CSceneNode* pNode) { if (_Nodes.empty()) { if (pNode) _Nodes.push_back(pNode); } else _Nodes[0] = pNode; //!!!could rebind instead of invalidating! //!!!to rebind, needs to remember name+parent when port is created! for (size_t i = 1; i < _Nodes.size(); ++i) _Nodes[i] = nullptr; } //--------------------------------------------------------------------- U16 CSkeleton::BindNode(CStrID NodeID, U16 ParentPort) { // Root must be set before binding other nodes if (_Nodes.empty() || !_Nodes[0]) return InvalidPort; Scene::CSceneNode* pNode = nullptr; if (ParentPort == InvalidPort) { // When no parent specified, we search by path from the root node. // Empty path is the root node itself, and root port is always 0. // FIXME: either require name matching or always store empty ID for clip root in DEM ACL files! if (!NodeID || NodeID == _Nodes[0]->GetName()) return 0; pNode = _Nodes[0]->FindNodeByPath(NodeID.CStr()); } else if (auto pParent = _Nodes[ParentPort].Get()) { // When parent is specified, the node is its direct child pNode = pParent->GetChild(NodeID); } if (!pNode) return InvalidPort; // Check if this node is already bound to some port auto It = std::find(_Nodes.cbegin(), _Nodes.cend(), pNode); if (It != _Nodes.cend()) return static_cast<U16>(std::distance(_Nodes.cbegin(), It)); // Create new port, if not _Nodes.push_back(pNode); return static_cast<U16>(_Nodes.size() - 1); } //--------------------------------------------------------------------- bool CSkeleton::IsPortActive(U16 Port) const { return _Nodes.size() > Port && _Nodes[Port] && _Nodes[Port]->IsActive(); } //--------------------------------------------------------------------- void CSkeleton::SetScale(U16 Port, const vector3& Scale) { _Nodes[Port]->SetLocalScale(Scale); } //--------------------------------------------------------------------- void CSkeleton::SetRotation(U16 Port, const quaternion& Rotation) { _Nodes[Port]->SetLocalRotation(Rotation); } //--------------------------------------------------------------------- void CSkeleton::SetTranslation(U16 Port, const vector3& Translation) { _Nodes[Port]->SetLocalPosition(Translation); } //--------------------------------------------------------------------- void CSkeleton::SetTransform(U16 Port, const Math::CTransformSRT& Tfm) { _Nodes[Port]->SetLocalTransform(Tfm); } //--------------------------------------------------------------------- } <|endoftext|>
<commit_before>#ifndef BNI_BP_HPP #define BNI_BP_HPP #include <functional> #include "graph.hpp" namespace bn { class bp { public: typedef std::unordered_map<vertex_type, matrix_type> return_type; explicit bp(graph_t const& graph); virtual ~bp() = default; inline return_type operator()() { std::unordered_map<vertex_type, matrix_type> const precondition; return operator()(precondition); } return_type operator()(std::unordered_map<vertex_type, matrix_type> const& precondition); private: void initialize(); void calculate_pi(vertex_type const& target); void calculate_pi_i(vertex_type const& from, vertex_type const& target); void calculate_lambda(vertex_type const& target); void calculate_lambda_k(vertex_type const& from, vertex_type const& target); // 与えられた確率変数全ての組み合わせに対し,functionを実行するというインターフェースを提供する void all_combination_pattern( std::vector<vertex_type> const& combination, std::function<void(condition_t const&)> const& function ) const; matrix_type& normalize(matrix_type& target) const; bool is_preconditional_node(vertex_type const& node) const; graph_t const graph_; std::unordered_map<vertex_type, matrix_type> pi_; std::unordered_map<vertex_type, matrix_type> lambda_; std::unordered_map<vertex_type, std::unordered_map<vertex_type, matrix_type>> pi_i_; std::unordered_map<vertex_type, std::unordered_map<vertex_type, matrix_type>> lambda_k_; std::vector<vertex_type> preconditional_node_; std::unordered_map<vertex_type, matrix_type> new_pi_; std::unordered_map<vertex_type, matrix_type> new_lambda_; std::unordered_map<vertex_type, std::unordered_map<vertex_type, matrix_type>> new_pi_i_; std::unordered_map<vertex_type, std::unordered_map<vertex_type, matrix_type>> new_lambda_k_; }; } // namespace bn #endif // #ifndef BNI_BP_HPP <commit_msg>Add Comment to header.<commit_after>#ifndef BNI_BP_HPP #define BNI_BP_HPP #include <functional> #include "graph.hpp" namespace bn { class bp { public: typedef std::unordered_map<vertex_type, matrix_type> return_type; explicit bp(graph_t const& graph); virtual ~bp() = default; // By-pass inline return_type operator()() { std::unordered_map<vertex_type, matrix_type> const precondition; return operator()(precondition); } // Run: Loopy Belief Propagation return_type operator()(std::unordered_map<vertex_type, matrix_type> const& precondition); private: void initialize(); void calculate_pi(vertex_type const& target); void calculate_pi_i(vertex_type const& from, vertex_type const& target); void calculate_lambda(vertex_type const& target); void calculate_lambda_k(vertex_type const& from, vertex_type const& target); // 与えられた確率変数全ての組み合わせに対し,functionを実行するというインターフェースを提供する void all_combination_pattern( std::vector<vertex_type> const& combination, std::function<void(condition_t const&)> const& function ) const; // matrixに存在するすべての数の和が1になるように正規化する matrix_type& normalize(matrix_type& target) const; // 引数のノードが事前条件ノードであるかどうか確認する bool is_preconditional_node(vertex_type const& node) const; graph_t const graph_; std::vector<vertex_type> preconditional_node_; // 現在のメッセージ状況 std::unordered_map<vertex_type, matrix_type> pi_; std::unordered_map<vertex_type, matrix_type> lambda_; std::unordered_map<vertex_type, std::unordered_map<vertex_type, matrix_type>> pi_i_; std::unordered_map<vertex_type, std::unordered_map<vertex_type, matrix_type>> lambda_k_; // 未来のメッセージ状況 std::unordered_map<vertex_type, matrix_type> new_pi_; std::unordered_map<vertex_type, matrix_type> new_lambda_; std::unordered_map<vertex_type, std::unordered_map<vertex_type, matrix_type>> new_pi_i_; std::unordered_map<vertex_type, std::unordered_map<vertex_type, matrix_type>> new_lambda_k_; }; } // namespace bn #endif // #ifndef BNI_BP_HPP <|endoftext|>
<commit_before>#include "mesh_config.h" // C++ includes #include <iostream> #include <vector> #include <string> #ifdef HAVE_GETOPT_H // GCC 2.95.3 (and maybe others) do not include // getopt.h in unistd.h... Hower IBM xlC has no // getopt.h! This works around that. #include <getopt.h> #endif #include <stdio.h> #include <fstream> // Local Includes #include "libmesh.h" #include "equation_systems.h" #include "mesh.h" #include "perfmon.h" #include "enum_xdr_mode.h" /** * how to use this, and command line processor */ void usage(char *progName) { std::string baseName; static std::string helpList = "usage:\n" " %s [options] ...\n" "\n" "options:\n" " -d <dim> <dim>-dimensional mesh\n" " -m <string> Mesh file name\n" " -l <string> Left Equation Systems file name\n" " -r <string> Right Equation Systems file name\n" " -t <float> threshold\n" " -a ASCII format (default)\n" " -b binary format\n" " -v Verbose\n" " -q really quiet\n" " -h Print help menu\n" "\n" "\n" " This program is used to compare equation systems to a user-specified\n" " threshold. Equation systems are imported in the libMesh format\n" " provided through the read and write methods in class EquationSystems.\n" " \n" " ./compare -d 3 -m grid.xda -l leftfile.dat -r rightfile.dat -b -t 1.e-8\n" "\n" " will read in the mesh grid.xda, the equation systems leftfile.dat and\n" " rightfile.dat in binary format and compare systems, and especially the\n" " floats stored in vectors. The comparison is said to be passed when the\n" " floating point values agree up to the given threshold. When no threshold\n" " is set the default libMesh tolerance is used. If neither -a or -b are set,\n" " ASCII format is assumed.\n" "\n" " Direct questions to:\n" " benkirk@cfdlab.ae.utexas.edu\n"; if (progName == NULL) baseName = "UNKNOWN"; else baseName = progName; fprintf(stderr, helpList.c_str(), baseName.c_str()); fflush(stderr); abort(); }; void process_cmd_line(int argc, char **argv, std::vector<std::string>& names, unsigned int& dim, double& threshold, libMeshEnums::XdrMODE& format, bool& verbose, bool& quiet) { char optionStr[] = "d:m:l:r:t:abvq?h"; int opt; bool format_set = false; bool left_name_set = false; if (argc < 3) usage(argv[0]); while ((opt = getopt(argc, argv, optionStr)) != -1) { switch (opt) { /** * Get mesh file name */ case 'm': { if (names.empty()) names.push_back(optarg); else { std::cout << "ERROR: Mesh file name must preceed left file name!" << std::endl; exit(1); } break; } /** * Get the mesh dimension */ case 'd': { dim = atoi(optarg); break; } /** * Get left file name */ case 'l': { if (!left_name_set) { names.push_back(optarg); left_name_set = true; } else { std::cout << "ERROR: Mesh file name must preceed right file name!" << std::endl; exit(1); } break; } /** * Get right file name */ case 'r': { if ((!names.empty()) && (left_name_set)) names.push_back(optarg); else { std::cout << "ERROR: Mesh file name and left file name must preceed " << "right file name!" << std::endl; exit(1); } break; } /** * Get the comparison threshold */ case 't': { threshold = atof(optarg); break; } /** * Use ascii format */ case 'a': { if (format_set) { std::cout << "ERROR: Equation system file format already set!" << std::endl; exit(1); } else { format = libMeshEnums::READ; format_set = true; } break; } /** * Use binary format */ case 'b': { if (format_set) { std::cout << "ERROR: Equation system file format already set!" << std::endl; exit(1); } else { format = libMeshEnums::DECODE; format_set = true; } break; } /** * Be verbose */ case 'v': { verbose = true; break; } /** * Be totally quiet, no matter what -v says */ case 'q': { quiet = true; break; } case 'h': case '?': usage(argv[0]); default: return; } } } /** * everything that is identical for the systems, and * should _not_ go into EquationSystems::compare(), * can go in this do_compare(). */ bool do_compare (EquationSystems& les, EquationSystems& res, double threshold, bool verbose) { if (verbose) { std::cout << "********* LEFT SYSTEM *********" << std::endl; les.print_info (); std::cout << "********* RIGHT SYSTEM *********" << std::endl; res.print_info (); std::cout << "********* COMPARISON PHASE *********" << std::endl << std::endl; } /** * start comparing */ bool result = les.compare(res, threshold, verbose); if (verbose) { std::cout << "********* FINISHED *********" << std::endl; } return result; } int main (int argc, char** argv) { libMesh::init (argc, argv); // these should better be not contained in the following braces bool quiet = false; bool are_equal; { PerfMon perfmon(argv[0]); // default values std::vector<std::string> names; unsigned int dim = static_cast<unsigned int>(-1); double threshold = TOLERANCE; libMeshEnums::XdrMODE format = libMeshEnums::READ; bool verbose = false; // get commands process_cmd_line(argc, argv, names, dim, threshold, format, verbose, quiet); if (dim == static_cast<unsigned int>(-1)) { std::cout << "ERROR: you must specify the dimension on " << "the command line!\n\n" << argv[0] << " -d 3 ... for example\n\n"; error(); } if (quiet) verbose = false; if (verbose) { std::cout << "Settings:" << std::endl << " dimensionality = " << dim << std::endl << " mesh = " << names[0] << std::endl << " left system = " << names[1] << std::endl << " right system = " << names[2] << std::endl << " threshold = " << threshold << std::endl << " read format = " << format << std::endl << std::endl; } /** * build the left and right mesh for left, inut them */ Mesh left_mesh (dim); Mesh right_mesh (dim); if (!names.empty()) { left_mesh.read (names[0]); right_mesh.read (names[0]); if (verbose) left_mesh.print_info(); } else { std::cout << "No input specified." << std::endl; return 1; } /** * build EquationSystems objects, read them */ EquationSystems left_system (left_mesh); EquationSystems right_system (right_mesh); if (names.size() == 3) { left_system.read (names[1], format); right_system.read (names[2], format); } else { std::cout << "Bad input specified." << std::endl; error(); } are_equal = do_compare (left_system, right_system, threshold, verbose); } /** * let's see what do_compare found out */ unsigned int our_result; if (are_equal) { if (!quiet) std::cout << std::endl << " Congrat's, up to the defined threshold, the two" << std::endl << " are identical." << std::endl; our_result=0; } else { if (!quiet) std::cout << std::endl << " Oops, differences occured!" << std::endl << " Use -v to obtain more information where differences occured." << std::endl; our_result=1; } // return libMesh::close(); return our_result; } <commit_msg>include file changed name<commit_after>#include "libmesh_config.h" // C++ includes #include <iostream> #include <vector> #include <string> #ifdef HAVE_GETOPT_H // GCC 2.95.3 (and maybe others) do not include // getopt.h in unistd.h... Hower IBM xlC has no // getopt.h! This works around that. #include <getopt.h> #endif #include <stdio.h> #include <fstream> // Local Includes #include "libmesh.h" #include "equation_systems.h" #include "mesh.h" #include "perfmon.h" #include "enum_xdr_mode.h" /** * how to use this, and command line processor */ void usage(char *progName) { std::string baseName; static std::string helpList = "usage:\n" " %s [options] ...\n" "\n" "options:\n" " -d <dim> <dim>-dimensional mesh\n" " -m <string> Mesh file name\n" " -l <string> Left Equation Systems file name\n" " -r <string> Right Equation Systems file name\n" " -t <float> threshold\n" " -a ASCII format (default)\n" " -b binary format\n" " -v Verbose\n" " -q really quiet\n" " -h Print help menu\n" "\n" "\n" " This program is used to compare equation systems to a user-specified\n" " threshold. Equation systems are imported in the libMesh format\n" " provided through the read and write methods in class EquationSystems.\n" " \n" " ./compare -d 3 -m grid.xda -l leftfile.dat -r rightfile.dat -b -t 1.e-8\n" "\n" " will read in the mesh grid.xda, the equation systems leftfile.dat and\n" " rightfile.dat in binary format and compare systems, and especially the\n" " floats stored in vectors. The comparison is said to be passed when the\n" " floating point values agree up to the given threshold. When no threshold\n" " is set the default libMesh tolerance is used. If neither -a or -b are set,\n" " ASCII format is assumed.\n" "\n" " Direct questions to:\n" " benkirk@cfdlab.ae.utexas.edu\n"; if (progName == NULL) baseName = "UNKNOWN"; else baseName = progName; fprintf(stderr, helpList.c_str(), baseName.c_str()); fflush(stderr); abort(); }; void process_cmd_line(int argc, char **argv, std::vector<std::string>& names, unsigned int& dim, double& threshold, libMeshEnums::XdrMODE& format, bool& verbose, bool& quiet) { char optionStr[] = "d:m:l:r:t:abvq?h"; int opt; bool format_set = false; bool left_name_set = false; if (argc < 3) usage(argv[0]); while ((opt = getopt(argc, argv, optionStr)) != -1) { switch (opt) { /** * Get mesh file name */ case 'm': { if (names.empty()) names.push_back(optarg); else { std::cout << "ERROR: Mesh file name must preceed left file name!" << std::endl; exit(1); } break; } /** * Get the mesh dimension */ case 'd': { dim = atoi(optarg); break; } /** * Get left file name */ case 'l': { if (!left_name_set) { names.push_back(optarg); left_name_set = true; } else { std::cout << "ERROR: Mesh file name must preceed right file name!" << std::endl; exit(1); } break; } /** * Get right file name */ case 'r': { if ((!names.empty()) && (left_name_set)) names.push_back(optarg); else { std::cout << "ERROR: Mesh file name and left file name must preceed " << "right file name!" << std::endl; exit(1); } break; } /** * Get the comparison threshold */ case 't': { threshold = atof(optarg); break; } /** * Use ascii format */ case 'a': { if (format_set) { std::cout << "ERROR: Equation system file format already set!" << std::endl; exit(1); } else { format = libMeshEnums::READ; format_set = true; } break; } /** * Use binary format */ case 'b': { if (format_set) { std::cout << "ERROR: Equation system file format already set!" << std::endl; exit(1); } else { format = libMeshEnums::DECODE; format_set = true; } break; } /** * Be verbose */ case 'v': { verbose = true; break; } /** * Be totally quiet, no matter what -v says */ case 'q': { quiet = true; break; } case 'h': case '?': usage(argv[0]); default: return; } } } /** * everything that is identical for the systems, and * should _not_ go into EquationSystems::compare(), * can go in this do_compare(). */ bool do_compare (EquationSystems& les, EquationSystems& res, double threshold, bool verbose) { if (verbose) { std::cout << "********* LEFT SYSTEM *********" << std::endl; les.print_info (); std::cout << "********* RIGHT SYSTEM *********" << std::endl; res.print_info (); std::cout << "********* COMPARISON PHASE *********" << std::endl << std::endl; } /** * start comparing */ bool result = les.compare(res, threshold, verbose); if (verbose) { std::cout << "********* FINISHED *********" << std::endl; } return result; } int main (int argc, char** argv) { libMesh::init (argc, argv); // these should better be not contained in the following braces bool quiet = false; bool are_equal; { PerfMon perfmon(argv[0]); // default values std::vector<std::string> names; unsigned int dim = static_cast<unsigned int>(-1); double threshold = TOLERANCE; libMeshEnums::XdrMODE format = libMeshEnums::READ; bool verbose = false; // get commands process_cmd_line(argc, argv, names, dim, threshold, format, verbose, quiet); if (dim == static_cast<unsigned int>(-1)) { std::cout << "ERROR: you must specify the dimension on " << "the command line!\n\n" << argv[0] << " -d 3 ... for example\n\n"; error(); } if (quiet) verbose = false; if (verbose) { std::cout << "Settings:" << std::endl << " dimensionality = " << dim << std::endl << " mesh = " << names[0] << std::endl << " left system = " << names[1] << std::endl << " right system = " << names[2] << std::endl << " threshold = " << threshold << std::endl << " read format = " << format << std::endl << std::endl; } /** * build the left and right mesh for left, inut them */ Mesh left_mesh (dim); Mesh right_mesh (dim); if (!names.empty()) { left_mesh.read (names[0]); right_mesh.read (names[0]); if (verbose) left_mesh.print_info(); } else { std::cout << "No input specified." << std::endl; return 1; } /** * build EquationSystems objects, read them */ EquationSystems left_system (left_mesh); EquationSystems right_system (right_mesh); if (names.size() == 3) { left_system.read (names[1], format); right_system.read (names[2], format); } else { std::cout << "Bad input specified." << std::endl; error(); } are_equal = do_compare (left_system, right_system, threshold, verbose); } /** * let's see what do_compare found out */ unsigned int our_result; if (are_equal) { if (!quiet) std::cout << std::endl << " Congrat's, up to the defined threshold, the two" << std::endl << " are identical." << std::endl; our_result=0; } else { if (!quiet) std::cout << std::endl << " Oops, differences occured!" << std::endl << " Use -v to obtain more information where differences occured." << std::endl; our_result=1; } // return libMesh::close(); return our_result; } <|endoftext|>
<commit_before>#include "PlaceholderParser.hpp" #include <cstring> #include <ctime> #include <iomanip> #include <sstream> #ifdef _MSC_VER #include <stdlib.h> // provides **_environ #else #include <unistd.h> // provides **environ #endif #ifdef __APPLE__ #include <crt_externs.h> #undef environ #define environ (*_NSGetEnviron()) #else #ifdef _MSC_VER #define environ _environ #else extern char **environ; #endif #endif namespace Slic3r { PlaceholderParser::PlaceholderParser() { this->set("version", SLIC3R_VERSION); this->apply_env_variables(); this->update_timestamp(); } void PlaceholderParser::update_timestamp() { time_t rawtime; time(&rawtime); struct tm* timeinfo = localtime(&rawtime); { std::ostringstream ss; ss << (1900 + timeinfo->tm_year); ss << std::setw(2) << std::setfill('0') << (1 + timeinfo->tm_mon); ss << std::setw(2) << std::setfill('0') << timeinfo->tm_mday; ss << "-"; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_hour; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_min; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_sec; this->set("timestamp", ss.str()); } this->set("year", 1900 + timeinfo->tm_year); this->set("month", 1 + timeinfo->tm_mon); this->set("day", timeinfo->tm_mday); this->set("hour", timeinfo->tm_hour); this->set("minute", timeinfo->tm_min); this->set("second", timeinfo->tm_sec); } void PlaceholderParser::apply_config(const DynamicPrintConfig &config) { t_config_option_keys opt_keys = config.keys(); for (t_config_option_keys::const_iterator i = opt_keys.begin(); i != opt_keys.end(); ++i) { const t_config_option_key &opt_key = *i; const ConfigOptionDef* def = config.def->get(opt_key); if (def->multiline) continue; const ConfigOption* opt = config.option(opt_key); if (const ConfigOptionVectorBase* optv = dynamic_cast<const ConfigOptionVectorBase*>(opt)) { // set placeholders for options with multiple values // TODO: treat [bed_shape] as single, not multiple this->set(opt_key, optv->vserialize()); } else if (const ConfigOptionPoint* optp = dynamic_cast<const ConfigOptionPoint*>(opt)) { this->set(opt_key, optp->serialize()); Pointf val = *optp; this->set(opt_key + "_X", val.x); this->set(opt_key + "_Y", val.y); } else { // set single-value placeholders this->set(opt_key, opt->serialize()); } } } void PlaceholderParser::apply_env_variables() { for (char** env = environ; *env; env++) { if (strncmp(*env, "SLIC3R_", 7) == 0) { std::stringstream ss(*env); std::string key, value; std::getline(ss, key, '='); ss >> value; this->set(key, value); } } } void PlaceholderParser::set(const std::string &key, const std::string &value) { this->_single[key] = value; this->_multiple.erase(key); } void PlaceholderParser::set(const std::string &key, int value) { std::ostringstream ss; ss << value; this->set(key, ss.str()); } void PlaceholderParser::set(const std::string &key, std::vector<std::string> values) { if (values.empty()) { this->_multiple.erase(key); this->_single.erase(key); } else { this->_multiple[key] = values; this->_single[key] = values.front(); } } std::string PlaceholderParser::process(std::string str) const { // replace single options, like [foo] for (t_strstr_map::const_iterator it = this->_single.begin(); it != this->_single.end(); ++it) { std::stringstream ss; ss << '[' << it->first << ']'; this->find_and_replace(str, ss.str(), it->second); } // replace multiple options like [foo_0] by looping until we have enough values // or until a previous match was found (this handles non-existing indices reasonably // without a regex) for (t_strstrs_map::const_iterator it = this->_multiple.begin(); it != this->_multiple.end(); ++it) { const std::vector<std::string> &values = it->second; bool found = false; for (size_t i = 0; (i < values.size()) || found; ++i) { std::stringstream ss; ss << '[' << it->first << '_' << i << ']'; if (i < values.size()) { found = this->find_and_replace(str, ss.str(), values[i]); } else { found = this->find_and_replace(str, ss.str(), values.front()); } } } return str; } bool PlaceholderParser::find_and_replace(std::string &source, std::string const &find, std::string const &replace) const { bool found = false; for (std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos; ) { source.replace(i, find.length(), replace); i += replace.length(); found = true; } return found; } } <commit_msg>Always format month/day/hour/second/minute placeholder variables out to their full width.<commit_after>#include "PlaceholderParser.hpp" #include <cstring> #include <ctime> #include <iomanip> #include <sstream> #ifdef _MSC_VER #include <stdlib.h> // provides **_environ #else #include <unistd.h> // provides **environ #endif #ifdef __APPLE__ #include <crt_externs.h> #undef environ #define environ (*_NSGetEnviron()) #else #ifdef _MSC_VER #define environ _environ #else extern char **environ; #endif #endif namespace Slic3r { PlaceholderParser::PlaceholderParser() { this->set("version", SLIC3R_VERSION); this->apply_env_variables(); this->update_timestamp(); } void PlaceholderParser::update_timestamp() { time_t rawtime; time(&rawtime); struct tm* timeinfo = localtime(&rawtime); this->set("year", 1900 + timeinfo->tm_year); { std::ostringstream ss; ss << std::setw(2) << std::setfill('0') << (1 + timeinfo->tm_mon); this->set("month", ss.str()); } { std::ostringstream ss; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_mday; this->set("day", ss.str()); } { std::ostringstream ss; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_hour; this->set("hour", ss.str()); } { std::ostringstream ss; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_min; this->set("minute", ss.str()); } { std::ostringstream ss; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_sec; this->set("second", ss.str()); } { std::ostringstream ss; ss << (1900 + timeinfo->tm_year); ss << this->_single["month"]; ss << this->_single["day"]; ss << "-"; ss << this->_single["hour"]; ss << this->_single["minute"]; ss << this->_single["second"]; this->set("timestamp", ss.str()); } } void PlaceholderParser::apply_config(const DynamicPrintConfig &config) { t_config_option_keys opt_keys = config.keys(); for (t_config_option_keys::const_iterator i = opt_keys.begin(); i != opt_keys.end(); ++i) { const t_config_option_key &opt_key = *i; const ConfigOptionDef* def = config.def->get(opt_key); if (def->multiline) continue; const ConfigOption* opt = config.option(opt_key); if (const ConfigOptionVectorBase* optv = dynamic_cast<const ConfigOptionVectorBase*>(opt)) { // set placeholders for options with multiple values // TODO: treat [bed_shape] as single, not multiple this->set(opt_key, optv->vserialize()); } else if (const ConfigOptionPoint* optp = dynamic_cast<const ConfigOptionPoint*>(opt)) { this->set(opt_key, optp->serialize()); Pointf val = *optp; this->set(opt_key + "_X", val.x); this->set(opt_key + "_Y", val.y); } else { // set single-value placeholders this->set(opt_key, opt->serialize()); } } } void PlaceholderParser::apply_env_variables() { for (char** env = environ; *env; env++) { if (strncmp(*env, "SLIC3R_", 7) == 0) { std::stringstream ss(*env); std::string key, value; std::getline(ss, key, '='); ss >> value; this->set(key, value); } } } void PlaceholderParser::set(const std::string &key, const std::string &value) { this->_single[key] = value; this->_multiple.erase(key); } void PlaceholderParser::set(const std::string &key, int value) { std::ostringstream ss; ss << value; this->set(key, ss.str()); } void PlaceholderParser::set(const std::string &key, std::vector<std::string> values) { if (values.empty()) { this->_multiple.erase(key); this->_single.erase(key); } else { this->_multiple[key] = values; this->_single[key] = values.front(); } } std::string PlaceholderParser::process(std::string str) const { // replace single options, like [foo] for (t_strstr_map::const_iterator it = this->_single.begin(); it != this->_single.end(); ++it) { std::stringstream ss; ss << '[' << it->first << ']'; this->find_and_replace(str, ss.str(), it->second); } // replace multiple options like [foo_0] by looping until we have enough values // or until a previous match was found (this handles non-existing indices reasonably // without a regex) for (t_strstrs_map::const_iterator it = this->_multiple.begin(); it != this->_multiple.end(); ++it) { const std::vector<std::string> &values = it->second; bool found = false; for (size_t i = 0; (i < values.size()) || found; ++i) { std::stringstream ss; ss << '[' << it->first << '_' << i << ']'; if (i < values.size()) { found = this->find_and_replace(str, ss.str(), values[i]); } else { found = this->find_and_replace(str, ss.str(), values.front()); } } } return str; } bool PlaceholderParser::find_and_replace(std::string &source, std::string const &find, std::string const &replace) const { bool found = false; for (std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos; ) { source.replace(i, find.length(), replace); i += replace.length(); found = true; } return found; } } <|endoftext|>
<commit_before>// // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // // // bench.cpp : spdlog benchmarks // #include "spdlog/async.h" #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/daily_file_sink.h" #include "spdlog/sinks/null_sink.h" #include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/spdlog.h" #include "utils.h" #include <atomic> #include <cstdlib> // EXIT_FAILURE #include <iostream> #include <memory> #include <string> #include <thread> using namespace std; using namespace std::chrono; using namespace spdlog; using namespace spdlog::sinks; using namespace utils; void bench(int howmany, std::shared_ptr<spdlog::logger> log); void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count); int main(int argc, char *argv[]) { int howmany = 1000000; int queue_size = howmany + 2; int threads = 10; int file_size = 30 * 1024 * 1024; int rotating_files = 5; try { if (argc > 1) howmany = atoi(argv[1]); if (argc > 2) threads = atoi(argv[2]); if (argc > 3) queue_size = atoi(argv[3]); cout << "*******************************************************************************\n"; cout << "Single thread, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true); bench(howmany, basic_st); auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files); bench(howmany, rotating_st); auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log"); bench(howmany, daily_st); bench(howmany, spdlog::create<null_sink_st>("null_st")); cout << "\n*******************************************************************************\n"; cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true); bench_mt(howmany, basic_mt, threads); auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files); bench_mt(howmany, rotating_mt, threads); auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log"); bench_mt(howmany, daily_mt, threads); bench_mt(howmany, spdlog::create<null_sink_mt>("null_mt")); cout << "\n*******************************************************************************\n"; cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl; cout << "*******************************************************************************\n"; for (int i = 0; i < 3; ++i) { spdlog::init_thread_pool(queue_size, 1); auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true); bench_mt(howmany, as, threads); spdlog::drop("async"); } } catch (std::exception &ex) { std::cerr << "Error: " << ex.what() << std::endl; perror("Last error"); return EXIT_FAILURE; } return EXIT_SUCCESS; } void bench(int howmany, std::shared_ptr<spdlog::logger> log) { using std::chrono::high_resolution_clock; cout << log->name() << "...\t\t" << flush; auto start = high_resolution_clock::now(); for (auto i = 0; i < howmany; ++i) { log->info("Hello logger: msg number {}", i); } auto delta = high_resolution_clock::now() - start; auto delta_d = duration_cast<duration<double>>(delta).count(); cout << "Elapsed: " << delta_d << "\t" << format(int(howmany / delta_d)) << "/sec" << endl; } void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count) { using std::chrono::high_resolution_clock; cout << log->name() << "...\t\t" << flush; vector<thread> threads; auto start = high_resolution_clock::now(); for (int t = 0; t < thread_count; ++t) { threads.push_back(std::thread([&]() { for (int j = 0; j < howmany / thread_count; j++) { log->info("Hello logger: msg number {}", j); } })); } for (auto &t : threads) { t.join(); }; auto delta = high_resolution_clock::now() - start; auto delta_d = duration_cast<duration<double>>(delta).count(); cout << "Elapsed: " << delta_d << "\t" << format(int(howmany / delta_d)) << "/sec" << endl; } <commit_msg>Fixed bench<commit_after>// // Copyright(c) 2015 Gabi Melman. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // // // bench.cpp : spdlog benchmarks // #include "spdlog/async.h" #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/daily_file_sink.h" #include "spdlog/sinks/null_sink.h" #include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/spdlog.h" #include "utils.h" #include <atomic> #include <cstdlib> // EXIT_FAILURE #include <iostream> #include <memory> #include <string> #include <thread> using namespace std; using namespace std::chrono; using namespace spdlog; using namespace spdlog::sinks; using namespace utils; void bench(int howmany, std::shared_ptr<spdlog::logger> log); void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count); int main(int argc, char *argv[]) { int howmany = 1000000; int queue_size = howmany + 2; int threads = 10; int file_size = 30 * 1024 * 1024; int rotating_files = 5; try { if (argc > 1) howmany = atoi(argv[1]); if (argc > 2) threads = atoi(argv[2]); if (argc > 3) queue_size = atoi(argv[3]); cout << "*******************************************************************************\n"; cout << "Single thread, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true); bench(howmany, basic_st); auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files); bench(howmany, rotating_st); auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log"); bench(howmany, daily_st); bench(howmany, spdlog::create<null_sink_st>("null_st")); cout << "\n*******************************************************************************\n"; cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl; cout << "*******************************************************************************\n"; auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true); bench_mt(howmany, basic_mt, threads); auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files); bench_mt(howmany, rotating_mt, threads); auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log"); bench_mt(howmany, daily_mt, threads); bench_mt(howmany, spdlog::create<null_sink_mt>("null_mt"), threads); cout << "\n*******************************************************************************\n"; cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl; cout << "*******************************************************************************\n"; for (int i = 0; i < 3; ++i) { spdlog::init_thread_pool(queue_size, 1); auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true); bench_mt(howmany, as, threads); spdlog::drop("async"); } } catch (std::exception &ex) { std::cerr << "Error: " << ex.what() << std::endl; perror("Last error"); return EXIT_FAILURE; } return EXIT_SUCCESS; } void bench(int howmany, std::shared_ptr<spdlog::logger> log) { using std::chrono::high_resolution_clock; cout << log->name() << "...\t\t" << flush; auto start = high_resolution_clock::now(); for (auto i = 0; i < howmany; ++i) { log->info("Hello logger: msg number {}", i); } auto delta = high_resolution_clock::now() - start; auto delta_d = duration_cast<duration<double>>(delta).count(); cout << "Elapsed: " << delta_d << "\t" << format(int(howmany / delta_d)) << "/sec" << endl; spdlog::drop(log->name()); } void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count) { using std::chrono::high_resolution_clock; cout << log->name() << "...\t\t" << flush; vector<thread> threads; auto start = high_resolution_clock::now(); for (int t = 0; t < thread_count; ++t) { threads.push_back(std::thread([&]() { for (int j = 0; j < howmany / thread_count; j++) { log->info("Hello logger: msg number {}", j); } })); } for (auto &t : threads) { t.join(); }; auto delta = high_resolution_clock::now() - start; auto delta_d = duration_cast<duration<double>>(delta).count(); cout << "Elapsed: " << delta_d << "\t" << format(int(howmany / delta_d)) << "/sec" << endl; } <|endoftext|>
<commit_before>// // Copyright (C) 2020 Gareth Jones, Glysade LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <ctime> #include <limits> #ifdef RDK_BUILD_THREADSAFE_SSS #include <future> #endif #include <assert.h> #include "RGroupGa.h" #include "RGroupDecompData.h" #include "RGroupDecomp.h" #include "RGroupFingerprintScore.h" #include "../../../External/GA/util/Util.h" // #define DEBUG namespace RDKit { RGroupDecompositionChromosome::RGroupDecompositionChromosome(RGroupGa& rGroupGa) : IntegerStringChromosome(rGroupGa.chromosomeLength(), rGroupGa.getRng(), rGroupGa.getChromosomePolicy()), rGroupGa(rGroupGa) { permutation.reserve(rGroupGa.numberDecompositions()); } std::string RGroupDecompositionChromosome::info() const { auto format = boost::format("Fit %7.3f : ") % fitness; return format.str() + geneInfo(); } double RGroupDecompositionChromosome::score() { auto& rGroupData = rGroupGa.getRGroupData(); RGroupScore scoreMethod = static_cast<RGroupScore>(rGroupData.params.scoreMethod); if (operationName != RgroupMutate) { decode(); } if (scoreMethod == FingerprintVariance && fingerprintVarianceScoreData.labelsToVarianceData.size() > 0 && operationName == RgroupMutate) { fitness = fingerprintVarianceScoreData.fingerprintVarianceGroupScore(); // Uncomment the following line to check that the // fingerprintVarianceGroupScore is giving the correct result. Don't do // this in production as it will be extremely slow. // assert(fitness == recalculateScore()); } else { fitness = rGroupData.score(permutation, &fingerprintVarianceScoreData); } return fitness; } double RGroupDecompositionChromosome::recalculateScore() { auto& rGroupData = rGroupGa.getRGroupData(); return rGroupData.score(permutation); } void RGroupDecompositionChromosome::decode() { auto values = getString(); permutation.clear(); const auto& matches = rGroupGa.getRGroupData().matches; auto pos = 0; for (const auto& m : matches) { if (m.size() == 1) { permutation.push_back(0); } else { permutation.push_back(values[pos]); pos++; } } } void RGroupDecompositionChromosome::copyGene( const StringChromosomeBase<int, IntegerStringChromosomePolicy>& other) { StringChromosomeBase<int, IntegerStringChromosomePolicy>::copyGene(other); const auto& parent = static_cast<const RGroupDecompositionChromosome&>(other); copyVarianceData(parent.fingerprintVarianceScoreData, fingerprintVarianceScoreData); } GaResult& GaResult::operator=(const GaResult& other) { if (&other == this) { return *this; } rGroupScorer = other.rGroupScorer; return *this; } RGroupGa::RGroupGa(const RGroupDecompData& rGroupData, const chrono::steady_clock::time_point* const t0) : rGroupData(rGroupData), chromosomePolicy(getRng(), rGroupData.matches.size()), t0(t0) { setSelectionPressure(1.0001); const auto& matches = rGroupData.matches; numPermutations = 1L; auto pos = 0; for (auto m : matches) { if (m.size() == 1) { continue; } chromosomePolicy.setMax(pos, m.size()); unsigned long count = numPermutations * m.size(); numPermutations = count / m.size() == numPermutations ? count : numeric_limits<unsigned int>::max(); pos++; } chromLength = pos; numberDecomps = matches.size(); // TODO refine these settings auto popsize = 100 + chromLength / 10; if (popsize > 200) { popsize = 200; } const auto& params = rGroupData.params; if (params.gaPopulationSize > 0) { popsize = params.gaPopulationSize; } // For now run the GA a long time and exit early if no improvement in the // score is seen numberOperations = 1000000; if (params.gaMaximumOperations > 0) { numberOperations = params.gaMaximumOperations; } numberOperationsWithoutImprovement = 7500; if (params.gaNumberOperationsWithoutImprovement > 0) { numberOperationsWithoutImprovement = params.gaNumberOperationsWithoutImprovement; } setPopsize(popsize); uint32_t rngSeed; if (params.gaRandomSeed >= 0) { rngSeed = params.gaRandomSeed; getRng().seed(rngSeed); } else if (params.gaRandomSeed == -2) { random_device rd; auto seed = rd(); rngSeed = seed; getRng().seed(rngSeed); } else { rngSeed = mt19937::default_seed; } BOOST_LOG(rdInfoLog) << "GA RNG seed " << rngSeed << endl; } void RGroupGa::rGroupMutateOperation( const std::vector<std::shared_ptr<RGroupDecompositionChromosome>>& parents, std::vector<std::shared_ptr<RGroupDecompositionChromosome>>& children) { auto parent = parents[0]; auto child = children[0]; child->copyGene(*parent); child->mutate(); child->setOperationName(RgroupMutate); child->decode(); auto& fingerprintVarianceScoreData = child->getFingerprintVarianceScoreData(); if (fingerprintVarianceScoreData.labelsToVarianceData.size() == 0) { return; } #ifdef DEBUG std::cerr << "RGroup mutate start" << std::endl; #endif #ifdef DEBUG std::cerr << "Starting child score" << std::endl; fingerprintVarianceGroupScore(fingerprintVarianceScoreData); #endif auto& parentPermutation = parent->getPermutation(); auto& childPermutation = child->getPermutation(); const auto& rgroupData = parent->getRGroupGA().getRGroupData(); const auto& matches = rgroupData.matches; const auto& labels = rgroupData.labels; for (auto pos = 0U; pos < parentPermutation.size(); pos++) { int parentValue = parentPermutation.at(pos); int childValue = childPermutation.at(pos); if (parentValue != childValue) { fingerprintVarianceScoreData.removeVarianceData(pos, parentValue, matches, labels); #ifdef DEBUG std::cerr << "After removing parent" << std::endl; fingerprintVarianceGroupScore(fingerprintVarianceScoreData); #endif fingerprintVarianceScoreData.addVarianceData(pos, childValue, matches, labels); #ifdef DEBUG std::cerr << "After adding child" << std::endl; fingerprintVarianceGroupScore(fingerprintVarianceScoreData); #endif } } #ifdef DEBUG std::cerr << "Final recalculating" << std::endl; child->recalculateScore(); std::cerr << "RGroup mutate done" << std::endl; #endif } void RGroupGa::rGroupCrossoverOperation( const std::vector<std::shared_ptr<RGroupDecompositionChromosome>>& parents, std::vector<std::shared_ptr<RGroupDecompositionChromosome>>& children) { auto parent1 = parents[0]; auto child1 = children[0]; auto parent2 = parents[1]; auto child2 = children[1]; child1->setOperationName(Crossover); child2->setOperationName(Crossover); clearVarianceData(child1->getFingerprintVarianceScoreData()); clearVarianceData(child2->getFingerprintVarianceScoreData()); parent1->twoPointCrossover(*parent2, *child1, *child2); } const vector<shared_ptr<GaOperation<RGroupDecompositionChromosome>>> RGroupGa::getOperations() const { // bias to mutation as that operator is so efficient auto mutationOperation = make_shared<GaOperation<RGroupDecompositionChromosome>>( 1, 1, 75.0, &rGroupMutateOperation); auto crossoverOperation = make_shared<GaOperation<RGroupDecompositionChromosome>>( 2, 2, 25.0, &rGroupCrossoverOperation); vector<shared_ptr<GaOperation<RGroupDecompositionChromosome>>> operations; operations.reserve(2); operations.push_back(mutationOperation); operations.push_back(crossoverOperation); return operations; } std::string timeInfo(const std::clock_t start) { auto now = std::clock(); auto seconds = (now - start) / (double)CLOCKS_PER_SEC; auto format = boost::format("Time %7.2f") % seconds; return format.str(); } GaResult RGroupGa::run(int runNumber) { auto startTime = clock(); RGroupGaPopulation population{*this}; auto format = boost::format( "Running GA run %2d number operations %5d population size %5d " "number operations without improvement %5d " "chromosome length %5d %s\n") % runNumber % numberOperations % getPopsize() % numberOperationsWithoutImprovement % chromLength % timeInfo(startTime); BOOST_LOG(rdInfoLog) << format.str(); population.create(); double bestScore = population.getBestScore(); BOOST_LOG(rdInfoLog) << population.info() << endl; int nOps = 0; int lastImprovementOp = 0; while (nOps < numberOperations) { population.iterate(); nOps++; if (nOps % 1000 == 0) { BOOST_LOG(rdInfoLog) << "Run " << runNumber << " " << population.info() << " " << timeInfo(startTime) << endl; } if (population.getBestScore() > bestScore) { bestScore = population.getBestScore(); lastImprovementOp = nOps; auto format = boost::format("Run %2d OP %5d Fit %7.3f %s\n") % runNumber % nOps % bestScore % timeInfo(startTime); BOOST_LOG(rdInfoLog) << format.str(); } if (nOps - lastImprovementOp > numberOperationsWithoutImprovement) { BOOST_LOG(rdInfoLog) << "Run " << runNumber << " Op " << nOps << " No improvement since " << lastImprovementOp << " finishing.." << endl; break; } if (t0 && checkForTimeout(*t0, rGroupData.params.timeout)) { break; } } const shared_ptr<RGroupDecompositionChromosome> best = population.getBest(); auto ties = population.getTiedBest(); vector<vector<size_t>> permutations; permutations.reserve(ties.size()); std::transform(ties.cbegin(), ties.cend(), back_inserter(permutations), [](const shared_ptr<RGroupDecompositionChromosome> c) { return c->getPermutation(); }); BOOST_LOG(rdInfoLog) << "Run " << runNumber << " Execution " << timeInfo(startTime) << std::endl; GaResult result{best->getFitness(), permutations}; return result; } vector<GaResult> RGroupGa::runBatch() { int numberRuns = rGroupData.params.gaNumberRuns; bool gaParallelRuns = rGroupData.params.gaParallelRuns; #ifndef RDK_BUILD_THREADSAFE_SSS if (gaParallelRuns) { gaParallelRuns = false; BOOST_LOG(rdWarningLog) << "This RDKit build does not enable GA parallel runs" << std::endl; } #endif vector<GaResult> results; results.reserve(numberRuns); if (gaParallelRuns) { #ifdef RDK_BUILD_THREADSAFE_SSS vector<future<GaResult>> tasks; tasks.reserve(numberRuns); for (int n = 0; n < numberRuns; n++) { auto future = async(launch::async, &RDKit::RGroupGa::run, this, n + 1); tasks.push_back(move(future)); } std::transform(tasks.begin(), tasks.end(), back_inserter(results), [](future<GaResult>& f) { return f.get(); }); #endif } else { for (int n = 0; n < numberRuns; n++) { auto result = run(n + 1); results.push_back(result); } } return results; } shared_ptr<RGroupDecompositionChromosome> RGroupGa::createChromosome() { return make_shared<RGroupDecompositionChromosome>(*this); } void copyVarianceData(const FingerprintVarianceScoreData& fromData, FingerprintVarianceScoreData& toData) { auto& from = fromData.labelsToVarianceData; auto& to = toData.labelsToVarianceData; for (auto it = from.cbegin(); it != from.end(); ++it) { auto df = to.find(it->first); if (df == to.end()) { to.emplace(it->first, make_shared<VarianceDataForLabel>(*it->second)); } else { auto& fromData = it->second; auto& toData = df->second; toData->numberFingerprints = fromData->numberFingerprints; toData->bitCounts.assign(fromData->bitCounts.cbegin(), fromData->bitCounts.cend()); } } toData.numberOfMolecules = fromData.numberOfMolecules; toData.numberOfMissingUserRGroups = fromData.numberOfMissingUserRGroups; } void clearVarianceData( FingerprintVarianceScoreData& fingerprintVarianceScoreData) { auto& data = fingerprintVarianceScoreData.labelsToVarianceData; for (auto it = data.begin(); it != data.end(); ++it) { auto d = it->second; d->numberFingerprints = 0; d->bitCounts.assign(d->bitCounts.size(), 0.0); } fingerprintVarianceScoreData.numberOfMissingUserRGroups = 0; fingerprintVarianceScoreData.numberOfMolecules = 0; } } // namespace RDKit <commit_msg>Fix integer overflow in RGroupDecomposition strategy GA (#5460)<commit_after>// // Copyright (C) 2020 Gareth Jones, Glysade LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <ctime> #include <limits> #ifdef RDK_BUILD_THREADSAFE_SSS #include <future> #endif #include <assert.h> #include "RGroupGa.h" #include "RGroupDecompData.h" #include "RGroupDecomp.h" #include "RGroupFingerprintScore.h" #include "../../../External/GA/util/Util.h" // #define DEBUG namespace RDKit { RGroupDecompositionChromosome::RGroupDecompositionChromosome(RGroupGa& rGroupGa) : IntegerStringChromosome(rGroupGa.chromosomeLength(), rGroupGa.getRng(), rGroupGa.getChromosomePolicy()), rGroupGa(rGroupGa) { permutation.reserve(rGroupGa.numberDecompositions()); } std::string RGroupDecompositionChromosome::info() const { auto format = boost::format("Fit %7.3f : ") % fitness; return format.str() + geneInfo(); } double RGroupDecompositionChromosome::score() { auto& rGroupData = rGroupGa.getRGroupData(); RGroupScore scoreMethod = static_cast<RGroupScore>(rGroupData.params.scoreMethod); if (operationName != RgroupMutate) { decode(); } if (scoreMethod == FingerprintVariance && fingerprintVarianceScoreData.labelsToVarianceData.size() > 0 && operationName == RgroupMutate) { fitness = fingerprintVarianceScoreData.fingerprintVarianceGroupScore(); // Uncomment the following line to check that the // fingerprintVarianceGroupScore is giving the correct result. Don't do // this in production as it will be extremely slow. // assert(fitness == recalculateScore()); } else { fitness = rGroupData.score(permutation, &fingerprintVarianceScoreData); } return fitness; } double RGroupDecompositionChromosome::recalculateScore() { auto& rGroupData = rGroupGa.getRGroupData(); return rGroupData.score(permutation); } void RGroupDecompositionChromosome::decode() { auto values = getString(); permutation.clear(); const auto& matches = rGroupGa.getRGroupData().matches; auto pos = 0; for (const auto& m : matches) { if (m.size() == 1) { permutation.push_back(0); } else { permutation.push_back(values[pos]); pos++; } } } void RGroupDecompositionChromosome::copyGene( const StringChromosomeBase<int, IntegerStringChromosomePolicy>& other) { StringChromosomeBase<int, IntegerStringChromosomePolicy>::copyGene(other); const auto& parent = static_cast<const RGroupDecompositionChromosome&>(other); copyVarianceData(parent.fingerprintVarianceScoreData, fingerprintVarianceScoreData); } GaResult& GaResult::operator=(const GaResult& other) { if (&other == this) { return *this; } rGroupScorer = other.rGroupScorer; return *this; } RGroupGa::RGroupGa(const RGroupDecompData& rGroupData, const chrono::steady_clock::time_point* const t0) : rGroupData(rGroupData), chromosomePolicy(getRng(), rGroupData.matches.size()), t0(t0) { setSelectionPressure(1.0001); const auto& matches = rGroupData.matches; numPermutations = 1L; auto pos = 0; for (auto m : matches) { if (m.size() == 1) { continue; } chromosomePolicy.setMax(pos, m.size()); unsigned long count = numPermutations * m.size(); numPermutations = std::min(count, static_cast<unsigned long>(numeric_limits<unsigned int>::max())); pos++; } chromLength = pos; numberDecomps = matches.size(); // TODO refine these settings auto popsize = 100 + chromLength / 10; if (popsize > 200) { popsize = 200; } const auto& params = rGroupData.params; if (params.gaPopulationSize > 0) { popsize = params.gaPopulationSize; } // For now run the GA a long time and exit early if no improvement in the // score is seen numberOperations = 1000000; if (params.gaMaximumOperations > 0) { numberOperations = params.gaMaximumOperations; } numberOperationsWithoutImprovement = 7500; if (params.gaNumberOperationsWithoutImprovement > 0) { numberOperationsWithoutImprovement = params.gaNumberOperationsWithoutImprovement; } setPopsize(popsize); uint32_t rngSeed; if (params.gaRandomSeed >= 0) { rngSeed = params.gaRandomSeed; getRng().seed(rngSeed); } else if (params.gaRandomSeed == -2) { random_device rd; auto seed = rd(); rngSeed = seed; getRng().seed(rngSeed); } else { rngSeed = mt19937::default_seed; } BOOST_LOG(rdInfoLog) << "GA RNG seed " << rngSeed << endl; } void RGroupGa::rGroupMutateOperation( const std::vector<std::shared_ptr<RGroupDecompositionChromosome>>& parents, std::vector<std::shared_ptr<RGroupDecompositionChromosome>>& children) { auto parent = parents[0]; auto child = children[0]; child->copyGene(*parent); child->mutate(); child->setOperationName(RgroupMutate); child->decode(); auto& fingerprintVarianceScoreData = child->getFingerprintVarianceScoreData(); if (fingerprintVarianceScoreData.labelsToVarianceData.size() == 0) { return; } #ifdef DEBUG std::cerr << "RGroup mutate start" << std::endl; #endif #ifdef DEBUG std::cerr << "Starting child score" << std::endl; fingerprintVarianceGroupScore(fingerprintVarianceScoreData); #endif auto& parentPermutation = parent->getPermutation(); auto& childPermutation = child->getPermutation(); const auto& rgroupData = parent->getRGroupGA().getRGroupData(); const auto& matches = rgroupData.matches; const auto& labels = rgroupData.labels; for (auto pos = 0U; pos < parentPermutation.size(); pos++) { int parentValue = parentPermutation.at(pos); int childValue = childPermutation.at(pos); if (parentValue != childValue) { fingerprintVarianceScoreData.removeVarianceData(pos, parentValue, matches, labels); #ifdef DEBUG std::cerr << "After removing parent" << std::endl; fingerprintVarianceGroupScore(fingerprintVarianceScoreData); #endif fingerprintVarianceScoreData.addVarianceData(pos, childValue, matches, labels); #ifdef DEBUG std::cerr << "After adding child" << std::endl; fingerprintVarianceGroupScore(fingerprintVarianceScoreData); #endif } } #ifdef DEBUG std::cerr << "Final recalculating" << std::endl; child->recalculateScore(); std::cerr << "RGroup mutate done" << std::endl; #endif } void RGroupGa::rGroupCrossoverOperation( const std::vector<std::shared_ptr<RGroupDecompositionChromosome>>& parents, std::vector<std::shared_ptr<RGroupDecompositionChromosome>>& children) { auto parent1 = parents[0]; auto child1 = children[0]; auto parent2 = parents[1]; auto child2 = children[1]; child1->setOperationName(Crossover); child2->setOperationName(Crossover); clearVarianceData(child1->getFingerprintVarianceScoreData()); clearVarianceData(child2->getFingerprintVarianceScoreData()); parent1->twoPointCrossover(*parent2, *child1, *child2); } const vector<shared_ptr<GaOperation<RGroupDecompositionChromosome>>> RGroupGa::getOperations() const { // bias to mutation as that operator is so efficient auto mutationOperation = make_shared<GaOperation<RGroupDecompositionChromosome>>( 1, 1, 75.0, &rGroupMutateOperation); auto crossoverOperation = make_shared<GaOperation<RGroupDecompositionChromosome>>( 2, 2, 25.0, &rGroupCrossoverOperation); vector<shared_ptr<GaOperation<RGroupDecompositionChromosome>>> operations; operations.reserve(2); operations.push_back(mutationOperation); operations.push_back(crossoverOperation); return operations; } std::string timeInfo(const std::clock_t start) { auto now = std::clock(); auto seconds = (now - start) / (double)CLOCKS_PER_SEC; auto format = boost::format("Time %7.2f") % seconds; return format.str(); } GaResult RGroupGa::run(int runNumber) { auto startTime = clock(); RGroupGaPopulation population{*this}; auto format = boost::format( "Running GA run %2d number operations %5d population size %5d " "number operations without improvement %5d " "chromosome length %5d %s\n") % runNumber % numberOperations % getPopsize() % numberOperationsWithoutImprovement % chromLength % timeInfo(startTime); BOOST_LOG(rdInfoLog) << format.str(); population.create(); double bestScore = population.getBestScore(); BOOST_LOG(rdInfoLog) << population.info() << endl; int nOps = 0; int lastImprovementOp = 0; while (nOps < numberOperations) { population.iterate(); nOps++; if (nOps % 1000 == 0) { BOOST_LOG(rdInfoLog) << "Run " << runNumber << " " << population.info() << " " << timeInfo(startTime) << endl; } if (population.getBestScore() > bestScore) { bestScore = population.getBestScore(); lastImprovementOp = nOps; auto format = boost::format("Run %2d OP %5d Fit %7.3f %s\n") % runNumber % nOps % bestScore % timeInfo(startTime); BOOST_LOG(rdInfoLog) << format.str(); } if (nOps - lastImprovementOp > numberOperationsWithoutImprovement) { BOOST_LOG(rdInfoLog) << "Run " << runNumber << " Op " << nOps << " No improvement since " << lastImprovementOp << " finishing.." << endl; break; } if (t0 && checkForTimeout(*t0, rGroupData.params.timeout)) { break; } } const shared_ptr<RGroupDecompositionChromosome> best = population.getBest(); auto ties = population.getTiedBest(); vector<vector<size_t>> permutations; permutations.reserve(ties.size()); std::transform(ties.cbegin(), ties.cend(), back_inserter(permutations), [](const shared_ptr<RGroupDecompositionChromosome> c) { return c->getPermutation(); }); BOOST_LOG(rdInfoLog) << "Run " << runNumber << " Execution " << timeInfo(startTime) << std::endl; GaResult result{best->getFitness(), permutations}; return result; } vector<GaResult> RGroupGa::runBatch() { int numberRuns = rGroupData.params.gaNumberRuns; bool gaParallelRuns = rGroupData.params.gaParallelRuns; #ifndef RDK_BUILD_THREADSAFE_SSS if (gaParallelRuns) { gaParallelRuns = false; BOOST_LOG(rdWarningLog) << "This RDKit build does not enable GA parallel runs" << std::endl; } #endif vector<GaResult> results; results.reserve(numberRuns); if (gaParallelRuns) { #ifdef RDK_BUILD_THREADSAFE_SSS vector<future<GaResult>> tasks; tasks.reserve(numberRuns); for (int n = 0; n < numberRuns; n++) { auto future = async(launch::async, &RDKit::RGroupGa::run, this, n + 1); tasks.push_back(move(future)); } std::transform(tasks.begin(), tasks.end(), back_inserter(results), [](future<GaResult>& f) { return f.get(); }); #endif } else { for (int n = 0; n < numberRuns; n++) { auto result = run(n + 1); results.push_back(result); } } return results; } shared_ptr<RGroupDecompositionChromosome> RGroupGa::createChromosome() { return make_shared<RGroupDecompositionChromosome>(*this); } void copyVarianceData(const FingerprintVarianceScoreData& fromData, FingerprintVarianceScoreData& toData) { auto& from = fromData.labelsToVarianceData; auto& to = toData.labelsToVarianceData; for (auto it = from.cbegin(); it != from.end(); ++it) { auto df = to.find(it->first); if (df == to.end()) { to.emplace(it->first, make_shared<VarianceDataForLabel>(*it->second)); } else { auto& fromData = it->second; auto& toData = df->second; toData->numberFingerprints = fromData->numberFingerprints; toData->bitCounts.assign(fromData->bitCounts.cbegin(), fromData->bitCounts.cend()); } } toData.numberOfMolecules = fromData.numberOfMolecules; toData.numberOfMissingUserRGroups = fromData.numberOfMissingUserRGroups; } void clearVarianceData( FingerprintVarianceScoreData& fingerprintVarianceScoreData) { auto& data = fingerprintVarianceScoreData.labelsToVarianceData; for (auto it = data.begin(); it != data.end(); ++it) { auto d = it->second; d->numberFingerprints = 0; d->bitCounts.assign(d->bitCounts.size(), 0.0); } fingerprintVarianceScoreData.numberOfMissingUserRGroups = 0; fingerprintVarianceScoreData.numberOfMolecules = 0; } } // namespace RDKit <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <time.h> #include <vector> using namespace std; vector <string> arr1 {"Ye are ", "Yer mum be ", "Yer mummy be "}; vector <string> arr2 {"a fowl ", "a wretched ", "a scurvy-lovin' ", "a land-lovin\' "}; vector <string> arr3 {"scallywag!", "blubber!", "whale!", "buffoon!", "kraken!"}; int main() { srand(time(NULL)); cout << arr1.at(rand() % arr1.size()) << arr2.at(rand() % arr2.size()) << arr3.at(rand() % arr3.size()); cout << endl; return 0; } <commit_msg>added to generator<commit_after>#include <iostream> #include <stdlib.h> #include <time.h> #include <vector> using namespace std; vector <string> arr1 {"Ye be ", "Yer mum be ", "Yer mummy be ", "Yer crew be ", "Yer ship be ", "Yer lassy be ", "Yer lad be "}; vector <string> arr2 {"a fowl ", "a wretched ", "a scurvy-lovin' ", "a land-lovin\' ", "a good fer nothin\' ", "a lily-livered ", "a yellow bellied ", "a barnacle bottomed ", "a barnacle lovin\' ", "a mermaid marryin\' ", "a thievin\' "}; vector <string> arr3 {"scallywag!", "blubber!", "whale!", "buffoon!", "kraken!", "rascal!", "blaggard!", "milk maid!", "landlubber!", "sorry sea dog!", "salty swab!", "blowfish!", "swine!"}; int main() { srand(time(NULL)); cout << arr1.at(rand() % arr1.size()) << arr2.at(rand() % arr2.size()) << arr3.at(rand() % arr3.size()); cout << endl; return 0; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, 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 the copyright holder(s) 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. * * * \author Raphael Favier * */ #include <pcl/io/pcd_io.h> #include <pcl/common/time.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/visualization/point_cloud_handlers.h> #include <pcl/visualization/common/common.h> #include <pcl/octree/octree_pointcloud_voxelcentroid.h> #include <pcl/filters/filter.h> #include "boost.h" #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkCubeSource.h> //============================= // Displaying cubes is very long! // so we limit their numbers. const int MAX_DISPLAYED_CUBES(15000); //============================= class OctreeViewer { public: OctreeViewer (std::string &filename, double resolution) : viz ("Octree visualizator"), cloud (new pcl::PointCloud<pcl::PointXYZ>()), displayCloud (new pcl::PointCloud<pcl::PointXYZ>()), octree (resolution), displayCubes(false), showPointsWithCubes (false), wireframe (true) { //try to load the cloud if (!loadCloud(filename)) return; //register keyboard callbacks viz.registerKeyboardCallback(&OctreeViewer::keyboardEventOccurred, *this, 0); //key legends viz.addText("Keys:", 0, 170, 0.0, 1.0, 0.0, "keys_t"); viz.addText("a -> Increment displayed depth", 10, 155, 0.0, 1.0, 0.0, "key_a_t"); viz.addText("z -> Decrement displayed depth", 10, 140, 0.0, 1.0, 0.0, "key_z_t"); viz.addText("d -> Toggle Point/Cube representation", 10, 125, 0.0, 1.0, 0.0, "key_d_t"); viz.addText("x -> Show/Hide original cloud", 10, 110, 0.0, 1.0, 0.0, "key_x_t"); viz.addText("s/w -> Surface/Wireframe representation", 10, 95, 0.0, 1.0, 0.0, "key_sw_t"); //set current level to half the maximum one displayedDepth = static_cast<int> (floor (octree.getTreeDepth() / 2.0)); if (displayedDepth == 0) displayedDepth = 1; //show octree at default depth extractPointsAtLevel(displayedDepth); //reset camera viz.resetCameraViewpoint("cloud"); //run main loop run(); } private: //======================================================== // PRIVATE ATTRIBUTES //======================================================== //visualizer pcl::PointCloud<pcl::PointXYZ>::Ptr xyz; pcl::PointCloud<pcl::PointXYZRGB>::Ptr xyz_rgb; pcl::visualization::PCLVisualizer viz; //original cloud pcl::PointCloud<pcl::PointXYZ>::Ptr cloud; //displayed_cloud pcl::PointCloud<pcl::PointXYZ>::Ptr displayCloud; //octree pcl::octree::OctreePointCloudVoxelCentroid<pcl::PointXYZ> octree; //level int displayedDepth; //bool to decide if we display points or cubes bool displayCubes, showPointsWithCubes, wireframe; //======================================================== /* \brief Callback to interact with the keyboard * */ void keyboardEventOccurred(const pcl::visualization::KeyboardEvent &event, void *) { if (event.getKeySym() == "a" && event.keyDown()) { IncrementLevel(); } else if (event.getKeySym() == "z" && event.keyDown()) { DecrementLevel(); } else if (event.getKeySym() == "d" && event.keyDown()) { displayCubes = !displayCubes; update(); } else if (event.getKeySym() == "x" && event.keyDown()) { showPointsWithCubes = !showPointsWithCubes; update(); } else if (event.getKeySym() == "w" && event.keyDown()) { if(!wireframe) wireframe=true; update(); } else if (event.getKeySym() == "s" && event.keyDown()) { if(wireframe) wireframe=false; update(); } } /* \brief Graphic loop for the viewer * */ void run() { while (!viz.wasStopped()) { //main loop of the visualizer viz.spinOnce(100); boost::this_thread::sleep(boost::posix_time::microseconds(100000)); } } /* \brief Helper function that read a pointcloud file (returns false if pbl) * Also initialize the octree * */ bool loadCloud(std::string &filename) { std::cout << "Loading file " << filename.c_str() << std::endl; //read cloud if (pcl::io::loadPCDFile(filename, *cloud)) { std::cerr << "ERROR: Cannot open file " << filename << "! Aborting..." << std::endl; return false; } //remove NaN Points std::vector<int> nanIndexes; pcl::removeNaNFromPointCloud(*cloud, *cloud, nanIndexes); std::cout << "Loaded " << cloud->points.size() << " points" << std::endl; //create octree structure octree.setInputCloud(cloud); //update bounding box automatically octree.defineBoundingBox(); //add points in the tree octree.addPointsFromInputCloud(); return true; } /* \brief Helper function that draw info for the user on the viewer * */ void showLegend(bool showCubes) { char dataDisplay[256]; sprintf(dataDisplay, "Displaying data as %s", (showCubes) ? ("CUBES") : ("POINTS")); viz.removeShape("disp_t"); viz.addText(dataDisplay, 0, 60, 1.0, 0.0, 0.0, "disp_t"); char level[256]; sprintf(level, "Displayed depth is %d on %d", displayedDepth, octree.getTreeDepth()); viz.removeShape("level_t1"); viz.addText(level, 0, 45, 1.0, 0.0, 0.0, "level_t1"); viz.removeShape("level_t2"); sprintf(level, "Voxel size: %.4fm [%lu voxels]", sqrt(octree.getVoxelSquaredSideLen(displayedDepth)), displayCloud->points.size()); viz.addText(level, 0, 30, 1.0, 0.0, 0.0, "level_t2"); viz.removeShape("org_t"); if (showPointsWithCubes) viz.addText("Displaying original cloud", 0, 15, 1.0, 0.0, 0.0, "org_t"); } /* \brief Visual update. Create visualizations and add them to the viewer * */ void update() { //remove existing shapes from visualizer clearView(); //prevent the display of too many cubes bool displayCubeLegend = displayCubes && static_cast<int> (displayCloud->points.size ()) <= MAX_DISPLAYED_CUBES; showLegend(displayCubeLegend); if (displayCubeLegend) { //show octree as cubes showCubes(sqrt(octree.getVoxelSquaredSideLen(displayedDepth))); if (showPointsWithCubes) { //add original cloud in visualizer pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> color_handler(cloud, "z"); viz.addPointCloud(cloud, color_handler, "cloud"); } } else { //add current cloud in visualizer pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> color_handler(displayCloud,"z"); viz.addPointCloud(displayCloud, color_handler, "cloud"); } } /* \brief remove dynamic objects from the viewer * */ void clearView() { //remove cubes if any vtkRenderer *renderer = viz.getRenderWindow()->GetRenderers()->GetFirstRenderer(); while (renderer->GetActors()->GetNumberOfItems() > 0) renderer->RemoveActor(renderer->GetActors()->GetLastActor()); //remove point clouds if any viz.removePointCloud("cloud"); } /* \brief Create a vtkSmartPointer object containing a cube * */ vtkSmartPointer<vtkPolyData> GetCuboid(double minX, double maxX, double minY, double maxY, double minZ, double maxZ) { vtkSmartPointer<vtkCubeSource> cube = vtkSmartPointer<vtkCubeSource>::New(); cube->SetBounds(minX, maxX, minY, maxY, minZ, maxZ); return cube->GetOutput(); } /* \brief display octree cubes via vtk-functions * */ void showCubes(double voxelSideLen) { //get the renderer of the visualizer object vtkRenderer *renderer = viz.getRenderWindow()->GetRenderers()->GetFirstRenderer(); vtkSmartPointer<vtkAppendPolyData> treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New(); size_t i; double s = voxelSideLen / 2.0; for (i = 0; i < displayCloud->points.size(); i++) { double x = displayCloud->points[i].x; double y = displayCloud->points[i].y; double z = displayCloud->points[i].z; #if VTK_MAJOR_VERSION < 6 treeWireframe->AddInput(GetCuboid(x - s, x + s, y - s, y + s, z - s, z + s)); #else treeWireframe->AddInputData (GetCuboid (x - s, x + s, y - s, y + s, z - s, z + s)); #endif } vtkSmartPointer<vtkActor> treeActor = vtkSmartPointer<vtkActor>::New(); vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); #if VTK_MAJOR_VERSION < 6 mapper->SetInput(treeWireframe->GetOutput()); #else mapper->SetInputData (treeWireframe->GetOutput ()); #endif treeActor->SetMapper(mapper); treeActor->GetProperty()->SetColor(1.0, 1.0, 1.0); treeActor->GetProperty()->SetLineWidth(2); if(wireframe) { treeActor->GetProperty()->SetRepresentationToWireframe(); treeActor->GetProperty()->SetOpacity(0.35); } else treeActor->GetProperty()->SetRepresentationToSurface(); renderer->AddActor(treeActor); } /* \brief Extracts all the points of depth = level from the octree * */ void extractPointsAtLevel(int depth) { displayCloud->points.clear(); pcl::octree::OctreePointCloudVoxelCentroid<pcl::PointXYZ>::Iterator tree_it; pcl::octree::OctreePointCloudVoxelCentroid<pcl::PointXYZ>::Iterator tree_it_end = octree.end(); pcl::PointXYZ pt; std::cout << "===== Extracting data at depth " << depth << "... " << std::flush; double start = pcl::getTime (); for (tree_it = octree.begin(depth); tree_it!=tree_it_end; ++tree_it) { Eigen::Vector3f voxel_min, voxel_max; octree.getVoxelBounds(tree_it, voxel_min, voxel_max); pt.x = (voxel_min.x() + voxel_max.x()) / 2.0f; pt.y = (voxel_min.y() + voxel_max.y()) / 2.0f; pt.z = (voxel_min.z() + voxel_max.z()) / 2.0f; displayCloud->points.push_back(pt); } double end = pcl::getTime (); printf("%lu pts, %.4gs. %.4gs./pt. =====\n", displayCloud->points.size (), end - start, (end - start) / static_cast<double> (displayCloud->points.size ())); update(); } /* \brief Helper function to increase the octree display level by one * */ bool IncrementLevel() { if (displayedDepth < static_cast<int> (octree.getTreeDepth ())) { displayedDepth++; extractPointsAtLevel(displayedDepth); return true; } else return false; } /* \brief Helper function to decrease the octree display level by one * */ bool DecrementLevel() { if (displayedDepth > 0) { displayedDepth--; extractPointsAtLevel(displayedDepth); return true; } return false; } }; int main(int argc, char ** argv) { if (argc != 3) { std::cerr << "ERROR: Syntax is octreeVisu <pcd file> <resolution>" << std::endl; std::cerr << "EXAMPLE: ./octreeVisu bun0.pcd 0.001" << std::endl; return -1; } std::string cloud_path(argv[1]); OctreeViewer v(cloud_path, atof(argv[2])); } <commit_msg>[OCTREE] Remove a useless field in octree_viewer.<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, 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 the copyright holder(s) 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. * * * \author Raphael Favier * */ #include <pcl/io/pcd_io.h> #include <pcl/common/time.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/visualization/point_cloud_handlers.h> #include <pcl/visualization/common/common.h> #include <pcl/octree/octree_pointcloud_voxelcentroid.h> #include <pcl/filters/filter.h> #include "boost.h" #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkCubeSource.h> //============================= // Displaying cubes is very long! // so we limit their numbers. const int MAX_DISPLAYED_CUBES(15000); //============================= class OctreeViewer { public: OctreeViewer (std::string &filename, double resolution) : viz ("Octree visualizator"), cloud (new pcl::PointCloud<pcl::PointXYZ>()), displayCloud (new pcl::PointCloud<pcl::PointXYZ>()), octree (resolution), displayCubes(false), showPointsWithCubes (false), wireframe (true) { //try to load the cloud if (!loadCloud(filename)) return; //register keyboard callbacks viz.registerKeyboardCallback(&OctreeViewer::keyboardEventOccurred, *this, 0); //key legends viz.addText("Keys:", 0, 170, 0.0, 1.0, 0.0, "keys_t"); viz.addText("a -> Increment displayed depth", 10, 155, 0.0, 1.0, 0.0, "key_a_t"); viz.addText("z -> Decrement displayed depth", 10, 140, 0.0, 1.0, 0.0, "key_z_t"); viz.addText("d -> Toggle Point/Cube representation", 10, 125, 0.0, 1.0, 0.0, "key_d_t"); viz.addText("x -> Show/Hide original cloud", 10, 110, 0.0, 1.0, 0.0, "key_x_t"); viz.addText("s/w -> Surface/Wireframe representation", 10, 95, 0.0, 1.0, 0.0, "key_sw_t"); //set current level to half the maximum one displayedDepth = static_cast<int> (floor (octree.getTreeDepth() / 2.0)); if (displayedDepth == 0) displayedDepth = 1; //show octree at default depth extractPointsAtLevel(displayedDepth); //reset camera viz.resetCameraViewpoint("cloud"); //run main loop run(); } private: //======================================================== // PRIVATE ATTRIBUTES //======================================================== //visualizer pcl::PointCloud<pcl::PointXYZ>::Ptr xyz; pcl::visualization::PCLVisualizer viz; //original cloud pcl::PointCloud<pcl::PointXYZ>::Ptr cloud; //displayed_cloud pcl::PointCloud<pcl::PointXYZ>::Ptr displayCloud; //octree pcl::octree::OctreePointCloudVoxelCentroid<pcl::PointXYZ> octree; //level int displayedDepth; //bool to decide if we display points or cubes bool displayCubes, showPointsWithCubes, wireframe; //======================================================== /* \brief Callback to interact with the keyboard * */ void keyboardEventOccurred(const pcl::visualization::KeyboardEvent &event, void *) { if (event.getKeySym() == "a" && event.keyDown()) { IncrementLevel(); } else if (event.getKeySym() == "z" && event.keyDown()) { DecrementLevel(); } else if (event.getKeySym() == "d" && event.keyDown()) { displayCubes = !displayCubes; update(); } else if (event.getKeySym() == "x" && event.keyDown()) { showPointsWithCubes = !showPointsWithCubes; update(); } else if (event.getKeySym() == "w" && event.keyDown()) { if(!wireframe) wireframe=true; update(); } else if (event.getKeySym() == "s" && event.keyDown()) { if(wireframe) wireframe=false; update(); } } /* \brief Graphic loop for the viewer * */ void run() { while (!viz.wasStopped()) { //main loop of the visualizer viz.spinOnce(100); boost::this_thread::sleep(boost::posix_time::microseconds(100000)); } } /* \brief Helper function that read a pointcloud file (returns false if pbl) * Also initialize the octree * */ bool loadCloud(std::string &filename) { std::cout << "Loading file " << filename.c_str() << std::endl; //read cloud if (pcl::io::loadPCDFile(filename, *cloud)) { std::cerr << "ERROR: Cannot open file " << filename << "! Aborting..." << std::endl; return false; } //remove NaN Points std::vector<int> nanIndexes; pcl::removeNaNFromPointCloud(*cloud, *cloud, nanIndexes); std::cout << "Loaded " << cloud->points.size() << " points" << std::endl; //create octree structure octree.setInputCloud(cloud); //update bounding box automatically octree.defineBoundingBox(); //add points in the tree octree.addPointsFromInputCloud(); return true; } /* \brief Helper function that draw info for the user on the viewer * */ void showLegend(bool showCubes) { char dataDisplay[256]; sprintf(dataDisplay, "Displaying data as %s", (showCubes) ? ("CUBES") : ("POINTS")); viz.removeShape("disp_t"); viz.addText(dataDisplay, 0, 60, 1.0, 0.0, 0.0, "disp_t"); char level[256]; sprintf(level, "Displayed depth is %d on %d", displayedDepth, octree.getTreeDepth()); viz.removeShape("level_t1"); viz.addText(level, 0, 45, 1.0, 0.0, 0.0, "level_t1"); viz.removeShape("level_t2"); sprintf(level, "Voxel size: %.4fm [%lu voxels]", sqrt(octree.getVoxelSquaredSideLen(displayedDepth)), displayCloud->points.size()); viz.addText(level, 0, 30, 1.0, 0.0, 0.0, "level_t2"); viz.removeShape("org_t"); if (showPointsWithCubes) viz.addText("Displaying original cloud", 0, 15, 1.0, 0.0, 0.0, "org_t"); } /* \brief Visual update. Create visualizations and add them to the viewer * */ void update() { //remove existing shapes from visualizer clearView(); //prevent the display of too many cubes bool displayCubeLegend = displayCubes && static_cast<int> (displayCloud->points.size ()) <= MAX_DISPLAYED_CUBES; showLegend(displayCubeLegend); if (displayCubeLegend) { //show octree as cubes showCubes(sqrt(octree.getVoxelSquaredSideLen(displayedDepth))); if (showPointsWithCubes) { //add original cloud in visualizer pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> color_handler(cloud, "z"); viz.addPointCloud(cloud, color_handler, "cloud"); } } else { //add current cloud in visualizer pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> color_handler(displayCloud,"z"); viz.addPointCloud(displayCloud, color_handler, "cloud"); } } /* \brief remove dynamic objects from the viewer * */ void clearView() { //remove cubes if any vtkRenderer *renderer = viz.getRenderWindow()->GetRenderers()->GetFirstRenderer(); while (renderer->GetActors()->GetNumberOfItems() > 0) renderer->RemoveActor(renderer->GetActors()->GetLastActor()); //remove point clouds if any viz.removePointCloud("cloud"); } /* \brief Create a vtkSmartPointer object containing a cube * */ vtkSmartPointer<vtkPolyData> GetCuboid(double minX, double maxX, double minY, double maxY, double minZ, double maxZ) { vtkSmartPointer<vtkCubeSource> cube = vtkSmartPointer<vtkCubeSource>::New(); cube->SetBounds(minX, maxX, minY, maxY, minZ, maxZ); return cube->GetOutput(); } /* \brief display octree cubes via vtk-functions * */ void showCubes(double voxelSideLen) { //get the renderer of the visualizer object vtkRenderer *renderer = viz.getRenderWindow()->GetRenderers()->GetFirstRenderer(); vtkSmartPointer<vtkAppendPolyData> treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New(); size_t i; double s = voxelSideLen / 2.0; for (i = 0; i < displayCloud->points.size(); i++) { double x = displayCloud->points[i].x; double y = displayCloud->points[i].y; double z = displayCloud->points[i].z; #if VTK_MAJOR_VERSION < 6 treeWireframe->AddInput(GetCuboid(x - s, x + s, y - s, y + s, z - s, z + s)); #else treeWireframe->AddInputData (GetCuboid (x - s, x + s, y - s, y + s, z - s, z + s)); #endif } vtkSmartPointer<vtkActor> treeActor = vtkSmartPointer<vtkActor>::New(); vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); #if VTK_MAJOR_VERSION < 6 mapper->SetInput(treeWireframe->GetOutput()); #else mapper->SetInputData (treeWireframe->GetOutput ()); #endif treeActor->SetMapper(mapper); treeActor->GetProperty()->SetColor(1.0, 1.0, 1.0); treeActor->GetProperty()->SetLineWidth(2); if(wireframe) { treeActor->GetProperty()->SetRepresentationToWireframe(); treeActor->GetProperty()->SetOpacity(0.35); } else treeActor->GetProperty()->SetRepresentationToSurface(); renderer->AddActor(treeActor); } /* \brief Extracts all the points of depth = level from the octree * */ void extractPointsAtLevel(int depth) { displayCloud->points.clear(); pcl::octree::OctreePointCloudVoxelCentroid<pcl::PointXYZ>::Iterator tree_it; pcl::octree::OctreePointCloudVoxelCentroid<pcl::PointXYZ>::Iterator tree_it_end = octree.end(); pcl::PointXYZ pt; std::cout << "===== Extracting data at depth " << depth << "... " << std::flush; double start = pcl::getTime (); for (tree_it = octree.begin(depth); tree_it!=tree_it_end; ++tree_it) { Eigen::Vector3f voxel_min, voxel_max; octree.getVoxelBounds(tree_it, voxel_min, voxel_max); pt.x = (voxel_min.x() + voxel_max.x()) / 2.0f; pt.y = (voxel_min.y() + voxel_max.y()) / 2.0f; pt.z = (voxel_min.z() + voxel_max.z()) / 2.0f; displayCloud->points.push_back(pt); } double end = pcl::getTime (); printf("%lu pts, %.4gs. %.4gs./pt. =====\n", displayCloud->points.size (), end - start, (end - start) / static_cast<double> (displayCloud->points.size ())); update(); } /* \brief Helper function to increase the octree display level by one * */ bool IncrementLevel() { if (displayedDepth < static_cast<int> (octree.getTreeDepth ())) { displayedDepth++; extractPointsAtLevel(displayedDepth); return true; } else return false; } /* \brief Helper function to decrease the octree display level by one * */ bool DecrementLevel() { if (displayedDepth > 0) { displayedDepth--; extractPointsAtLevel(displayedDepth); return true; } return false; } }; int main(int argc, char ** argv) { if (argc != 3) { std::cerr << "ERROR: Syntax is octreeVisu <pcd file> <resolution>" << std::endl; std::cerr << "EXAMPLE: ./octreeVisu bun0.pcd 0.001" << std::endl; return -1; } std::string cloud_path(argv[1]); OctreeViewer v(cloud_path, atof(argv[2])); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkTimeSlicedGeometry.h" #include <vtkTransform.h> mitk::Geometry3D* mitk::TimeSlicedGeometry::GetGeometry3D(int t) const { mitk::Geometry3D::Pointer geometry3d = NULL; if(IsValidTime(t)) { geometry3d = m_Geometry3Ds[t]; //if (a) we don't have a Geometry3D stored for the requested time, //(b) m_EvenlyTimed is activated and (c) the first geometry (t=0) //is set, then we clone the geometry and set the m_TimeBoundsInMS accordingly. if((m_EvenlyTimed) && (geometry3d.IsNull())) { const Geometry3D* firstgeometry=m_Geometry3Ds[0].GetPointer(); assert(firstgeometry != NULL); mitk::Geometry3D::Pointer requestedgeometry; requestedgeometry = static_cast<Geometry3D*>(firstgeometry->Clone().GetPointer()); TimeBounds timebounds = requestedgeometry->GetTimeBoundsInMS(); if(timebounds[1]<ScalarTypeNumericTraits::max()) { mitk::ScalarType later = (timebounds[1]-timebounds[0])*t; timebounds[0]+=later; timebounds[1]+=later; requestedgeometry->SetTimeBoundsInMS(timebounds); } geometry3d = requestedgeometry; m_Geometry3Ds[t] = geometry3d; } } else return NULL; return geometry3d; } const mitk::TimeBounds& mitk::TimeSlicedGeometry::GetTimeBoundsInMS() const { //@todo calculation should be moved into a method and called when first or last time-slice is changed. TimeBounds timebounds; mitk::Geometry3D::Pointer geometry3d; geometry3d = m_Geometry3Ds[0]; assert(geometry3d.IsNotNull()); timebounds[0] = geometry3d->GetTimeBoundsInMS()[0]; geometry3d = GetGeometry3D(m_TimeSteps-1); assert(geometry3d.IsNotNull()); timebounds[1]=geometry3d->GetTimeBoundsInMS()[1]; m_TimeBoundsInMS = timebounds; return m_TimeBoundsInMS; } bool mitk::TimeSlicedGeometry::SetGeometry3D(mitk::Geometry3D* geometry3D, int t) { if(IsValidTime(t)) { m_Geometry3Ds[t]=geometry3D; return true; } return false; } int mitk::TimeSlicedGeometry::MSToTimeStep(mitk::ScalarType time_in_ms) const { assert(m_EvenlyTimed); { if(time_in_ms < m_TimeBoundsInMS[0]) return -1; if(time_in_ms >= m_TimeBoundsInMS[1]) return m_TimeSteps; if(m_TimeBoundsInMS[0]==m_TimeBoundsInMS[1]) return 0; if((m_TimeBoundsInMS[0]>-ScalarTypeNumericTraits::max()) && (m_TimeBoundsInMS[1]<ScalarTypeNumericTraits::max())) return (int) ((time_in_ms - m_TimeBoundsInMS[0])/(m_TimeBoundsInMS[1]-m_TimeBoundsInMS[0])*m_TimeSteps); return 0; } return 0; } mitk::ScalarType mitk::TimeSlicedGeometry::TimeStepToMS(int timestep) const { assert(m_EvenlyTimed); if(IsValidTime(timestep)==false) return ScalarTypeNumericTraits::max(); return ((mitk::ScalarType)timestep)/m_TimeSteps*(m_TimeBoundsInMS[1]-m_TimeBoundsInMS[0])+m_TimeBoundsInMS[0]; } void mitk::TimeSlicedGeometry::Initialize(unsigned int timeSteps) { Superclass::Initialize(); m_TimeSteps = timeSteps; m_Geometry3Ds.clear(); Geometry3D::Pointer gnull=NULL; m_Geometry3Ds.reserve(m_TimeSteps); m_Geometry3Ds.assign(m_TimeSteps, gnull); } void mitk::TimeSlicedGeometry::InitializeEvenlyTimed(mitk::Geometry3D* geometry3D, unsigned int timeSteps) { assert(geometry3D!=NULL); geometry3D->Register(); Initialize(timeSteps); AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetMatrix(geometry3D->GetIndexToWorldTransform()->GetMatrix()); transform->SetOffset(geometry3D->GetIndexToWorldTransform()->GetOffset()); SetIndexToWorldTransform(transform); SetBounds(geometry3D->GetBounds()); SetGeometry3D(geometry3D, 0); SetEvenlyTimed(); // // commented out because this results in a // segmentation fault under linux! // //GetTimeBoundsInMS(); //@todo see GetTimeBoundsInMS geometry3D->UnRegister(); } mitk::TimeSlicedGeometry::TimeSlicedGeometry() : m_TimeSteps(0), m_EvenlyTimed(false) { } mitk::TimeSlicedGeometry::~TimeSlicedGeometry() { } const mitk::BoundingBox* mitk::TimeSlicedGeometry::GetBoundingBox() const { mitk::BoundingBox::Pointer boundingBox=mitk::BoundingBox::New(); mitk::BoundingBox::PointsContainer::Pointer pointscontainer=mitk::BoundingBox::PointsContainer::New(); mitk::ScalarType nullpoint[]={0,0,0}; mitk::BoundingBox::PointType p(nullpoint); unsigned int t; mitk::Geometry3D* geometry3d; mitk::BoundingBox::ConstPointer nextBoundingBox; mitk::BoundingBox::PointIdentifier pointid=0; for(t=0; t<m_TimeSteps; ++t) { geometry3d = GetGeometry3D(t); assert(geometry3d!=NULL); nextBoundingBox = geometry3d->GetBoundingBox(); assert(nextBoundingBox.IsNotNull()); const mitk::BoundingBox::PointsContainer * nextPoints = nextBoundingBox->GetPoints(); if(nextPoints!=NULL) { mitk::BoundingBox::PointsContainer::ConstIterator pointsIt = nextPoints->Begin(); while (pointsIt != nextPoints->End() ) { pointscontainer->InsertElement( pointid++, pointsIt->Value()); ++pointsIt; } } } boundingBox->SetPoints(pointscontainer); boundingBox->ComputeBoundingBox(); m_BoundingBox=boundingBox; return boundingBox.GetPointer(); } void mitk::TimeSlicedGeometry::SetEvenlyTimed(bool on) { m_EvenlyTimed = on; Modified(); } bool mitk::TimeSlicedGeometry::IsValidTime(int t) const { return (t>=0) && (t< (int)m_TimeSteps); } mitk::AffineGeometryFrame3D::Pointer mitk::TimeSlicedGeometry::Clone() const { Self::Pointer newGeometry = Self::New(); newGeometry->Initialize(m_TimeSteps); InitializeGeometry(newGeometry); return newGeometry.GetPointer(); } void mitk::TimeSlicedGeometry::InitializeGeometry(Self * newGeometry) const { Superclass::InitializeGeometry(newGeometry); newGeometry->SetEvenlyTimed(m_EvenlyTimed); unsigned int t; for(t=0; t<m_TimeSteps; ++t) { if(m_Geometry3Ds[t].IsNull()) { assert(m_EvenlyTimed); } else { newGeometry->SetGeometry3D(dynamic_cast<Geometry3D*>(m_Geometry3Ds[t]->Clone().GetPointer()), t); } } } <commit_msg>FIX: fixed the bug making it necessary to commented out call to GetTimeBoundsInMS() in InitializeEvenlyTimed(...) in revision 1.14<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkTimeSlicedGeometry.h" #include <vtkTransform.h> mitk::Geometry3D* mitk::TimeSlicedGeometry::GetGeometry3D(int t) const { mitk::Geometry3D::Pointer geometry3d = NULL; if(IsValidTime(t)) { geometry3d = m_Geometry3Ds[t]; //if (a) we don't have a Geometry3D stored for the requested time, //(b) m_EvenlyTimed is activated and (c) the first geometry (t=0) //is set, then we clone the geometry and set the m_TimeBoundsInMS accordingly. if((m_EvenlyTimed) && (geometry3d.IsNull())) { const Geometry3D* firstgeometry=m_Geometry3Ds[0].GetPointer(); assert(firstgeometry != NULL); mitk::Geometry3D::Pointer requestedgeometry; requestedgeometry = static_cast<Geometry3D*>(firstgeometry->Clone().GetPointer()); TimeBounds timebounds = requestedgeometry->GetTimeBoundsInMS(); if(timebounds[1]<ScalarTypeNumericTraits::max()) { mitk::ScalarType later = (timebounds[1]-timebounds[0])*t; timebounds[0]+=later; timebounds[1]+=later; requestedgeometry->SetTimeBoundsInMS(timebounds); } geometry3d = requestedgeometry; m_Geometry3Ds[t] = geometry3d; } } else return NULL; return geometry3d; } const mitk::TimeBounds& mitk::TimeSlicedGeometry::GetTimeBoundsInMS() const { //@todo calculation should be moved into a method and called when first or last time-slice is changed. TimeBounds timebounds; mitk::Geometry3D::Pointer geometry3d; geometry3d = m_Geometry3Ds[0]; assert(geometry3d.IsNotNull()); timebounds[0] = geometry3d->GetTimeBoundsInMS()[0]; geometry3d = GetGeometry3D(m_TimeSteps-1); assert(geometry3d.IsNotNull()); timebounds[1]=geometry3d->GetTimeBoundsInMS()[1]; m_TimeBoundsInMS = timebounds; assert(timebounds[0]<=timebounds[1]); return m_TimeBoundsInMS; } bool mitk::TimeSlicedGeometry::SetGeometry3D(mitk::Geometry3D* geometry3D, int t) { if(IsValidTime(t)) { m_Geometry3Ds[t]=geometry3D; return true; } return false; } int mitk::TimeSlicedGeometry::MSToTimeStep(mitk::ScalarType time_in_ms) const { assert(m_EvenlyTimed); { if(time_in_ms < m_TimeBoundsInMS[0]) return -1; if(time_in_ms >= m_TimeBoundsInMS[1]) return m_TimeSteps-1; if(m_TimeBoundsInMS[0]==m_TimeBoundsInMS[1]) return 0; if((m_TimeBoundsInMS[0]>-ScalarTypeNumericTraits::max()) && (m_TimeBoundsInMS[1]<ScalarTypeNumericTraits::max())) return (int) ((time_in_ms - m_TimeBoundsInMS[0])/(m_TimeBoundsInMS[1]-m_TimeBoundsInMS[0])*m_TimeSteps); return 0; } return 0; } mitk::ScalarType mitk::TimeSlicedGeometry::TimeStepToMS(int timestep) const { assert(m_EvenlyTimed); if(IsValidTime(timestep)==false) return ScalarTypeNumericTraits::max(); return ((mitk::ScalarType)timestep)/m_TimeSteps*(m_TimeBoundsInMS[1]-m_TimeBoundsInMS[0])+m_TimeBoundsInMS[0]; } void mitk::TimeSlicedGeometry::Initialize(unsigned int timeSteps) { Superclass::Initialize(); m_TimeSteps = timeSteps; m_Geometry3Ds.clear(); Geometry3D::Pointer gnull=NULL; m_Geometry3Ds.reserve(m_TimeSteps); m_Geometry3Ds.assign(m_TimeSteps, gnull); } void mitk::TimeSlicedGeometry::InitializeEvenlyTimed(mitk::Geometry3D* geometry3D, unsigned int timeSteps) { assert(geometry3D!=NULL); geometry3D->Register(); Initialize(timeSteps); AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetMatrix(geometry3D->GetIndexToWorldTransform()->GetMatrix()); transform->SetOffset(geometry3D->GetIndexToWorldTransform()->GetOffset()); SetIndexToWorldTransform(transform); SetBounds(geometry3D->GetBounds()); SetGeometry3D(geometry3D, 0); SetEvenlyTimed(); // // commented out because this results in a // segmentation fault under linux! // GetTimeBoundsInMS(); //@todo see GetTimeBoundsInMS geometry3D->UnRegister(); } mitk::TimeSlicedGeometry::TimeSlicedGeometry() : m_TimeSteps(0), m_EvenlyTimed(false) { } mitk::TimeSlicedGeometry::~TimeSlicedGeometry() { } const mitk::BoundingBox* mitk::TimeSlicedGeometry::GetBoundingBox() const { mitk::BoundingBox::Pointer boundingBox=mitk::BoundingBox::New(); mitk::BoundingBox::PointsContainer::Pointer pointscontainer=mitk::BoundingBox::PointsContainer::New(); mitk::ScalarType nullpoint[]={0,0,0}; mitk::BoundingBox::PointType p(nullpoint); unsigned int t; mitk::Geometry3D* geometry3d; mitk::BoundingBox::ConstPointer nextBoundingBox; mitk::BoundingBox::PointIdentifier pointid=0; for(t=0; t<m_TimeSteps; ++t) { geometry3d = GetGeometry3D(t); assert(geometry3d!=NULL); nextBoundingBox = geometry3d->GetBoundingBox(); assert(nextBoundingBox.IsNotNull()); const mitk::BoundingBox::PointsContainer * nextPoints = nextBoundingBox->GetPoints(); if(nextPoints!=NULL) { mitk::BoundingBox::PointsContainer::ConstIterator pointsIt = nextPoints->Begin(); while (pointsIt != nextPoints->End() ) { pointscontainer->InsertElement( pointid++, pointsIt->Value()); ++pointsIt; } } } boundingBox->SetPoints(pointscontainer); boundingBox->ComputeBoundingBox(); m_BoundingBox=boundingBox; return boundingBox.GetPointer(); } void mitk::TimeSlicedGeometry::SetEvenlyTimed(bool on) { m_EvenlyTimed = on; Modified(); } bool mitk::TimeSlicedGeometry::IsValidTime(int t) const { return (t>=0) && (t< (int)m_TimeSteps); } mitk::AffineGeometryFrame3D::Pointer mitk::TimeSlicedGeometry::Clone() const { Self::Pointer newGeometry = Self::New(); newGeometry->Initialize(m_TimeSteps); InitializeGeometry(newGeometry); return newGeometry.GetPointer(); } void mitk::TimeSlicedGeometry::InitializeGeometry(Self * newGeometry) const { Superclass::InitializeGeometry(newGeometry); newGeometry->SetEvenlyTimed(m_EvenlyTimed); unsigned int t; for(t=0; t<m_TimeSteps; ++t) { if(m_Geometry3Ds[t].IsNull()) { assert(m_EvenlyTimed); } else { newGeometry->SetGeometry3D(dynamic_cast<Geometry3D*>(m_Geometry3Ds[t]->Clone().GetPointer()), t); } } } <|endoftext|>
<commit_before> #include <unistd.h> #include <cstddef> #include <cmath> #include <cstdlib> #include <map> #include <iostream> #include <persistence/persistence.hpp> /// \brief the class we want to be serialized / deserialized class my_class { public: /// \brief mandatory constructor my_class(int _i, double _s_double, float _s_float, int _s_int) : s_int(_s_int), s_double(_s_double), s_float(_s_float), i(_i) {} void print(const std::string &str) const { std::cout << str << " my_class: [s_int: " << s_int << ", s_double: " << s_double << ", s_float: " << s_float << ", i: " << i << "]" << std::endl; } void increment() { ++s_int; } private: /// \brief the function that will be called when deserializing the object void post_deserialization(int _i, neam::cr::from_serialization_t) { i = _i; } private: // serialized properties int s_int; double s_double; float s_float; private: // non-serialized properties int i; friend neam::cr::persistence; }; // the serialization meta-data namespace neam { namespace cr { template<typename Backend> class persistence::serializable<Backend, my_class> : public persistence::constructible_serializable_object < Backend, // Embed in the template a call to the post-deserialization function // This function will be called just after the object has been deserialized N_CALL_POST_FUNCTION(my_class, N_EMBED(42), neam::cr::from_serialization), // simply list here the members you want to serialize / deserialize NCRP_TYPED_OFFSET(my_class, s_int), NCRP_TYPED_OFFSET(my_class, s_double), NCRP_TYPED_OFFSET(my_class, s_float) > {}; } // namespace cr } // namespace neam void init_storage(neam::cr::storage &storage) { my_class my_instance(13, 42.00000042, 4.2e-5, 0); my_instance.print("original:\n "); storage.write_to_file("sample/storage/instance", my_instance); } int main() { neam::cr::storage storage("samples.storage"); if (!storage.is_valid() || !storage.contains("sample/storage/instance")) init_storage(storage); // deserialize stored data: my_class *ptr = storage.load_from_file<my_class>("sample/storage/instance"); if (!ptr) { std::cerr << "Unable to de-serialize... :(" << std::endl; return 1; } ptr->print("deserialized:\n "); ptr->increment(); // update it: storage.write_to_file("sample/storage/instance", *ptr); delete ptr; return 0; } <commit_msg>[NEAM/PERSISTENCE/SAMPLES/STORGAE]: a more fault tolerant recovery<commit_after> #include <unistd.h> #include <cstddef> #include <cmath> #include <cstdlib> #include <map> #include <iostream> #include <persistence/persistence.hpp> /// \brief the class we want to be serialized / deserialized class my_class { public: /// \brief mandatory constructor my_class(int _i, double _s_double, float _s_float, int _s_int) : s_int(_s_int), s_double(_s_double), s_float(_s_float), i(_i) {} void print(const std::string &str) const { std::cout << str << " my_class: [s_int: " << s_int << ", s_double: " << s_double << ", s_float: " << s_float << ", i: " << i << "]" << std::endl; } void increment() { ++s_int; } private: /// \brief the function that will be called when deserializing the object void post_deserialization(int _i, neam::cr::from_serialization_t) { i = _i; } private: // serialized properties int s_int; double s_double; float s_float; private: // non-serialized properties int i; friend neam::cr::persistence; }; // the serialization meta-data namespace neam { namespace cr { template<typename Backend> class persistence::serializable<Backend, my_class> : public persistence::constructible_serializable_object < Backend, // Embed in the template a call to the post-deserialization function // This function will be called just after the object has been deserialized N_CALL_POST_FUNCTION(my_class, N_EMBED(42), neam::cr::from_serialization), // simply list here the members you want to serialize / deserialize NCRP_TYPED_OFFSET(my_class, s_int), NCRP_TYPED_OFFSET(my_class, s_double), NCRP_TYPED_OFFSET(my_class, s_float) > {}; } // namespace cr } // namespace neam void init_storage(neam::cr::storage &storage) { my_class my_instance(13, 42.00000042, 4.2e-5, 0); my_instance.print("original:\n "); storage.write_to_file("sample/storage/instance", my_instance); } int main() { neam::cr::storage storage("samples.storage"); if (!storage.is_valid() || !storage.contains("sample/storage/instance")) init_storage(storage); // deserialize stored data: my_class *ptr = storage.load_from_file<my_class>("sample/storage/instance"); if (!ptr) { std::cerr << "Invalid data: reset 'sample/storage/instance'" << std::endl; // re-init the storage with a valid value init_storage(storage); // re-get the pointer ptr = storage.load_from_file<my_class>("sample/storage/instance"); // should never happen if (!ptr) { std::cerr << "Unable to retrieve valid data... :(" << std::endl; return 1; } } ptr->print("deserialized:\n "); ptr->increment(); // update it: storage.write_to_file("sample/storage/instance", *ptr); delete ptr; return 0; } <|endoftext|>
<commit_before>#include <babylon/inspector/actions/action_store.h> #include <babylon/babylon_stl_util.h> namespace BABYLON { ActionStore::ActionStore() = default; ActionStore::~ActionStore() = default; void ActionStore::addAction(const char* id, const char* icon, const char* label, const char* shortcut, const SA::delegate<void()>& callback) { _actions[id] = InspectorAction(id, icon, label, shortcut, callback); } InspectorAction* ActionStore::getAction(const char* id) { if (stl_util::contains(_actions, id)) { return &_actions[id]; } return nullptr; } } // end of namespace BABYLON <commit_msg>Formatting<commit_after>#include <babylon/inspector/actions/action_store.h> #include <babylon/babylon_stl_util.h> namespace BABYLON { ActionStore::ActionStore() = default; ActionStore::~ActionStore() = default; void ActionStore::addAction(const char* id, const char* icon, const char* label, const char* shortcut, const SA::delegate<void()>& callback) { _actions[id] = InspectorAction(id, icon, label, shortcut, callback); } InspectorAction* ActionStore::getAction(const char* id) { if (stl_util::contains(_actions, id)) { return &_actions[id]; } return nullptr; } } // end of namespace BABYLON <|endoftext|>
<commit_before>/**************************************************************************** Copyright (c) 2015 Sérgio Vieira - sergiosvieira@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** YDA **/ #include "YMain.h" #include "YSpriteManager.h" #include "YFileSystem.h" #include "YSprite.h" #include "YSpriteSheet.h" #include "YObject.h" #include "YObjectManager.h" #include "Bird.h" #include "Cloud.h" /** STL **/ #include <array> #include <algorithm> const char* kCloud01 = "cloud_01"; const char* kCloud02 = "cloud_02"; const char* kRedBird = "red_bird"; void createClouds(std::vector<Cloud*>&& a_clouds, int a_size, YSpriteManager* a_manager) { a_clouds.reserve(a_size); for (int i = 0; i < a_size; ++i) { const char* name = (i % 2 == 0) ? kCloud01 : kCloud02; float z = (i % 2 == 0) ? 0.f : 2.f; YSprite* cloudSprite = new YSprite(a_manager->findByName(name)); Cloud* cloud01 = new Cloud(cloudSprite); YPoint position = cloud01->position(); position.z(z); cloud01->position(position); a_clouds.push_back(cloud01); } } int main(int argc, char** argv) { typedef struct { std::string key; std::string value; } KeyValue; YObjectManager* objectManager = new YObjectManager(); YMain* game = new YMain("Z-Order - sergiosvieira@gmail.com", 640, 480, objectManager); /** Load Resources **/ YSpriteManager* manager = new YSpriteManager(game->SDLRenderer()); std::array<KeyValue, 3> images = { { {kCloud01, "cloud_01.png"}, {kCloud02, "cloud_02.png"}, {kRedBird, "red_bird_set.png"} } }; for (const KeyValue& kv: images) { manager->add(kv.key.c_str(), YFileSystem::fullPathName({"gfx"}, kv.value.c_str())); } /** Creates Clouds **/ std::vector<Cloud*> clouds; createClouds(std::move(clouds), 100, manager); /** Creates Bird **/ YSpriteSheet* birdSprite = new YSpriteSheet(manager->findByName("red_bird"), YFrame(0, 0, 5), 64, 40, 20); Bird* bird = new Bird(birdSprite); /** Update/Render Objects **/ for (Cloud* cloud: clouds) { objectManager->add(cloud); } objectManager->add(bird); game->start(); delete objectManager; delete game; delete manager; return 0; }<commit_msg>Adds undef main (visual studio compability)<commit_after>/**************************************************************************** Copyright (c) 2015 Sérgio Vieira - sergiosvieira@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** YDA **/ #include "YMain.h" #include "YSpriteManager.h" #include "YFileSystem.h" #include "YSprite.h" #include "YSpriteSheet.h" #include "YObject.h" #include "YObjectManager.h" #include "Bird.h" #include "Cloud.h" /** STL **/ #include <array> #include <algorithm> const char* kCloud01 = "cloud_01"; const char* kCloud02 = "cloud_02"; const char* kRedBird = "red_bird"; void createClouds(std::vector<Cloud*>&& a_clouds, int a_size, YSpriteManager* a_manager) { a_clouds.reserve(a_size); for (int i = 0; i < a_size; ++i) { const char* name = (i % 2 == 0) ? kCloud01 : kCloud02; float z = (i % 2 == 0) ? 0.f : 2.f; YSprite* cloudSprite = new YSprite(a_manager->findByName(name)); Cloud* cloud01 = new Cloud(cloudSprite); YPoint position = cloud01->position(); position.z(z); cloud01->position(position); a_clouds.push_back(cloud01); } } #undef main int main(int argc, char** argv) { typedef struct { std::string key; std::string value; } KeyValue; YObjectManager* objectManager = new YObjectManager(); YMain* game = new YMain("Z-Order - sergiosvieira@gmail.com", 640, 480, objectManager); /** Load Resources **/ YSpriteManager* manager = new YSpriteManager(game->SDLRenderer()); std::array<KeyValue, 3> images = { { {kCloud01, "cloud_01.png"}, {kCloud02, "cloud_02.png"}, {kRedBird, "red_bird_set.png"} } }; for (const KeyValue& kv: images) { manager->add(kv.key.c_str(), YFileSystem::fullPathName({"gfx"}, kv.value.c_str())); } /** Creates Clouds **/ std::vector<Cloud*> clouds; createClouds(std::move(clouds), 100, manager); /** Creates Bird **/ YSpriteSheet* birdSprite = new YSpriteSheet(manager->findByName("red_bird"), YFrame(0, 0, 5), 64, 40, 20); Bird* bird = new Bird(birdSprite); /** Update/Render Objects **/ for (Cloud* cloud: clouds) { objectManager->add(cloud); } objectManager->add(bird); game->start(); delete objectManager; delete game; delete manager; return 0; }<|endoftext|>
<commit_before>#pragma once #include <memory> #include <pdal/Dimension.hpp> #include <pdal/Compression.hpp> #include <entwine/compression/stream.hpp> namespace entwine { class Schema; class DimInfo; } class ItcBuffer; class ReadQuery { public: ReadQuery( const entwine::Schema& schema, bool compress, std::size_t index = 0); virtual ~ReadQuery() { } void read(ItcBuffer& buffer); bool compress() const { return m_compressor.get() != 0; } bool done() const { return m_done; } virtual uint64_t numPoints() const = 0; protected: // Must return true if done, else false. virtual bool readSome(ItcBuffer& buffer) = 0; void compressionSwap(ItcBuffer& buffer); entwine::CompressionStream m_compressionStream; std::unique_ptr<pdal::LazPerfCompressor< entwine::CompressionStream>> m_compressor; std::size_t m_compressionOffset; const entwine::Schema& m_schema; bool m_done; }; <commit_msg>Call done on compressor if an in-progress query is terminated.<commit_after>#pragma once #include <memory> #include <pdal/Dimension.hpp> #include <pdal/Compression.hpp> #include <entwine/compression/stream.hpp> namespace entwine { class Schema; class DimInfo; } class ItcBuffer; class ReadQuery { public: ReadQuery( const entwine::Schema& schema, bool compress, std::size_t index = 0); virtual ~ReadQuery() { if (m_compressor) m_compressor->done(); } void read(ItcBuffer& buffer); bool compress() const { return m_compressor.get() != 0; } bool done() const { return m_done; } virtual uint64_t numPoints() const = 0; protected: // Must return true if done, else false. virtual bool readSome(ItcBuffer& buffer) = 0; void compressionSwap(ItcBuffer& buffer); entwine::CompressionStream m_compressionStream; std::unique_ptr<pdal::LazPerfCompressor< entwine::CompressionStream>> m_compressor; std::size_t m_compressionOffset; const entwine::Schema& m_schema; bool m_done; }; <|endoftext|>
<commit_before>/********************************************************************** Copyright (c) 2018 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************/ #include "scene_load_utils.h" #include <SceneGraph/scene1.h> #include <scene_io.h> #include <image_io.h> #include <material_io.h> #include "XML/tinyxml2.h" using namespace Baikal; namespace { void LoadMaterials(std::string const& basepath, Scene1::Ptr scene) { // Check it we have material remapping std::ifstream in_materials(basepath + "materials.xml"); std::ifstream in_mapping(basepath + "mapping.xml"); if (!in_materials || !in_mapping) return; auto material_io = Baikal::MaterialIo::CreateMaterialIoXML(); auto mats = material_io->LoadMaterials(basepath + "materials.xml"); auto mapping = material_io->LoadMaterialMapping(basepath + "mapping.xml"); material_io->ReplaceSceneMaterials(*scene, *mats, mapping); } void LoadLights(std::string const& light_file, Scene1::Ptr scene) { if (light_file.empty()) { return; } tinyxml2::XMLDocument doc; doc.LoadFile(light_file.c_str()); auto root = doc.FirstChildElement("light_list"); if (!root) { throw std::runtime_error("Failed to open lights set file."); } tinyxml2::XMLElement* elem = root->FirstChildElement("light"); while (elem) { Light::Ptr light; std::string type = elem->Attribute("type"); if (type == "point") { light = PointLight::Create(); } else if (type == "spot") { auto spot = SpotLight::Create(); RadeonRays::float2 cone_shape(elem->FloatAttribute("csx"), elem->FloatAttribute("csy")); spot->SetConeShape(cone_shape); light = spot; } else if (type == "direct") { light = DirectionalLight::Create(); } else if (type == "ibl") { auto image_io = ImageIo::CreateImageIo(); auto tex = image_io->LoadImage(elem->Attribute("tex")); auto ibl = ImageBasedLight::Create(); ibl->SetTexture(tex); ibl->SetMultiplier(elem->FloatAttribute("mul")); light = ibl; } else { throw std::runtime_error(std::string("Unknown light type: ") + type); } RadeonRays::float3 rad; light->SetPosition({ elem->FloatAttribute("posx"), elem->FloatAttribute("posy"), elem->FloatAttribute("posz")}); light->SetDirection({ elem->FloatAttribute("dirx"), elem->FloatAttribute("diry"), elem->FloatAttribute("dirz")}); light->SetEmittedRadiance({ elem->FloatAttribute("radx"), elem->FloatAttribute("rady"), elem->FloatAttribute("radz")}); scene->AttachLight(light); elem = elem->NextSiblingElement("light"); } } } Scene1::Ptr LoadScene(Baikal::AppSettings const& settings) { #ifdef WIN32 std::string basepath = settings.path + "\\"; #elif std::string basepath = settings.path + "/"; #endif std::string filename = basepath + settings.modelname; auto scene = Baikal::SceneIo::LoadScene(filename, basepath); if (scene == nullptr) { throw std::runtime_error("LoadScene(...): cannot create scene"); } LoadMaterials(basepath, scene); LoadLights(settings.light_file, scene); return scene; }<commit_msg>Build fix<commit_after>/********************************************************************** Copyright (c) 2018 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************/ #include "scene_load_utils.h" #include <SceneGraph/scene1.h> #include <scene_io.h> #include <image_io.h> #include <material_io.h> #include "XML/tinyxml2.h" using namespace Baikal; namespace { void LoadMaterials(std::string const& basepath, Scene1::Ptr scene) { // Check it we have material remapping std::ifstream in_materials(basepath + "materials.xml"); std::ifstream in_mapping(basepath + "mapping.xml"); if (!in_materials || !in_mapping) return; auto material_io = Baikal::MaterialIo::CreateMaterialIoXML(); auto mats = material_io->LoadMaterials(basepath + "materials.xml"); auto mapping = material_io->LoadMaterialMapping(basepath + "mapping.xml"); material_io->ReplaceSceneMaterials(*scene, *mats, mapping); } void LoadLights(std::string const& light_file, Scene1::Ptr scene) { if (light_file.empty()) { return; } tinyxml2::XMLDocument doc; doc.LoadFile(light_file.c_str()); auto root = doc.FirstChildElement("light_list"); if (!root) { throw std::runtime_error("Failed to open lights set file."); } tinyxml2::XMLElement* elem = root->FirstChildElement("light"); while (elem) { Light::Ptr light; std::string type = elem->Attribute("type"); if (type == "point") { light = PointLight::Create(); } else if (type == "spot") { auto spot = SpotLight::Create(); RadeonRays::float2 cone_shape(elem->FloatAttribute("csx"), elem->FloatAttribute("csy")); spot->SetConeShape(cone_shape); light = spot; } else if (type == "direct") { light = DirectionalLight::Create(); } else if (type == "ibl") { auto image_io = ImageIo::CreateImageIo(); auto tex = image_io->LoadImage(elem->Attribute("tex")); auto ibl = ImageBasedLight::Create(); ibl->SetTexture(tex); ibl->SetMultiplier(elem->FloatAttribute("mul")); light = ibl; } else { throw std::runtime_error(std::string("Unknown light type: ") + type); } RadeonRays::float3 rad; light->SetPosition({ elem->FloatAttribute("posx"), elem->FloatAttribute("posy"), elem->FloatAttribute("posz")}); light->SetDirection({ elem->FloatAttribute("dirx"), elem->FloatAttribute("diry"), elem->FloatAttribute("dirz")}); light->SetEmittedRadiance({ elem->FloatAttribute("radx"), elem->FloatAttribute("rady"), elem->FloatAttribute("radz")}); scene->AttachLight(light); elem = elem->NextSiblingElement("light"); } } } Scene1::Ptr LoadScene(Baikal::AppSettings const& settings) { #ifdef WIN32 std::string basepath = settings.path + "\\"; #else std::string basepath = settings.path + "/"; #endif std::string filename = basepath + settings.modelname; auto scene = Baikal::SceneIo::LoadScene(filename, basepath); if (scene == nullptr) { throw std::runtime_error("LoadScene(...): cannot create scene"); } LoadMaterials(basepath, scene); LoadLights(settings.light_file, scene); return scene; }<|endoftext|>
<commit_before>#ifndef XG_HASH_MAP_SET_H #define XG_HASH_MAP_SET_H #include "sparsehash/sparse_hash_map" #include "sparsehash/sparse_hash_set" // http://stackoverflow.com/questions/4870437/pairint-int-pair-as-key-of-unordered-map-issue#comment5439557_4870467 // https://github.com/Revolutionary-Games/Thrive/blob/fd8ab943dd4ced59a8e7d1e4a7b725468b7c2557/src/util/pair_hash.h // taken from boost namespace std { template <typename A, typename B> struct hash<pair<A,B> > { size_t operator()(const pair<A,B>& x) const { std::size_t hashA = std::hash<A>()(x.first); std::size_t hashB = std::hash<B>()(x.second); return hashA ^ (hashB + 0x9e3779b9 + (hashA << 6) + (hashA >> 2)); } }; } namespace xg { using google::sparse_hash_map; using google::sparse_hash_set; template<typename K, typename V> class hash_map : public sparse_hash_map<K,V> { public: hash_map() { this->set_deleted_key(-2); } }; template<typename K, typename V> class string_hash_map : public sparse_hash_map<K,V> { public: string_hash_map() { this->set_deleted_key(""); } }; template<typename K, typename V> class pair_hash_map : public sparse_hash_map<K,V,std::hash<K> > { public: pair_hash_map() { this->set_deleted_key(K(-2, -2)); } }; template<typename K, typename V> class hash_map<K*,V> : public sparse_hash_map<K*,V> { public: hash_map() { this->set_deleted_key((K*)(0)); } }; template<typename K> class hash_set : public sparse_hash_set<K> { public: hash_set() { this->set_deleted_key(-2); } }; template<typename K> class string_hash_set : public sparse_hash_set<K> { public: string_hash_set() { this->set_deleted_key(""); } }; template<typename K> class pair_hash_set : public sparse_hash_set<K,std::hash<K> > { public: pair_hash_set() { this->set_deleted_key(K(-2, -2)); } }; template<typename K> class hash_set<K*> : public sparse_hash_set<K*> { public: hash_set() { this->set_deleted_key((K*)(0)); } }; } #endif <commit_msg>include guard for use of hash-map pair hash overload vg<commit_after>#ifndef XG_HASH_MAP_SET_H #define XG_HASH_MAP_SET_H #include "sparsehash/sparse_hash_map" #include "sparsehash/sparse_hash_set" // http://stackoverflow.com/questions/4870437/pairint-int-pair-as-key-of-unordered-map-issue#comment5439557_4870467 // https://github.com/Revolutionary-Games/Thrive/blob/fd8ab943dd4ced59a8e7d1e4a7b725468b7c2557/src/util/pair_hash.h // taken from boost #ifndef OVERLOAD_PAIR_HASH #define OVERLOAD_PAIR_HASH namespace std { template <typename A, typename B> struct hash<pair<A,B> > { size_t operator()(const pair<A,B>& x) const { std::size_t hashA = std::hash<A>()(x.first); std::size_t hashB = std::hash<B>()(x.second); return hashA ^ (hashB + 0x9e3779b9 + (hashA << 6) + (hashA >> 2)); } }; } #endif namespace xg { using google::sparse_hash_map; using google::sparse_hash_set; template<typename K, typename V> class hash_map : public sparse_hash_map<K,V> { public: hash_map() { this->set_deleted_key(-2); } }; template<typename K, typename V> class string_hash_map : public sparse_hash_map<K,V> { public: string_hash_map() { this->set_deleted_key(""); } }; template<typename K, typename V> class pair_hash_map : public sparse_hash_map<K,V,std::hash<K> > { public: pair_hash_map() { this->set_deleted_key(K(-2, -2)); } }; template<typename K, typename V> class hash_map<K*,V> : public sparse_hash_map<K*,V> { public: hash_map() { this->set_deleted_key((K*)(0)); } }; template<typename K> class hash_set : public sparse_hash_set<K> { public: hash_set() { this->set_deleted_key(-2); } }; template<typename K> class string_hash_set : public sparse_hash_set<K> { public: string_hash_set() { this->set_deleted_key(""); } }; template<typename K> class pair_hash_set : public sparse_hash_set<K,std::hash<K> > { public: pair_hash_set() { this->set_deleted_key(K(-2, -2)); } }; template<typename K> class hash_set<K*> : public sparse_hash_set<K*> { public: hash_set() { this->set_deleted_key((K*)(0)); } }; } #endif <|endoftext|>
<commit_before>/* * ButtonParam.cpp * * Copyright (C) 2008 by Universitaet Stuttgart (VIS). * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmcore/param/ButtonParam.h" #ifdef CUESDK_ENABLED #define CORSAIR_LIGHTING_SDK_DISABLE_DEPRECATION_WARNINGS #include "CUESDK.h" #endif using namespace megamol; using namespace megamol::core::param; /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(void) : AbstractParam(), keycode() { initialize(); } /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(const core::view::KeyCode &keycode) : AbstractParam(), keycode(keycode) { initialize(); } /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(const core::view::Key &key, const core::view::Modifiers &mods) : AbstractParam(), keycode(key, mods) { initialize(); } /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(const core::view::Key &key, const core::view::Modifier &mod) : AbstractParam(), keycode(key, core::view::Modifiers(mod)) { initialize(); } /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(const core::view::Key &key) : AbstractParam(), keycode(key) { initialize(); } /* * ButtonParam::~ButtonParam */ ButtonParam::~ButtonParam(void) { // intentionally empty } /* * ButtonParam::Definition */ void ButtonParam::Definition(vislib::RawStorage& outDef) const { outDef.AssertSize(6 + (2 * sizeof(WORD))); memcpy(outDef.AsAt<char>(0), "MMBUTN", 6); *outDef.AsAt<WORD>(6) = (WORD)this->keycode.key; core::view::Modifiers mods = this->keycode.mods; *outDef.AsAt<WORD>(6 + sizeof(WORD)) = (WORD)mods.toInt(); } /* * ButtonParam::ParseValue */ bool ButtonParam::ParseValue(const vislib::TString& v) { this->setDirty(); return true; } /* * ButtonParam::ValueString */ vislib::TString ButtonParam::ValueString(void) const { // intentionally empty return _T(""); } void ButtonParam::initialize() { this->InitPresentation(AbstractParamPresentation::ParamType::BUTTON); #ifdef CUESDK_ENABLED if (this->keycode.key != view::Key::KEY_UNKNOWN) { // this cannot be done here, the button does not know whether modifiers are pressed or not // needs to be communicated to some frontend service //auto ledColor = CorsairLedColor{ ledId, val, val, val }; //CorsairSetLedsColors(1, &ledColor); } #endif } <commit_msg>parked glfw-key-to-corsair-led table<commit_after>/* * ButtonParam.cpp * * Copyright (C) 2008 by Universitaet Stuttgart (VIS). * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmcore/param/ButtonParam.h" #ifdef CUESDK_ENABLED #define CORSAIR_LIGHTING_SDK_DISABLE_DEPRECATION_WARNINGS #include "CUESDK.h" #include <map> // TODO move somewhere it's needed std::map<megamol::frontend_resources::Key, CorsairLedId> CorsairLEDfromGLFWKey { {megamol::frontend_resources::Key::KEY_ESCAPE, CLK_Escape}, {megamol::frontend_resources::Key::KEY_F1, CLK_F1}, {megamol::frontend_resources::Key::KEY_F2, CLK_F2}, {megamol::frontend_resources::Key::KEY_F3, CLK_F3}, {megamol::frontend_resources::Key::KEY_F4, CLK_F4}, {megamol::frontend_resources::Key::KEY_F5, CLK_F5}, {megamol::frontend_resources::Key::KEY_F6, CLK_F6}, {megamol::frontend_resources::Key::KEY_F7, CLK_F7}, {megamol::frontend_resources::Key::KEY_F8, CLK_F8}, {megamol::frontend_resources::Key::KEY_F9, CLK_F9}, {megamol::frontend_resources::Key::KEY_F10, CLK_F10}, {megamol::frontend_resources::Key::KEY_F11, CLK_F11}, {megamol::frontend_resources::Key::KEY_F12, CLK_F12}, {megamol::frontend_resources::Key::KEY_GRAVE_ACCENT, CLK_GraveAccentAndTilde}, {megamol::frontend_resources::Key::KEY_1, CLK_1}, {megamol::frontend_resources::Key::KEY_2, CLK_2}, {megamol::frontend_resources::Key::KEY_3, CLK_3}, {megamol::frontend_resources::Key::KEY_4, CLK_4}, {megamol::frontend_resources::Key::KEY_5, CLK_5}, {megamol::frontend_resources::Key::KEY_6, CLK_6}, {megamol::frontend_resources::Key::KEY_7, CLK_7}, {megamol::frontend_resources::Key::KEY_8, CLK_8}, {megamol::frontend_resources::Key::KEY_9, CLK_9}, {megamol::frontend_resources::Key::KEY_0, CLK_0}, {megamol::frontend_resources::Key::KEY_MINUS, CLK_MinusAndUnderscore}, {megamol::frontend_resources::Key::KEY_TAB, CLK_Tab}, {megamol::frontend_resources::Key::KEY_Q, CLK_Q}, {megamol::frontend_resources::Key::KEY_W, CLK_W}, {megamol::frontend_resources::Key::KEY_E, CLK_E}, {megamol::frontend_resources::Key::KEY_R, CLK_R}, {megamol::frontend_resources::Key::KEY_T, CLK_T}, {megamol::frontend_resources::Key::KEY_Y, CLK_Y}, {megamol::frontend_resources::Key::KEY_U, CLK_U}, {megamol::frontend_resources::Key::KEY_I, CLK_I}, {megamol::frontend_resources::Key::KEY_O, CLK_O}, {megamol::frontend_resources::Key::KEY_P, CLK_P}, {megamol::frontend_resources::Key::KEY_LEFT_BRACKET, CLK_BracketLeft}, {megamol::frontend_resources::Key::KEY_CAPS_LOCK, CLK_CapsLock}, {megamol::frontend_resources::Key::KEY_A, CLK_A}, {megamol::frontend_resources::Key::KEY_S, CLK_S}, {megamol::frontend_resources::Key::KEY_D, CLK_D}, {megamol::frontend_resources::Key::KEY_F, CLK_F}, {megamol::frontend_resources::Key::KEY_G, CLK_G}, {megamol::frontend_resources::Key::KEY_H, CLK_H}, {megamol::frontend_resources::Key::KEY_J, CLK_J}, {megamol::frontend_resources::Key::KEY_K, CLK_K}, {megamol::frontend_resources::Key::KEY_L, CLK_L}, {megamol::frontend_resources::Key::KEY_SEMICOLON, CLK_SemicolonAndColon}, {megamol::frontend_resources::Key::KEY_APOSTROPHE, CLK_ApostropheAndDoubleQuote}, {megamol::frontend_resources::Key::KEY_LEFT_SHIFT, CLK_LeftShift}, {megamol::frontend_resources::Key::KEY_BACKSLASH, CLK_NonUsBackslash}, {megamol::frontend_resources::Key::KEY_Z, CLK_Z}, {megamol::frontend_resources::Key::KEY_X, CLK_X}, {megamol::frontend_resources::Key::KEY_C, CLK_C}, {megamol::frontend_resources::Key::KEY_V, CLK_V}, {megamol::frontend_resources::Key::KEY_B, CLK_B}, {megamol::frontend_resources::Key::KEY_N, CLK_N}, {megamol::frontend_resources::Key::KEY_M, CLK_M}, {megamol::frontend_resources::Key::KEY_COMMA, CLK_CommaAndLessThan}, {megamol::frontend_resources::Key::KEY_PERIOD, CLK_PeriodAndBiggerThan}, {megamol::frontend_resources::Key::KEY_SLASH, CLK_SlashAndQuestionMark}, {megamol::frontend_resources::Key::KEY_LEFT_CONTROL, CLK_LeftCtrl}, {megamol::frontend_resources::Key::KEY_LEFT_SUPER, CLK_LeftGui}, {megamol::frontend_resources::Key::KEY_LEFT_ALT, CLK_LeftAlt}, //{megamol::frontend_resources::Key::KEY_, CLK_Lang2}, {megamol::frontend_resources::Key::KEY_SPACE, CLK_Space}, //{megamol::frontend_resources::Key::KEY_, CLK_Lang1}, //{megamol::frontend_resources::Key::KEY_, CLK_International2}, {megamol::frontend_resources::Key::KEY_RIGHT_ALT, CLK_RightAlt}, {megamol::frontend_resources::Key::KEY_RIGHT_SUPER, CLK_RightGui}, //{megamol::frontend_resources::Key::KEY_, CLK_Application}, //{megamol::frontend_resources::Key::KEY_, CLK_LedProgramming}, //{megamol::frontend_resources::Key::KEY_, CLK_Brightness}, //{megamol::frontend_resources::Key::KEY_, CLK_F12}, {megamol::frontend_resources::Key::KEY_PRINT_SCREEN, CLK_PrintScreen}, {megamol::frontend_resources::Key::KEY_SCROLL_LOCK, CLK_ScrollLock}, {megamol::frontend_resources::Key::KEY_PAUSE, CLK_PauseBreak}, {megamol::frontend_resources::Key::KEY_INSERT, CLK_Insert}, {megamol::frontend_resources::Key::KEY_HOME, CLK_Home}, {megamol::frontend_resources::Key::KEY_PAGE_UP, CLK_PageUp}, {megamol::frontend_resources::Key::KEY_RIGHT_BRACKET, CLK_BracketRight}, {megamol::frontend_resources::Key::KEY_BACKSLASH, CLK_Backslash}, //{megamol::frontend_resources::Key::KEY_, CLK_NonUsTilde}, {megamol::frontend_resources::Key::KEY_ENTER, CLK_Enter}, //{megamol::frontend_resources::Key::KEY_, CLK_International1}, {megamol::frontend_resources::Key::KEY_EQUAL, CLK_EqualsAndPlus}, //{megamol::frontend_resources::Key::KEY_, CLK_International3}, {megamol::frontend_resources::Key::KEY_BACKSPACE, CLK_Backspace}, {megamol::frontend_resources::Key::KEY_DELETE, CLK_Delete}, {megamol::frontend_resources::Key::KEY_END, CLK_End}, {megamol::frontend_resources::Key::KEY_PAGE_DOWN, CLK_PageDown}, {megamol::frontend_resources::Key::KEY_RIGHT_SHIFT, CLK_RightShift}, {megamol::frontend_resources::Key::KEY_RIGHT_CONTROL, CLK_RightCtrl}, {megamol::frontend_resources::Key::KEY_UP, CLK_UpArrow}, {megamol::frontend_resources::Key::KEY_LEFT, CLK_LeftArrow}, {megamol::frontend_resources::Key::KEY_DOWN, CLK_DownArrow}, {megamol::frontend_resources::Key::KEY_RIGHT, CLK_RightArrow}, //{megamol::frontend_resources::Key::KEY_, CLK_WinLock}, //{megamol::frontend_resources::Key::KEY_, CLK_Mute}, //{megamol::frontend_resources::Key::KEY_, CLK_Stop}, //{megamol::frontend_resources::Key::KEY_, CLK_ScanPreviousTrack}, //{megamol::frontend_resources::Key::KEY_, CLK_PlayPause}, //{megamol::frontend_resources::Key::KEY_, CLK_ScanNextTrack}, {megamol::frontend_resources::Key::KEY_NUM_LOCK, CLK_NumLock}, {megamol::frontend_resources::Key::KEY_KP_DIVIDE, CLK_KeypadSlash}, {megamol::frontend_resources::Key::KEY_KP_MULTIPLY, CLK_KeypadAsterisk}, {megamol::frontend_resources::Key::KEY_KP_SUBTRACT, CLK_KeypadMinus}, {megamol::frontend_resources::Key::KEY_KP_ADD, CLK_KeypadPlus}, {megamol::frontend_resources::Key::KEY_KP_ENTER, CLK_KeypadEnter}, {megamol::frontend_resources::Key::KEY_KP_7, CLK_Keypad7}, {megamol::frontend_resources::Key::KEY_KP_8, CLK_Keypad8}, {megamol::frontend_resources::Key::KEY_KP_9, CLK_Keypad9}, //{megamol::frontend_resources::Key::KEY_KP_DECIMAL, CLK_KeypadComma}, {megamol::frontend_resources::Key::KEY_KP_4, CLK_Keypad4}, {megamol::frontend_resources::Key::KEY_KP_5, CLK_Keypad5}, {megamol::frontend_resources::Key::KEY_KP_6, CLK_Keypad6}, {megamol::frontend_resources::Key::KEY_KP_1, CLK_Keypad1}, {megamol::frontend_resources::Key::KEY_KP_2, CLK_Keypad2}, {megamol::frontend_resources::Key::KEY_KP_3, CLK_Keypad3}, {megamol::frontend_resources::Key::KEY_KP_0, CLK_Keypad0}, {megamol::frontend_resources::Key::KEY_KP_DECIMAL, CLK_KeypadPeriodAndDelete}, //{megamol::frontend_resources::Key::KEY_, CLK_G1}, //{megamol::frontend_resources::Key::KEY_, CLK_G2}, //{megamol::frontend_resources::Key::KEY_, CLK_G3}, //{megamol::frontend_resources::Key::KEY_, CLK_G4}, //{megamol::frontend_resources::Key::KEY_, CLK_G5}, //{megamol::frontend_resources::Key::KEY_, CLK_G6}, //{megamol::frontend_resources::Key::KEY_, CLK_G7}, //{megamol::frontend_resources::Key::KEY_, CLK_G8}, //{megamol::frontend_resources::Key::KEY_, CLK_G9}, //{megamol::frontend_resources::Key::KEY_, CLK_G10}, //{megamol::frontend_resources::Key::KEY_, CLK_VolumeUp}, //{megamol::frontend_resources::Key::KEY_, CLK_VolumeDown}, //{megamol::frontend_resources::Key::KEY_, CLK_MR}, //{megamol::frontend_resources::Key::KEY_, CLK_M1}, //{megamol::frontend_resources::Key::KEY_, CLK_M2}, //{megamol::frontend_resources::Key::KEY_, CLK_M3}, //{megamol::frontend_resources::Key::KEY_, CLK_G11}, //{megamol::frontend_resources::Key::KEY_, CLK_G12}, //{megamol::frontend_resources::Key::KEY_, CLK_G13}, //{megamol::frontend_resources::Key::KEY_, CLK_G14}, //{megamol::frontend_resources::Key::KEY_, CLK_G15}, //{megamol::frontend_resources::Key::KEY_, CLK_G16}, //{megamol::frontend_resources::Key::KEY_, CLK_G17}, //{megamol::frontend_resources::Key::KEY_, CLK_G18}, //{megamol::frontend_resources::Key::KEY_, CLK_International5}, //{megamol::frontend_resources::Key::KEY_, CLK_International4}, }; #endif using namespace megamol; using namespace megamol::core::param; /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(void) : AbstractParam(), keycode() { initialize(); } /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(const core::view::KeyCode &keycode) : AbstractParam(), keycode(keycode) { initialize(); } /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(const core::view::Key &key, const core::view::Modifiers &mods) : AbstractParam(), keycode(key, mods) { initialize(); } /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(const core::view::Key &key, const core::view::Modifier &mod) : AbstractParam(), keycode(key, core::view::Modifiers(mod)) { initialize(); } /* * ButtonParam::ButtonParam */ ButtonParam::ButtonParam(const core::view::Key &key) : AbstractParam(), keycode(key) { initialize(); } /* * ButtonParam::~ButtonParam */ ButtonParam::~ButtonParam(void) { // intentionally empty } /* * ButtonParam::Definition */ void ButtonParam::Definition(vislib::RawStorage& outDef) const { outDef.AssertSize(6 + (2 * sizeof(WORD))); memcpy(outDef.AsAt<char>(0), "MMBUTN", 6); *outDef.AsAt<WORD>(6) = (WORD)this->keycode.key; core::view::Modifiers mods = this->keycode.mods; *outDef.AsAt<WORD>(6 + sizeof(WORD)) = (WORD)mods.toInt(); } /* * ButtonParam::ParseValue */ bool ButtonParam::ParseValue(const vislib::TString& v) { this->setDirty(); return true; } /* * ButtonParam::ValueString */ vislib::TString ButtonParam::ValueString(void) const { // intentionally empty return _T(""); } void ButtonParam::initialize() { this->InitPresentation(AbstractParamPresentation::ParamType::BUTTON); #ifdef CUESDK_ENABLED if (this->keycode.key != view::Key::KEY_UNKNOWN) { // this cannot be done here, the button does not know whether modifiers are pressed or not // needs to be communicated to some frontend service //auto ledColor = CorsairLedColor{ ledId, val, val, val }; //CorsairSetLedsColors(1, &ledColor); } #endif } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qfxtester.h> #include <QDebug> #include <QApplication> #include <qdeclarativeview.h> #include <QFile> #include <QDeclarativeComponent> #include <QDir> #include <QCryptographicHash> #include <private/qabstractanimation_p.h> #include <private/qdeclarativeitem_p.h> QT_BEGIN_NAMESPACE QDeclarativeTester::QDeclarativeTester(const QString &script, QDeclarativeViewer::ScriptOptions opts, QDeclarativeView *parent) : QAbstractAnimation(parent), m_script(script), m_view(parent), filterEvents(true), options(opts), testscript(0), hasCompleted(false), hasFailed(false) { parent->viewport()->installEventFilter(this); parent->installEventFilter(this); QUnifiedTimer::instance()->setConsistentTiming(true); if (options & QDeclarativeViewer::Play) this->run(); start(); } QDeclarativeTester::~QDeclarativeTester() { if (!hasFailed && options & QDeclarativeViewer::Record && options & QDeclarativeViewer::SaveOnExit) save(); } int QDeclarativeTester::duration() const { return -1; } void QDeclarativeTester::addMouseEvent(Destination dest, QMouseEvent *me) { MouseEvent e(me); e.destination = dest; m_mouseEvents << e; } void QDeclarativeTester::addKeyEvent(Destination dest, QKeyEvent *ke) { KeyEvent e(ke); e.destination = dest; m_keyEvents << e; } bool QDeclarativeTester::eventFilter(QObject *o, QEvent *e) { if (!filterEvents) return false; Destination destination; if (o == m_view) { destination = View; } else if (o == m_view->viewport()) { destination = ViewPort; } else { return false; } switch (e->type()) { case QEvent::KeyPress: case QEvent::KeyRelease: addKeyEvent(destination, (QKeyEvent *)e); return true; case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: case QEvent::MouseButtonDblClick: addMouseEvent(destination, (QMouseEvent *)e); return true; default: break; } return false; } void QDeclarativeTester::executefailure() { hasFailed = true; if (options & QDeclarativeViewer::ExitOnFailure) exit(-1); } void QDeclarativeTester::imagefailure() { hasFailed = true; if (options & QDeclarativeViewer::ExitOnFailure) exit(-1); } void QDeclarativeTester::complete() { if ((options & QDeclarativeViewer::TestErrorProperty) && !hasFailed) { QString e = m_view->rootObject()->property("error").toString(); if (!e.isEmpty()) { qWarning() << "Test failed:" << e; hasFailed = true; } } if (options & QDeclarativeViewer::ExitOnComplete) QApplication::exit(hasFailed?-1:0); if (hasCompleted) return; hasCompleted = true; if (options & QDeclarativeViewer::Play) qWarning("Script playback complete"); } void QDeclarativeTester::run() { QDeclarativeComponent c(m_view->engine(), m_script + QLatin1String(".qml")); testscript = qobject_cast<QDeclarativeVisualTest *>(c.create()); if (testscript) testscript->setParent(this); else { executefailure(); exit(-1); } testscriptidx = 0; } void QDeclarativeTester::save() { QString filename = m_script + QLatin1String(".qml"); QFileInfo filenameInfo(filename); QDir saveDir = filenameInfo.absoluteDir(); saveDir.mkpath("."); QFile file(filename); file.open(QIODevice::WriteOnly); QTextStream ts(&file); ts << "import Qt.VisualTest 4.6\n\n"; ts << "VisualTest {\n"; int imgCount = 0; QList<KeyEvent> keyevents = m_savedKeyEvents; QList<MouseEvent> mouseevents = m_savedMouseEvents; for (int ii = 0; ii < m_savedFrameEvents.count(); ++ii) { const FrameEvent &fe = m_savedFrameEvents.at(ii); ts << " Frame {\n"; ts << " msec: " << fe.msec << "\n"; if (!fe.hash.isEmpty()) { ts << " hash: \"" << fe.hash.toHex() << "\"\n"; } else if (!fe.image.isNull()) { QString filename = filenameInfo.baseName() + "." + QString::number(imgCount) + ".png"; fe.image.save(m_script + "." + QString::number(imgCount) + ".png"); imgCount++; ts << " image: \"" << filename << "\"\n"; } ts << " }\n"; while (!mouseevents.isEmpty() && mouseevents.first().msec == fe.msec) { MouseEvent me = mouseevents.takeFirst(); ts << " Mouse {\n"; ts << " type: " << me.type << "\n"; ts << " button: " << me.button << "\n"; ts << " buttons: " << me.buttons << "\n"; ts << " x: " << me.pos.x() << "; y: " << me.pos.y() << "\n"; ts << " modifiers: " << me.modifiers << "\n"; if (me.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } while (!keyevents.isEmpty() && keyevents.first().msec == fe.msec) { KeyEvent ke = keyevents.takeFirst(); ts << " Key {\n"; ts << " type: " << ke.type << "\n"; ts << " key: " << ke.key << "\n"; ts << " modifiers: " << ke.modifiers << "\n"; ts << " text: \"" << ke.text.toUtf8().toHex() << "\"\n"; ts << " autorep: " << (ke.autorep?"true":"false") << "\n"; ts << " count: " << ke.count << "\n"; if (ke.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } } ts << "}\n"; file.close(); } void QDeclarativeTester::updateCurrentTime(int msec) { QDeclarativeItemPrivate::setConsistentTime(msec); QImage img(m_view->width(), m_view->height(), QImage::Format_RGB32); if (options & QDeclarativeViewer::TestImages) { img.fill(qRgb(255,255,255)); QPainter p(&img); m_view->render(&p); } FrameEvent fe; fe.msec = msec; if (msec == 0 || !(options & QDeclarativeViewer::TestImages)) { // Skip first frame, skip if not doing images } else if (0 == (m_savedFrameEvents.count() % 60)) { fe.image = img; } else { QCryptographicHash hash(QCryptographicHash::Md5); hash.addData((const char *)img.bits(), img.bytesPerLine() * img.height()); fe.hash = hash.result(); } m_savedFrameEvents.append(fe); // Deliver mouse events filterEvents = false; if (!testscript) { for (int ii = 0; ii < m_mouseEvents.count(); ++ii) { MouseEvent &me = m_mouseEvents[ii]; me.msec = msec; QMouseEvent event(me.type, me.pos, me.button, me.buttons, me.modifiers); if (me.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } for (int ii = 0; ii < m_keyEvents.count(); ++ii) { KeyEvent &ke = m_keyEvents[ii]; ke.msec = msec; QKeyEvent event(ke.type, ke.key, ke.modifiers, ke.text, ke.autorep, ke.count); if (ke.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } m_savedMouseEvents.append(m_mouseEvents); m_savedKeyEvents.append(m_keyEvents); } m_mouseEvents.clear(); m_keyEvents.clear(); // Advance test script static int imgCount = 0; while (testscript && testscript->count() > testscriptidx) { QObject *event = testscript->event(testscriptidx); if (QDeclarativeVisualTestFrame *frame = qobject_cast<QDeclarativeVisualTestFrame *>(event)) { if (frame->msec() < msec) { if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record)) { qWarning() << "QDeclarativeTester: Extra frame. Seen:" << msec << "Expected:" << frame->msec(); imagefailure(); } } else if (frame->msec() == msec) { if (!frame->hash().isEmpty() && frame->hash().toUtf8() != fe.hash.toHex()) { if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record)) { qWarning() << "QDeclarativeTester: Mismatched frame hash. Seen:" << fe.hash.toHex() << "Expected:" << frame->hash().toUtf8(); imagefailure(); } } } else if (frame->msec() > msec) { break; } if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record) && !frame->image().isEmpty()) { QImage goodImage(frame->image().toLocalFile()); if (goodImage != img) { QString reject(frame->image().toLocalFile() + ".reject.png"); qWarning() << "QDeclarativeTester: Image mismatch. Reject saved to:" << reject; img.save(reject); imagefailure(); } } } else if (QDeclarativeVisualTestMouse *mouse = qobject_cast<QDeclarativeVisualTestMouse *>(event)) { QPoint pos(mouse->x(), mouse->y()); QPoint globalPos = m_view->mapToGlobal(QPoint(0, 0)) + pos; QMouseEvent event((QEvent::Type)mouse->type(), pos, globalPos, (Qt::MouseButton)mouse->button(), (Qt::MouseButtons)mouse->buttons(), (Qt::KeyboardModifiers)mouse->modifiers()); MouseEvent me(&event); me.msec = msec; if (!mouse->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); me.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); me.destination = ViewPort; } m_savedMouseEvents.append(me); } else if (QDeclarativeVisualTestKey *key = qobject_cast<QDeclarativeVisualTestKey *>(event)) { QKeyEvent event((QEvent::Type)key->type(), key->key(), (Qt::KeyboardModifiers)key->modifiers(), QString::fromUtf8(QByteArray::fromHex(key->text().toUtf8())), key->autorep(), key->count()); KeyEvent ke(&event); ke.msec = msec; if (!key->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); ke.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); ke.destination = ViewPort; } m_savedKeyEvents.append(ke); } testscriptidx++; } filterEvents = true; if (testscript && testscript->count() <= testscriptidx) complete(); } void QDeclarativeTester::registerTypes() { QML_REGISTER_TYPE(Qt.VisualTest, 4,6, VisualTest, QDeclarativeVisualTest); QML_REGISTER_TYPE(Qt.VisualTest, 4,6, Frame, QDeclarativeVisualTestFrame); QML_REGISTER_TYPE(Qt.VisualTest, 4,6, Mouse, QDeclarativeVisualTestMouse); QML_REGISTER_TYPE(Qt.VisualTest, 4,6, Key, QDeclarativeVisualTestKey); } QT_END_NAMESPACE <commit_msg>Compile warning-- for qmlviewer<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qfxtester.h> #include <QDebug> #include <QApplication> #include <qdeclarativeview.h> #include <QFile> #include <QDeclarativeComponent> #include <QDir> #include <QCryptographicHash> #include <private/qabstractanimation_p.h> #include <private/qdeclarativeitem_p.h> QT_BEGIN_NAMESPACE QDeclarativeTester::QDeclarativeTester(const QString &script, QDeclarativeViewer::ScriptOptions opts, QDeclarativeView *parent) : QAbstractAnimation(parent), m_script(script), m_view(parent), filterEvents(true), options(opts), testscript(0), hasCompleted(false), hasFailed(false) { parent->viewport()->installEventFilter(this); parent->installEventFilter(this); QUnifiedTimer::instance()->setConsistentTiming(true); if (options & QDeclarativeViewer::Play) this->run(); start(); } QDeclarativeTester::~QDeclarativeTester() { if (!hasFailed && options & QDeclarativeViewer::Record && options & QDeclarativeViewer::SaveOnExit) save(); } int QDeclarativeTester::duration() const { return -1; } void QDeclarativeTester::addMouseEvent(Destination dest, QMouseEvent *me) { MouseEvent e(me); e.destination = dest; m_mouseEvents << e; } void QDeclarativeTester::addKeyEvent(Destination dest, QKeyEvent *ke) { KeyEvent e(ke); e.destination = dest; m_keyEvents << e; } bool QDeclarativeTester::eventFilter(QObject *o, QEvent *e) { if (!filterEvents) return false; Destination destination; if (o == m_view) { destination = View; } else if (o == m_view->viewport()) { destination = ViewPort; } else { return false; } switch (e->type()) { case QEvent::KeyPress: case QEvent::KeyRelease: addKeyEvent(destination, (QKeyEvent *)e); return true; case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: case QEvent::MouseButtonDblClick: addMouseEvent(destination, (QMouseEvent *)e); return true; default: break; } return false; } void QDeclarativeTester::executefailure() { hasFailed = true; if (options & QDeclarativeViewer::ExitOnFailure) exit(-1); } void QDeclarativeTester::imagefailure() { hasFailed = true; if (options & QDeclarativeViewer::ExitOnFailure) exit(-1); } void QDeclarativeTester::complete() { if ((options & QDeclarativeViewer::TestErrorProperty) && !hasFailed) { QString e = m_view->rootObject()->property("error").toString(); if (!e.isEmpty()) { qWarning() << "Test failed:" << e; hasFailed = true; } } if (options & QDeclarativeViewer::ExitOnComplete) QApplication::exit(hasFailed?-1:0); if (hasCompleted) return; hasCompleted = true; if (options & QDeclarativeViewer::Play) qWarning("Script playback complete"); } void QDeclarativeTester::run() { QDeclarativeComponent c(m_view->engine(), m_script + QLatin1String(".qml")); testscript = qobject_cast<QDeclarativeVisualTest *>(c.create()); if (testscript) testscript->setParent(this); else { executefailure(); exit(-1); } testscriptidx = 0; } void QDeclarativeTester::save() { QString filename = m_script + QLatin1String(".qml"); QFileInfo filenameInfo(filename); QDir saveDir = filenameInfo.absoluteDir(); saveDir.mkpath("."); QFile file(filename); file.open(QIODevice::WriteOnly); QTextStream ts(&file); ts << "import Qt.VisualTest 4.6\n\n"; ts << "VisualTest {\n"; int imgCount = 0; QList<KeyEvent> keyevents = m_savedKeyEvents; QList<MouseEvent> mouseevents = m_savedMouseEvents; for (int ii = 0; ii < m_savedFrameEvents.count(); ++ii) { const FrameEvent &fe = m_savedFrameEvents.at(ii); ts << " Frame {\n"; ts << " msec: " << fe.msec << "\n"; if (!fe.hash.isEmpty()) { ts << " hash: \"" << fe.hash.toHex() << "\"\n"; } else if (!fe.image.isNull()) { QString filename = filenameInfo.baseName() + "." + QString::number(imgCount) + ".png"; fe.image.save(m_script + "." + QString::number(imgCount) + ".png"); imgCount++; ts << " image: \"" << filename << "\"\n"; } ts << " }\n"; while (!mouseevents.isEmpty() && mouseevents.first().msec == fe.msec) { MouseEvent me = mouseevents.takeFirst(); ts << " Mouse {\n"; ts << " type: " << me.type << "\n"; ts << " button: " << me.button << "\n"; ts << " buttons: " << me.buttons << "\n"; ts << " x: " << me.pos.x() << "; y: " << me.pos.y() << "\n"; ts << " modifiers: " << me.modifiers << "\n"; if (me.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } while (!keyevents.isEmpty() && keyevents.first().msec == fe.msec) { KeyEvent ke = keyevents.takeFirst(); ts << " Key {\n"; ts << " type: " << ke.type << "\n"; ts << " key: " << ke.key << "\n"; ts << " modifiers: " << ke.modifiers << "\n"; ts << " text: \"" << ke.text.toUtf8().toHex() << "\"\n"; ts << " autorep: " << (ke.autorep?"true":"false") << "\n"; ts << " count: " << ke.count << "\n"; if (ke.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } } ts << "}\n"; file.close(); } void QDeclarativeTester::updateCurrentTime(int msec) { QDeclarativeItemPrivate::setConsistentTime(msec); QImage img(m_view->width(), m_view->height(), QImage::Format_RGB32); if (options & QDeclarativeViewer::TestImages) { img.fill(qRgb(255,255,255)); QPainter p(&img); m_view->render(&p); } FrameEvent fe; fe.msec = msec; if (msec == 0 || !(options & QDeclarativeViewer::TestImages)) { // Skip first frame, skip if not doing images } else if (0 == (m_savedFrameEvents.count() % 60)) { fe.image = img; } else { QCryptographicHash hash(QCryptographicHash::Md5); hash.addData((const char *)img.bits(), img.bytesPerLine() * img.height()); fe.hash = hash.result(); } m_savedFrameEvents.append(fe); // Deliver mouse events filterEvents = false; if (!testscript) { for (int ii = 0; ii < m_mouseEvents.count(); ++ii) { MouseEvent &me = m_mouseEvents[ii]; me.msec = msec; QMouseEvent event(me.type, me.pos, me.button, me.buttons, me.modifiers); if (me.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } for (int ii = 0; ii < m_keyEvents.count(); ++ii) { KeyEvent &ke = m_keyEvents[ii]; ke.msec = msec; QKeyEvent event(ke.type, ke.key, ke.modifiers, ke.text, ke.autorep, ke.count); if (ke.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } m_savedMouseEvents.append(m_mouseEvents); m_savedKeyEvents.append(m_keyEvents); } m_mouseEvents.clear(); m_keyEvents.clear(); // Advance test script while (testscript && testscript->count() > testscriptidx) { QObject *event = testscript->event(testscriptidx); if (QDeclarativeVisualTestFrame *frame = qobject_cast<QDeclarativeVisualTestFrame *>(event)) { if (frame->msec() < msec) { if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record)) { qWarning() << "QDeclarativeTester: Extra frame. Seen:" << msec << "Expected:" << frame->msec(); imagefailure(); } } else if (frame->msec() == msec) { if (!frame->hash().isEmpty() && frame->hash().toUtf8() != fe.hash.toHex()) { if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record)) { qWarning() << "QDeclarativeTester: Mismatched frame hash. Seen:" << fe.hash.toHex() << "Expected:" << frame->hash().toUtf8(); imagefailure(); } } } else if (frame->msec() > msec) { break; } if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record) && !frame->image().isEmpty()) { QImage goodImage(frame->image().toLocalFile()); if (goodImage != img) { QString reject(frame->image().toLocalFile() + ".reject.png"); qWarning() << "QDeclarativeTester: Image mismatch. Reject saved to:" << reject; img.save(reject); imagefailure(); } } } else if (QDeclarativeVisualTestMouse *mouse = qobject_cast<QDeclarativeVisualTestMouse *>(event)) { QPoint pos(mouse->x(), mouse->y()); QPoint globalPos = m_view->mapToGlobal(QPoint(0, 0)) + pos; QMouseEvent event((QEvent::Type)mouse->type(), pos, globalPos, (Qt::MouseButton)mouse->button(), (Qt::MouseButtons)mouse->buttons(), (Qt::KeyboardModifiers)mouse->modifiers()); MouseEvent me(&event); me.msec = msec; if (!mouse->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); me.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); me.destination = ViewPort; } m_savedMouseEvents.append(me); } else if (QDeclarativeVisualTestKey *key = qobject_cast<QDeclarativeVisualTestKey *>(event)) { QKeyEvent event((QEvent::Type)key->type(), key->key(), (Qt::KeyboardModifiers)key->modifiers(), QString::fromUtf8(QByteArray::fromHex(key->text().toUtf8())), key->autorep(), key->count()); KeyEvent ke(&event); ke.msec = msec; if (!key->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); ke.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); ke.destination = ViewPort; } m_savedKeyEvents.append(ke); } testscriptidx++; } filterEvents = true; if (testscript && testscript->count() <= testscriptidx) complete(); } void QDeclarativeTester::registerTypes() { QML_REGISTER_TYPE(Qt.VisualTest, 4,6, VisualTest, QDeclarativeVisualTest); QML_REGISTER_TYPE(Qt.VisualTest, 4,6, Frame, QDeclarativeVisualTestFrame); QML_REGISTER_TYPE(Qt.VisualTest, 4,6, Mouse, QDeclarativeVisualTestMouse); QML_REGISTER_TYPE(Qt.VisualTest, 4,6, Key, QDeclarativeVisualTestKey); } QT_END_NAMESPACE <|endoftext|>
<commit_before>/* * Copyright (c) 2004 The Regents of The University of Michigan * 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 copyright holders 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 * linux_system.cc loads the linux kernel, console, pal and patches certain functions. * The symbol tables are loaded so that traces can show the executing function and we can * skip functions. Various delay loops are skipped and their final values manually computed to * speed up boot time. */ #include "base/loader/aout_object.hh" #include "base/loader/elf_object.hh" #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "base/remote_gdb.hh" #include "base/trace.hh" #include "cpu/exec_context.hh" #include "cpu/base_cpu.hh" #include "kern/linux/linux_events.hh" #include "kern/linux/linux_system.hh" #include "kern/system_events.hh" #include "mem/functional_mem/memory_control.hh" #include "mem/functional_mem/physical_memory.hh" #include "sim/builder.hh" #include "dev/platform.hh" #include "targetarch/isa_traits.hh" #include "targetarch/vtophys.hh" extern SymbolTable *debugSymbolTable; using namespace std; LinuxSystem::LinuxSystem(const string _name, const uint64_t _init_param, MemoryController *_memCtrl, PhysicalMemory *_physmem, const string &kernel_path, const string &console_path, const string &palcode, const string &boot_osflags, const bool _bin, const vector<string> &_binned_fns) : System(_name, _init_param, _memCtrl, _physmem, _bin, _binned_fns), bin(_bin), binned_fns(_binned_fns) { kernelSymtab = new SymbolTable; consoleSymtab = new SymbolTable; /** * Load the kernel, pal, and console code into memory */ // Load kernel code ObjectFile *kernel = createObjectFile(kernel_path); if (kernel == NULL) fatal("Could not load kernel file %s", kernel_path); // Load Console Code ObjectFile *console = createObjectFile(console_path); if (console == NULL) fatal("Could not load console file %s", console_path); // Load pal file ObjectFile *pal = createObjectFile(palcode); if (pal == NULL) fatal("Could not load PALcode file %s", palcode); pal->loadSections(physmem, true); // Load console file console->loadSections(physmem, true); // Load kernel file kernel->loadSections(physmem, true); kernelStart = kernel->textBase(); kernelEnd = kernel->bssBase() + kernel->bssSize(); kernelEntry = kernel->entryPoint(); // load symbols if (!kernel->loadGlobalSymbols(kernelSymtab)) panic("could not load kernel symbols\n"); debugSymbolTable = kernelSymtab; if (!kernel->loadLocalSymbols(kernelSymtab)) panic("could not load kernel local symbols\n"); if (!console->loadGlobalSymbols(consoleSymtab)) panic("could not load console symbols\n"); DPRINTF(Loader, "Kernel start = %#x\n" "Kernel end = %#x\n" "Kernel entry = %#x\n", kernelStart, kernelEnd, kernelEntry); DPRINTF(Loader, "Kernel loaded...\n"); #ifdef DEBUG kernelPanicEvent = new BreakPCEvent(&pcEventQueue, "kernel panic"); consolePanicEvent = new BreakPCEvent(&pcEventQueue, "console panic"); #endif skipIdeDelay50msEvent = new SkipFuncEvent(&pcEventQueue, "ide_delay_50ms"); skipDelayLoopEvent = new LinuxSkipDelayLoopEvent(&pcEventQueue, "calibrate_delay"); skipCacheProbeEvent = new SkipFuncEvent(&pcEventQueue, "determine_cpu_caches"); Addr addr = 0; /** * find the address of the est_cycle_freq variable and insert it so we don't * through the lengthly process of trying to calculated it by using the PIT, * RTC, etc. */ if (kernelSymtab->findAddress("est_cycle_freq", addr)) { Addr paddr = vtophys(physmem, addr); uint8_t *est_cycle_frequency = physmem->dma_addr(paddr, sizeof(uint64_t)); if (est_cycle_frequency) *(uint64_t *)est_cycle_frequency = htoa(ticksPerSecond); } /** * Copy the osflags (kernel arguments) into the consoles memory. Presently * Linux does use the console service routine to get these command line * arguments, but we might as well make them available just in case. */ if (consoleSymtab->findAddress("env_booted_osflags", addr)) { Addr paddr = vtophys(physmem, addr); char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t)); if (osflags) strcpy(osflags, boot_osflags.c_str()); } /** * Since we aren't using a bootloader, we have to copy the kernel arguments * directly into the kernels memory. */ { Addr paddr = vtophys(physmem, PARAM_ADDR); char *commandline = (char*)physmem->dma_addr(paddr, sizeof(uint64_t)); if (commandline) strcpy(commandline, boot_osflags.c_str()); } /** * Set the hardware reset parameter block system type and revision information * to Tsunami. */ if (consoleSymtab->findAddress("xxm_rpb", addr)) { Addr paddr = vtophys(physmem, addr); char *hwprb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (hwprb) { *(uint64_t*)(hwprb+0x50) = htoa(ULL(34)); // Tsunami *(uint64_t*)(hwprb+0x58) = htoa(ULL(1)<<10); // Plain DP264 } else panic("could not translate hwprb addr to set system type/variation\n"); } else panic("could not find hwprb to set system type/variation\n"); #ifdef DEBUG if (kernelSymtab->findAddress("panic", addr)) kernelPanicEvent->schedule(addr); else panic("could not find kernel symbol \'panic\'"); if (consoleSymtab->findAddress("panic", addr)) consolePanicEvent->schedule(addr); #endif /** * Any time ide_delay_50ms, calibarte_delay or determine_cpu_caches is called * just skip the function. Currently determine_cpu_caches only is used put * information in proc, however if that changes in the future we will have to * fill in the cache size variables appropriately. */ if (kernelSymtab->findAddress("ide_delay_50ms", addr)) skipIdeDelay50msEvent->schedule(addr+sizeof(MachInst)); if (kernelSymtab->findAddress("calibrate_delay", addr)) skipDelayLoopEvent->schedule(addr+sizeof(MachInst)); if (kernelSymtab->findAddress("determine_cpu_caches", addr)) skipCacheProbeEvent->schedule(addr+sizeof(MachInst)); } LinuxSystem::~LinuxSystem() { delete kernel; delete console; delete kernelSymtab; delete consoleSymtab; delete kernelPanicEvent; delete consolePanicEvent; delete skipIdeDelay50msEvent; delete skipDelayLoopEvent; delete skipCacheProbeEvent; } void LinuxSystem::setDelayLoop(ExecContext *xc) { Addr addr = 0; if (kernelSymtab->findAddress("loops_per_jiffy", addr)) { Addr paddr = vtophys(physmem, addr); uint8_t *loops_per_jiffy = physmem->dma_addr(paddr, sizeof(uint32_t)); Tick cpuFreq = xc->cpu->getFreq(); Tick intrFreq = platform->interrupt_frequency; *(uint32_t *)loops_per_jiffy = (uint32_t)((cpuFreq / intrFreq) * 0.9988); } } int LinuxSystem::registerExecContext(ExecContext *xc) { int xcIndex = System::registerExecContext(xc); if (xcIndex == 0) { // activate with zero delay so that we start ticking right // away on cycle 0 xc->activate(0); } RemoteGDB *rgdb = new RemoteGDB(this, xc); GDBListener *gdbl = new GDBListener(rgdb, 7000 + xcIndex); gdbl->listen(); /** * Uncommenting this line waits for a remote debugger to connect * to the simulator before continuing. */ //gdbl->accept(); if (remoteGDB.size() <= xcIndex) { remoteGDB.resize(xcIndex+1); } remoteGDB[xcIndex] = rgdb; return xcIndex; } void LinuxSystem::replaceExecContext(ExecContext *xc, int xcIndex) { System::replaceExecContext(xcIndex, xc); remoteGDB[xcIndex]->replaceExecContext(xc); } bool LinuxSystem::breakpoint() { return remoteGDB[0]->trap(ALPHA_KENTRY_IF); } BEGIN_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem) Param<bool> bin; SimObjectParam<MemoryController *> mem_ctl; SimObjectParam<PhysicalMemory *> physmem; Param<uint64_t> init_param; Param<string> kernel_code; Param<string> console_code; Param<string> pal_code; Param<string> boot_osflags; VectorParam<string> binned_fns; END_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem) BEGIN_INIT_SIM_OBJECT_PARAMS(LinuxSystem) INIT_PARAM_DFLT(bin, "is this system to be binned", false), INIT_PARAM(mem_ctl, "memory controller"), INIT_PARAM(physmem, "phsyical memory"), INIT_PARAM_DFLT(init_param, "numerical value to pass into simulator", 0), INIT_PARAM(kernel_code, "file that contains the code"), INIT_PARAM(console_code, "file that contains the console code"), INIT_PARAM(pal_code, "file that contains palcode"), INIT_PARAM_DFLT(boot_osflags, "flags to pass to the kernel during boot", "a"), INIT_PARAM(binned_fns, "functions to be broken down and binned") END_INIT_SIM_OBJECT_PARAMS(LinuxSystem) CREATE_SIM_OBJECT(LinuxSystem) { LinuxSystem *sys = new LinuxSystem(getInstanceName(), init_param, mem_ctl, physmem, kernel_code, console_code, pal_code, boot_osflags, bin, binned_fns); return sys; } REGISTER_SIM_OBJECT("LinuxSystem", LinuxSystem) <commit_msg>Update MAX ASN in kernel to 127 since that's what the ev5 supports<commit_after>/* * Copyright (c) 2004 The Regents of The University of Michigan * 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 copyright holders 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 * linux_system.cc loads the linux kernel, console, pal and patches certain functions. * The symbol tables are loaded so that traces can show the executing function and we can * skip functions. Various delay loops are skipped and their final values manually computed to * speed up boot time. */ #include "base/loader/aout_object.hh" #include "base/loader/elf_object.hh" #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "base/remote_gdb.hh" #include "base/trace.hh" #include "cpu/exec_context.hh" #include "cpu/base_cpu.hh" #include "kern/linux/linux_events.hh" #include "kern/linux/linux_system.hh" #include "kern/system_events.hh" #include "mem/functional_mem/memory_control.hh" #include "mem/functional_mem/physical_memory.hh" #include "sim/builder.hh" #include "dev/platform.hh" #include "targetarch/isa_traits.hh" #include "targetarch/vtophys.hh" #include "sim/debug.hh" extern SymbolTable *debugSymbolTable; using namespace std; LinuxSystem::LinuxSystem(const string _name, const uint64_t _init_param, MemoryController *_memCtrl, PhysicalMemory *_physmem, const string &kernel_path, const string &console_path, const string &palcode, const string &boot_osflags, const bool _bin, const vector<string> &_binned_fns) : System(_name, _init_param, _memCtrl, _physmem, _bin, _binned_fns), bin(_bin), binned_fns(_binned_fns) { kernelSymtab = new SymbolTable; consoleSymtab = new SymbolTable; /** * Load the kernel, pal, and console code into memory */ // Load kernel code ObjectFile *kernel = createObjectFile(kernel_path); if (kernel == NULL) fatal("Could not load kernel file %s", kernel_path); // Load Console Code ObjectFile *console = createObjectFile(console_path); if (console == NULL) fatal("Could not load console file %s", console_path); // Load pal file ObjectFile *pal = createObjectFile(palcode); if (pal == NULL) fatal("Could not load PALcode file %s", palcode); pal->loadSections(physmem, true); // Load console file console->loadSections(physmem, true); // Load kernel file kernel->loadSections(physmem, true); kernelStart = kernel->textBase(); kernelEnd = kernel->bssBase() + kernel->bssSize(); kernelEntry = kernel->entryPoint(); // load symbols if (!kernel->loadGlobalSymbols(kernelSymtab)) panic("could not load kernel symbols\n"); debugSymbolTable = kernelSymtab; if (!kernel->loadLocalSymbols(kernelSymtab)) panic("could not load kernel local symbols\n"); if (!console->loadGlobalSymbols(consoleSymtab)) panic("could not load console symbols\n"); DPRINTF(Loader, "Kernel start = %#x\n" "Kernel end = %#x\n" "Kernel entry = %#x\n", kernelStart, kernelEnd, kernelEntry); DPRINTF(Loader, "Kernel loaded...\n"); #ifdef DEBUG kernelPanicEvent = new BreakPCEvent(&pcEventQueue, "kernel panic"); consolePanicEvent = new BreakPCEvent(&pcEventQueue, "console panic"); #endif skipIdeDelay50msEvent = new SkipFuncEvent(&pcEventQueue, "ide_delay_50ms"); skipDelayLoopEvent = new LinuxSkipDelayLoopEvent(&pcEventQueue, "calibrate_delay"); skipCacheProbeEvent = new SkipFuncEvent(&pcEventQueue, "determine_cpu_caches"); Addr addr = 0; /** * find the address of the est_cycle_freq variable and insert it so we don't * through the lengthly process of trying to calculated it by using the PIT, * RTC, etc. */ if (kernelSymtab->findAddress("est_cycle_freq", addr)) { Addr paddr = vtophys(physmem, addr); uint8_t *est_cycle_frequency = physmem->dma_addr(paddr, sizeof(uint64_t)); if (est_cycle_frequency) *(uint64_t *)est_cycle_frequency = htoa(ticksPerSecond); } /** * Copy the osflags (kernel arguments) into the consoles memory. Presently * Linux does use the console service routine to get these command line * arguments, but we might as well make them available just in case. */ if (consoleSymtab->findAddress("env_booted_osflags", addr)) { Addr paddr = vtophys(physmem, addr); char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t)); if (osflags) strcpy(osflags, boot_osflags.c_str()); } /** * Since we aren't using a bootloader, we have to copy the kernel arguments * directly into the kernels memory. */ { Addr paddr = vtophys(physmem, PARAM_ADDR); char *commandline = (char*)physmem->dma_addr(paddr, sizeof(uint64_t)); if (commandline) strcpy(commandline, boot_osflags.c_str()); } /** * Set the hardware reset parameter block system type and revision information * to Tsunami. */ if (consoleSymtab->findAddress("xxm_rpb", addr)) { Addr paddr = vtophys(physmem, addr); char *hwprb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (hwprb) { *(uint64_t*)(hwprb+0x50) = htoa(ULL(34)); // Tsunami *(uint64_t*)(hwprb+0x58) = htoa(ULL(1)<<10); // Plain DP264 } else panic("could not translate hwprb addr to set system type/variation\n"); } else panic("could not find hwprb to set system type/variation\n"); /** * EV5 only supports 127 ASNs so we are going to tell the kernel that the * paritiuclar EV6 we have only supports 127 asns. * @todo At some point we should change ev5.hh and the palcode to support * 255 ASNs. */ if (kernelSymtab->findAddress("dp264_mv", addr)) { Addr paddr = vtophys(physmem, addr); char *dp264_mv = (char *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (dp264_mv) { *(uint32_t*)(dp264_mv+0x18) = htoa((uint32_t)127); } else panic("could not translate dp264_mv addr to set the MAX_ASN to 127\n"); } else panic("could not find dp264_mv to set the MAX_ASN to 127\n"); #ifdef DEBUG if (kernelSymtab->findAddress("panic", addr)) kernelPanicEvent->schedule(addr); else panic("could not find kernel symbol \'panic\'"); if (consoleSymtab->findAddress("panic", addr)) consolePanicEvent->schedule(addr); #endif /** * Any time ide_delay_50ms, calibarte_delay or determine_cpu_caches is called * just skip the function. Currently determine_cpu_caches only is used put * information in proc, however if that changes in the future we will have to * fill in the cache size variables appropriately. */ if (kernelSymtab->findAddress("ide_delay_50ms", addr)) skipIdeDelay50msEvent->schedule(addr+sizeof(MachInst)); if (kernelSymtab->findAddress("calibrate_delay", addr)) skipDelayLoopEvent->schedule(addr+sizeof(MachInst)); if (kernelSymtab->findAddress("determine_cpu_caches", addr)) skipCacheProbeEvent->schedule(addr+sizeof(MachInst)); } LinuxSystem::~LinuxSystem() { delete kernel; delete console; delete kernelSymtab; delete consoleSymtab; delete kernelPanicEvent; delete consolePanicEvent; delete skipIdeDelay50msEvent; delete skipDelayLoopEvent; delete skipCacheProbeEvent; } void LinuxSystem::setDelayLoop(ExecContext *xc) { Addr addr = 0; if (kernelSymtab->findAddress("loops_per_jiffy", addr)) { Addr paddr = vtophys(physmem, addr); uint8_t *loops_per_jiffy = physmem->dma_addr(paddr, sizeof(uint32_t)); Tick cpuFreq = xc->cpu->getFreq(); Tick intrFreq = platform->interrupt_frequency; *(uint32_t *)loops_per_jiffy = (uint32_t)((cpuFreq / intrFreq) * 0.9988); } } int LinuxSystem::registerExecContext(ExecContext *xc) { int xcIndex = System::registerExecContext(xc); if (xcIndex == 0) { // activate with zero delay so that we start ticking right // away on cycle 0 xc->activate(0); } RemoteGDB *rgdb = new RemoteGDB(this, xc); GDBListener *gdbl = new GDBListener(rgdb, 7000 + xcIndex); gdbl->listen(); /** * Uncommenting this line waits for a remote debugger to connect * to the simulator before continuing. */ //gdbl->accept(); if (remoteGDB.size() <= xcIndex) { remoteGDB.resize(xcIndex+1); } remoteGDB[xcIndex] = rgdb; return xcIndex; } void LinuxSystem::replaceExecContext(ExecContext *xc, int xcIndex) { System::replaceExecContext(xcIndex, xc); remoteGDB[xcIndex]->replaceExecContext(xc); } bool LinuxSystem::breakpoint() { return remoteGDB[0]->trap(ALPHA_KENTRY_IF); } BEGIN_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem) Param<bool> bin; SimObjectParam<MemoryController *> mem_ctl; SimObjectParam<PhysicalMemory *> physmem; Param<uint64_t> init_param; Param<string> kernel_code; Param<string> console_code; Param<string> pal_code; Param<string> boot_osflags; VectorParam<string> binned_fns; END_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem) BEGIN_INIT_SIM_OBJECT_PARAMS(LinuxSystem) INIT_PARAM_DFLT(bin, "is this system to be binned", false), INIT_PARAM(mem_ctl, "memory controller"), INIT_PARAM(physmem, "phsyical memory"), INIT_PARAM_DFLT(init_param, "numerical value to pass into simulator", 0), INIT_PARAM(kernel_code, "file that contains the code"), INIT_PARAM(console_code, "file that contains the console code"), INIT_PARAM(pal_code, "file that contains palcode"), INIT_PARAM_DFLT(boot_osflags, "flags to pass to the kernel during boot", "a"), INIT_PARAM(binned_fns, "functions to be broken down and binned") END_INIT_SIM_OBJECT_PARAMS(LinuxSystem) CREATE_SIM_OBJECT(LinuxSystem) { LinuxSystem *sys = new LinuxSystem(getInstanceName(), init_param, mem_ctl, physmem, kernel_code, console_code, pal_code, boot_osflags, bin, binned_fns); return sys; } REGISTER_SIM_OBJECT("LinuxSystem", LinuxSystem) <|endoftext|>
<commit_before>/* * Copyright (c) 2004 The Regents of The University of Michigan * 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 copyright holders 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 * linux_system.cc loads the linux kernel, console, pal and patches certain functions. * The symbol tables are loaded so that traces can show the executing function and we can * skip functions. Various delay loops are skipped and their final values manually computed to * speed up boot time. */ #include "base/loader/aout_object.hh" #include "base/loader/elf_object.hh" #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "base/remote_gdb.hh" #include "base/trace.hh" #include "cpu/exec_context.hh" #include "cpu/base_cpu.hh" #include "kern/linux/linux_events.hh" #include "kern/linux/linux_system.hh" #include "kern/system_events.hh" #include "mem/functional_mem/memory_control.hh" #include "mem/functional_mem/physical_memory.hh" #include "sim/builder.hh" #include "dev/platform.hh" #include "targetarch/isa_traits.hh" #include "targetarch/vtophys.hh" extern SymbolTable *debugSymbolTable; using namespace std; LinuxSystem::LinuxSystem(const string _name, const uint64_t _init_param, MemoryController *_memCtrl, PhysicalMemory *_physmem, const string &kernel_path, const string &console_path, const string &palcode, const string &boot_osflags, const bool _bin, const vector<string> &_binned_fns) : System(_name, _init_param, _memCtrl, _physmem, _bin, _binned_fns), bin(_bin), binned_fns(_binned_fns) { kernelSymtab = new SymbolTable; consoleSymtab = new SymbolTable; /** * Load the kernel, pal, and console code into memory */ // Load kernel code ObjectFile *kernel = createObjectFile(kernel_path); if (kernel == NULL) fatal("Could not load kernel file %s", kernel_path); // Load Console Code ObjectFile *console = createObjectFile(console_path); if (console == NULL) fatal("Could not load console file %s", console_path); // Load pal file ObjectFile *pal = createObjectFile(palcode); if (pal == NULL) fatal("Could not load PALcode file %s", palcode); pal->loadSections(physmem, true); // Load console file console->loadSections(physmem, true); // Load kernel file kernel->loadSections(physmem, true); kernelStart = kernel->textBase(); kernelEnd = kernel->bssBase() + kernel->bssSize(); kernelEntry = kernel->entryPoint(); // load symbols if (!kernel->loadGlobalSymbols(kernelSymtab)) panic("could not load kernel symbols\n"); debugSymbolTable = kernelSymtab; if (!kernel->loadLocalSymbols(kernelSymtab)) panic("could not load kernel local symbols\n"); if (!console->loadGlobalSymbols(consoleSymtab)) panic("could not load console symbols\n"); DPRINTF(Loader, "Kernel start = %#x\n" "Kernel end = %#x\n" "Kernel entry = %#x\n", kernelStart, kernelEnd, kernelEntry); DPRINTF(Loader, "Kernel loaded...\n"); #ifdef DEBUG kernelPanicEvent = new BreakPCEvent(&pcEventQueue, "kernel panic"); consolePanicEvent = new BreakPCEvent(&pcEventQueue, "console panic"); #endif skipIdeDelay50msEvent = new SkipFuncEvent(&pcEventQueue, "ide_delay_50ms"); skipDelayLoopEvent = new LinuxSkipDelayLoopEvent(&pcEventQueue, "calibrate_delay"); skipCacheProbeEvent = new SkipFuncEvent(&pcEventQueue, "determine_cpu_caches"); Addr addr = 0; /** * find the address of the est_cycle_freq variable and insert it so we don't * through the lengthly process of trying to calculated it by using the PIT, * RTC, etc. */ if (kernelSymtab->findAddress("est_cycle_freq", addr)) { Addr paddr = vtophys(physmem, addr); uint8_t *est_cycle_frequency = physmem->dma_addr(paddr, sizeof(uint64_t)); if (est_cycle_frequency) *(uint64_t *)est_cycle_frequency = htoa(ticksPerSecond); } /** * Copy the osflags (kernel arguments) into the consoles memory. Presently * Linux does use the console service routine to get these command line * arguments, but we might as well make them available just in case. */ if (consoleSymtab->findAddress("env_booted_osflags", addr)) { Addr paddr = vtophys(physmem, addr); char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t)); if (osflags) strcpy(osflags, boot_osflags.c_str()); } /** * Since we aren't using a bootloader, we have to copy the kernel arguments * directly into the kernels memory. */ { Addr paddr = vtophys(physmem, PARAM_ADDR); char *commandline = (char*)physmem->dma_addr(paddr, sizeof(uint64_t)); if (commandline) strcpy(commandline, boot_osflags.c_str()); } /** * Set the hardware reset parameter block system type and revision information * to Tsunami. */ if (consoleSymtab->findAddress("xxm_rpb", addr)) { Addr paddr = vtophys(physmem, addr); char *hwprb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (hwprb) { *(uint64_t*)(hwprb+0x50) = htoa(ULL(34)); // Tsunami *(uint64_t*)(hwprb+0x58) = htoa(ULL(1)<<10); // Plain DP264 } else panic("could not translate hwprb addr to set system type/variation\n"); } else panic("could not find hwprb to set system type/variation\n"); #ifdef DEBUG if (kernelSymtab->findAddress("panic", addr)) kernelPanicEvent->schedule(addr); else panic("could not find kernel symbol \'panic\'"); if (consoleSymtab->findAddress("panic", addr)) consolePanicEvent->schedule(addr); #endif /** * Any time ide_delay_50ms, calibarte_delay or determine_cpu_caches is called * just skip the function. Currently determine_cpu_caches only is used put * information in proc, however if that changes in the future we will have to * fill in the cache size variables appropriately. */ if (kernelSymtab->findAddress("ide_delay_50ms", addr)) skipIdeDelay50msEvent->schedule(addr+sizeof(MachInst)); if (kernelSymtab->findAddress("calibrate_delay", addr)) skipDelayLoopEvent->schedule(addr+sizeof(MachInst)); if (kernelSymtab->findAddress("determine_cpu_caches", addr)) skipCacheProbeEvent->schedule(addr+sizeof(MachInst)); } LinuxSystem::~LinuxSystem() { delete kernel; delete console; delete kernelSymtab; delete consoleSymtab; delete kernelPanicEvent; delete consolePanicEvent; delete skipIdeDelay50msEvent; delete skipDelayLoopEvent; delete skipCacheProbeEvent; } void LinuxSystem::setDelayLoop(ExecContext *xc) { Addr addr = 0; if (kernelSymtab->findAddress("loops_per_jiffy", addr)) { Addr paddr = vtophys(physmem, addr); uint8_t *loops_per_jiffy = physmem->dma_addr(paddr, sizeof(uint32_t)); Tick cpuFreq = xc->cpu->getFreq(); Tick intrFreq = platform->interrupt_frequency; *(uint32_t *)loops_per_jiffy = (uint32_t)((cpuFreq / intrFreq) * 0.9988); } } int LinuxSystem::registerExecContext(ExecContext *xc) { int xcIndex = System::registerExecContext(xc); if (xcIndex == 0) { // activate with zero delay so that we start ticking right // away on cycle 0 xc->activate(0); } RemoteGDB *rgdb = new RemoteGDB(this, xc); GDBListener *gdbl = new GDBListener(rgdb, 7000 + xcIndex); gdbl->listen(); /** * Uncommenting this line waits for a remote debugger to connect * to the simulator before continuing. */ //gdbl->accept(); if (remoteGDB.size() <= xcIndex) { remoteGDB.resize(xcIndex+1); } remoteGDB[xcIndex] = rgdb; return xcIndex; } void LinuxSystem::replaceExecContext(ExecContext *xc, int xcIndex) { System::replaceExecContext(xcIndex, xc); remoteGDB[xcIndex]->replaceExecContext(xc); } bool LinuxSystem::breakpoint() { return remoteGDB[0]->trap(ALPHA_KENTRY_IF); } BEGIN_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem) Param<bool> bin; SimObjectParam<MemoryController *> mem_ctl; SimObjectParam<PhysicalMemory *> physmem; Param<uint64_t> init_param; Param<string> kernel_code; Param<string> console_code; Param<string> pal_code; Param<string> boot_osflags; VectorParam<string> binned_fns; END_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem) BEGIN_INIT_SIM_OBJECT_PARAMS(LinuxSystem) INIT_PARAM_DFLT(bin, "is this system to be binned", false), INIT_PARAM(mem_ctl, "memory controller"), INIT_PARAM(physmem, "phsyical memory"), INIT_PARAM_DFLT(init_param, "numerical value to pass into simulator", 0), INIT_PARAM(kernel_code, "file that contains the code"), INIT_PARAM(console_code, "file that contains the console code"), INIT_PARAM(pal_code, "file that contains palcode"), INIT_PARAM_DFLT(boot_osflags, "flags to pass to the kernel during boot", "a"), INIT_PARAM(binned_fns, "functions to be broken down and binned") END_INIT_SIM_OBJECT_PARAMS(LinuxSystem) CREATE_SIM_OBJECT(LinuxSystem) { LinuxSystem *sys = new LinuxSystem(getInstanceName(), init_param, mem_ctl, physmem, kernel_code, console_code, pal_code, boot_osflags, bin, binned_fns); return sys; } REGISTER_SIM_OBJECT("LinuxSystem", LinuxSystem) <commit_msg>Update MAX ASN in kernel to 127 since that's what the ev5 supports<commit_after>/* * Copyright (c) 2004 The Regents of The University of Michigan * 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 copyright holders 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 * linux_system.cc loads the linux kernel, console, pal and patches certain functions. * The symbol tables are loaded so that traces can show the executing function and we can * skip functions. Various delay loops are skipped and their final values manually computed to * speed up boot time. */ #include "base/loader/aout_object.hh" #include "base/loader/elf_object.hh" #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "base/remote_gdb.hh" #include "base/trace.hh" #include "cpu/exec_context.hh" #include "cpu/base_cpu.hh" #include "kern/linux/linux_events.hh" #include "kern/linux/linux_system.hh" #include "kern/system_events.hh" #include "mem/functional_mem/memory_control.hh" #include "mem/functional_mem/physical_memory.hh" #include "sim/builder.hh" #include "dev/platform.hh" #include "targetarch/isa_traits.hh" #include "targetarch/vtophys.hh" #include "sim/debug.hh" extern SymbolTable *debugSymbolTable; using namespace std; LinuxSystem::LinuxSystem(const string _name, const uint64_t _init_param, MemoryController *_memCtrl, PhysicalMemory *_physmem, const string &kernel_path, const string &console_path, const string &palcode, const string &boot_osflags, const bool _bin, const vector<string> &_binned_fns) : System(_name, _init_param, _memCtrl, _physmem, _bin, _binned_fns), bin(_bin), binned_fns(_binned_fns) { kernelSymtab = new SymbolTable; consoleSymtab = new SymbolTable; /** * Load the kernel, pal, and console code into memory */ // Load kernel code ObjectFile *kernel = createObjectFile(kernel_path); if (kernel == NULL) fatal("Could not load kernel file %s", kernel_path); // Load Console Code ObjectFile *console = createObjectFile(console_path); if (console == NULL) fatal("Could not load console file %s", console_path); // Load pal file ObjectFile *pal = createObjectFile(palcode); if (pal == NULL) fatal("Could not load PALcode file %s", palcode); pal->loadSections(physmem, true); // Load console file console->loadSections(physmem, true); // Load kernel file kernel->loadSections(physmem, true); kernelStart = kernel->textBase(); kernelEnd = kernel->bssBase() + kernel->bssSize(); kernelEntry = kernel->entryPoint(); // load symbols if (!kernel->loadGlobalSymbols(kernelSymtab)) panic("could not load kernel symbols\n"); debugSymbolTable = kernelSymtab; if (!kernel->loadLocalSymbols(kernelSymtab)) panic("could not load kernel local symbols\n"); if (!console->loadGlobalSymbols(consoleSymtab)) panic("could not load console symbols\n"); DPRINTF(Loader, "Kernel start = %#x\n" "Kernel end = %#x\n" "Kernel entry = %#x\n", kernelStart, kernelEnd, kernelEntry); DPRINTF(Loader, "Kernel loaded...\n"); #ifdef DEBUG kernelPanicEvent = new BreakPCEvent(&pcEventQueue, "kernel panic"); consolePanicEvent = new BreakPCEvent(&pcEventQueue, "console panic"); #endif skipIdeDelay50msEvent = new SkipFuncEvent(&pcEventQueue, "ide_delay_50ms"); skipDelayLoopEvent = new LinuxSkipDelayLoopEvent(&pcEventQueue, "calibrate_delay"); skipCacheProbeEvent = new SkipFuncEvent(&pcEventQueue, "determine_cpu_caches"); Addr addr = 0; /** * find the address of the est_cycle_freq variable and insert it so we don't * through the lengthly process of trying to calculated it by using the PIT, * RTC, etc. */ if (kernelSymtab->findAddress("est_cycle_freq", addr)) { Addr paddr = vtophys(physmem, addr); uint8_t *est_cycle_frequency = physmem->dma_addr(paddr, sizeof(uint64_t)); if (est_cycle_frequency) *(uint64_t *)est_cycle_frequency = htoa(ticksPerSecond); } /** * Copy the osflags (kernel arguments) into the consoles memory. Presently * Linux does use the console service routine to get these command line * arguments, but we might as well make them available just in case. */ if (consoleSymtab->findAddress("env_booted_osflags", addr)) { Addr paddr = vtophys(physmem, addr); char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t)); if (osflags) strcpy(osflags, boot_osflags.c_str()); } /** * Since we aren't using a bootloader, we have to copy the kernel arguments * directly into the kernels memory. */ { Addr paddr = vtophys(physmem, PARAM_ADDR); char *commandline = (char*)physmem->dma_addr(paddr, sizeof(uint64_t)); if (commandline) strcpy(commandline, boot_osflags.c_str()); } /** * Set the hardware reset parameter block system type and revision information * to Tsunami. */ if (consoleSymtab->findAddress("xxm_rpb", addr)) { Addr paddr = vtophys(physmem, addr); char *hwprb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (hwprb) { *(uint64_t*)(hwprb+0x50) = htoa(ULL(34)); // Tsunami *(uint64_t*)(hwprb+0x58) = htoa(ULL(1)<<10); // Plain DP264 } else panic("could not translate hwprb addr to set system type/variation\n"); } else panic("could not find hwprb to set system type/variation\n"); /** * EV5 only supports 127 ASNs so we are going to tell the kernel that the * paritiuclar EV6 we have only supports 127 asns. * @todo At some point we should change ev5.hh and the palcode to support * 255 ASNs. */ if (kernelSymtab->findAddress("dp264_mv", addr)) { Addr paddr = vtophys(physmem, addr); char *dp264_mv = (char *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (dp264_mv) { *(uint32_t*)(dp264_mv+0x18) = htoa((uint32_t)127); } else panic("could not translate dp264_mv addr to set the MAX_ASN to 127\n"); } else panic("could not find dp264_mv to set the MAX_ASN to 127\n"); #ifdef DEBUG if (kernelSymtab->findAddress("panic", addr)) kernelPanicEvent->schedule(addr); else panic("could not find kernel symbol \'panic\'"); if (consoleSymtab->findAddress("panic", addr)) consolePanicEvent->schedule(addr); #endif /** * Any time ide_delay_50ms, calibarte_delay or determine_cpu_caches is called * just skip the function. Currently determine_cpu_caches only is used put * information in proc, however if that changes in the future we will have to * fill in the cache size variables appropriately. */ if (kernelSymtab->findAddress("ide_delay_50ms", addr)) skipIdeDelay50msEvent->schedule(addr+sizeof(MachInst)); if (kernelSymtab->findAddress("calibrate_delay", addr)) skipDelayLoopEvent->schedule(addr+sizeof(MachInst)); if (kernelSymtab->findAddress("determine_cpu_caches", addr)) skipCacheProbeEvent->schedule(addr+sizeof(MachInst)); } LinuxSystem::~LinuxSystem() { delete kernel; delete console; delete kernelSymtab; delete consoleSymtab; delete kernelPanicEvent; delete consolePanicEvent; delete skipIdeDelay50msEvent; delete skipDelayLoopEvent; delete skipCacheProbeEvent; } void LinuxSystem::setDelayLoop(ExecContext *xc) { Addr addr = 0; if (kernelSymtab->findAddress("loops_per_jiffy", addr)) { Addr paddr = vtophys(physmem, addr); uint8_t *loops_per_jiffy = physmem->dma_addr(paddr, sizeof(uint32_t)); Tick cpuFreq = xc->cpu->getFreq(); Tick intrFreq = platform->interrupt_frequency; *(uint32_t *)loops_per_jiffy = (uint32_t)((cpuFreq / intrFreq) * 0.9988); } } int LinuxSystem::registerExecContext(ExecContext *xc) { int xcIndex = System::registerExecContext(xc); if (xcIndex == 0) { // activate with zero delay so that we start ticking right // away on cycle 0 xc->activate(0); } RemoteGDB *rgdb = new RemoteGDB(this, xc); GDBListener *gdbl = new GDBListener(rgdb, 7000 + xcIndex); gdbl->listen(); /** * Uncommenting this line waits for a remote debugger to connect * to the simulator before continuing. */ //gdbl->accept(); if (remoteGDB.size() <= xcIndex) { remoteGDB.resize(xcIndex+1); } remoteGDB[xcIndex] = rgdb; return xcIndex; } void LinuxSystem::replaceExecContext(ExecContext *xc, int xcIndex) { System::replaceExecContext(xcIndex, xc); remoteGDB[xcIndex]->replaceExecContext(xc); } bool LinuxSystem::breakpoint() { return remoteGDB[0]->trap(ALPHA_KENTRY_IF); } BEGIN_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem) Param<bool> bin; SimObjectParam<MemoryController *> mem_ctl; SimObjectParam<PhysicalMemory *> physmem; Param<uint64_t> init_param; Param<string> kernel_code; Param<string> console_code; Param<string> pal_code; Param<string> boot_osflags; VectorParam<string> binned_fns; END_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem) BEGIN_INIT_SIM_OBJECT_PARAMS(LinuxSystem) INIT_PARAM_DFLT(bin, "is this system to be binned", false), INIT_PARAM(mem_ctl, "memory controller"), INIT_PARAM(physmem, "phsyical memory"), INIT_PARAM_DFLT(init_param, "numerical value to pass into simulator", 0), INIT_PARAM(kernel_code, "file that contains the code"), INIT_PARAM(console_code, "file that contains the console code"), INIT_PARAM(pal_code, "file that contains palcode"), INIT_PARAM_DFLT(boot_osflags, "flags to pass to the kernel during boot", "a"), INIT_PARAM(binned_fns, "functions to be broken down and binned") END_INIT_SIM_OBJECT_PARAMS(LinuxSystem) CREATE_SIM_OBJECT(LinuxSystem) { LinuxSystem *sys = new LinuxSystem(getInstanceName(), init_param, mem_ctl, physmem, kernel_code, console_code, pal_code, boot_osflags, bin, binned_fns); return sys; } REGISTER_SIM_OBJECT("LinuxSystem", LinuxSystem) <|endoftext|>
<commit_before>/* * Copyright (c) 2008, AMT – The Association For Manufacturing Technology (“AMT”) * 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 AMT nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * DISCLAIMER OF WARRANTY. ALL MTCONNECT MATERIALS AND SPECIFICATIONS PROVIDED * BY AMT, MTCONNECT OR ANY PARTICIPANT TO YOU OR ANY PARTY ARE PROVIDED "AS IS" * AND WITHOUT ANY WARRANTY OF ANY KIND. AMT, MTCONNECT, AND EACH OF THEIR * RESPECTIVE MEMBERS, OFFICERS, DIRECTORS, AFFILIATES, SPONSORS, AND AGENTS * (COLLECTIVELY, THE "AMT PARTIES") AND PARTICIPANTS MAKE NO REPRESENTATION OR * WARRANTY OF ANY KIND WHATSOEVER RELATING TO THESE MATERIALS, INCLUDING, WITHOUT * LIMITATION, ANY EXPRESS OR IMPLIED WARRANTY OF NONINFRINGEMENT, * MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * LIMITATION OF LIABILITY. IN NO EVENT SHALL AMT, MTCONNECT, ANY OTHER AMT * PARTY, OR ANY PARTICIPANT BE LIABLE FOR THE COST OF PROCURING SUBSTITUTE GOODS * OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA OR ANY INCIDENTAL, * CONSEQUENTIAL, INDIRECT, SPECIAL OR PUNITIVE DAMAGES OR OTHER DIRECT DAMAGES, * WHETHER UNDER CONTRACT, TORT, WARRANTY OR OTHERWISE, ARISING IN ANY WAY OUT OF * THIS AGREEMENT, USE OR INABILITY TO USE MTCONNECT MATERIALS, WHETHER OR NOT * SUCH PARTY HAD ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. */ #include "adapter.hpp" #include "device.hpp" #include "dlib/logger.h" using namespace std; static dlib::logger sLogger("input.adapter"); /* Adapter public methods */ Adapter::Adapter( const string& device, const string& server, const unsigned int port ) : Connector(server, port), mDeviceName(device), mRunning(true) { } Adapter::~Adapter() { // Will stop threaded object gracefully Adapter::thread() mRunning = false; stop(); wait(); } void Adapter::setAgent(Agent &aAgent) { mAgent = &aAgent; mDevice = mAgent->getDeviceByName(mDeviceName); } inline static bool splitKey(string &key, string &dev) { size_t found = key.find_first_of(':'); if (found == string::npos) { return false; } else { dev = key; dev.erase(found); key.erase(0, found + 1); return true; } } /** * Expected data to parse in SDHR format: * Time|Alarm|Code|NativeCode|Severity|State|Description * Time|Item|Value * Time|Item1|Value1|Item2|Value2... */ void Adapter::processData(const string& data) { istringstream toParse(data); string key, value, dev; Device *device; getline(toParse, key, '|'); string time = key; getline(toParse, key, '|'); getline(toParse, value, '|'); DataItem *dataItem; if (splitKey(key, dev)) { device = mAgent->getDeviceByName(dev); } else { device = mDevice; } if (device != NULL) { dataItem = device->getDeviceDataItem(key); if (dataItem == NULL) { sLogger << LWARN << "Could not find data item: " << key; } else { string rest; if (dataItem->isCondition() || dataItem->isAlarm() || dataItem->isMessage()) { getline(toParse, rest); value = value + "|" + rest; } // Add key->value pairings dataItem->setDataSource(this); mAgent->addToBuffer(dataItem, value, time); } } else { sLogger << LDEBUG << "Could not find device: " << dev; } // Look for more key->value pairings in the rest of the data while (getline(toParse, key, '|') && getline(toParse, value, '|')) { if (splitKey(key, dev)) { device = mAgent->getDeviceByName(dev); } else { device = mDevice; } if (device == NULL) { sLogger << LDEBUG << "Could not find device: " << dev; continue; } dataItem = device->getDeviceDataItem(key); if (dataItem == NULL) { sLogger << LWARN << "Could not find data item: " << key; } else { dataItem->setDataSource(this); mAgent->addToBuffer(dataItem, toUpperCase(value), time); } } } inline static void trim(std::string str) { size_t index = str.find_first_not_of(" \t"); if (index != string::npos) str.erase(0, index); index = str.find_last_not_of(" \t"); if (index != string::npos) str.erase(index); } void Adapter::protocolCommand(const std::string& data) { // Handle initial push of settings for uuid, serial number and manufacturer. // This will override the settings in the device from the xml size_t index = data.find(':', 2); if (index != string::npos) { // Slice from the second character to the :, without the colon string key = data.substr(2, index - 2); trim(key); string value = data.substr(index + 1); trim(value); if (key == "uuid") mDevice->setUuid(value); else if (key == "manufacturer") mDevice->setManufacturer(value); else if (key == "station") mDevice->setStation(value); else if (key == "serialNumber") mDevice->setSerialNumber(value); else sLogger << LWARN << "Unknown command '" << data << "' for device '" << mDeviceName; } } void Adapter::disconnected() { mAgent->disconnected(this, mDevice); } /* Adapter private methods */ void Adapter::thread() { // Start the connection to the socket while (mRunning) { connect(); // Try to reconnect every 10 seconds sLogger << LINFO << "Will try to reconnect in 10 seconds"; dlib::sleep(10 * 1000); } } <commit_msg>Removed whitespace from end of values<commit_after>/* * Copyright (c) 2008, AMT – The Association For Manufacturing Technology (“AMT”) * 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 AMT nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * DISCLAIMER OF WARRANTY. ALL MTCONNECT MATERIALS AND SPECIFICATIONS PROVIDED * BY AMT, MTCONNECT OR ANY PARTICIPANT TO YOU OR ANY PARTY ARE PROVIDED "AS IS" * AND WITHOUT ANY WARRANTY OF ANY KIND. AMT, MTCONNECT, AND EACH OF THEIR * RESPECTIVE MEMBERS, OFFICERS, DIRECTORS, AFFILIATES, SPONSORS, AND AGENTS * (COLLECTIVELY, THE "AMT PARTIES") AND PARTICIPANTS MAKE NO REPRESENTATION OR * WARRANTY OF ANY KIND WHATSOEVER RELATING TO THESE MATERIALS, INCLUDING, WITHOUT * LIMITATION, ANY EXPRESS OR IMPLIED WARRANTY OF NONINFRINGEMENT, * MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * LIMITATION OF LIABILITY. IN NO EVENT SHALL AMT, MTCONNECT, ANY OTHER AMT * PARTY, OR ANY PARTICIPANT BE LIABLE FOR THE COST OF PROCURING SUBSTITUTE GOODS * OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA OR ANY INCIDENTAL, * CONSEQUENTIAL, INDIRECT, SPECIAL OR PUNITIVE DAMAGES OR OTHER DIRECT DAMAGES, * WHETHER UNDER CONTRACT, TORT, WARRANTY OR OTHERWISE, ARISING IN ANY WAY OUT OF * THIS AGREEMENT, USE OR INABILITY TO USE MTCONNECT MATERIALS, WHETHER OR NOT * SUCH PARTY HAD ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. */ #include "adapter.hpp" #include "device.hpp" #include "dlib/logger.h" using namespace std; static dlib::logger sLogger("input.adapter"); /* Adapter public methods */ Adapter::Adapter( const string& device, const string& server, const unsigned int port ) : Connector(server, port), mDeviceName(device), mRunning(true) { } Adapter::~Adapter() { // Will stop threaded object gracefully Adapter::thread() mRunning = false; stop(); wait(); } void Adapter::setAgent(Agent &aAgent) { mAgent = &aAgent; mDevice = mAgent->getDeviceByName(mDeviceName); } inline static bool splitKey(string &key, string &dev) { size_t found = key.find_first_of(':'); if (found == string::npos) { return false; } else { dev = key; dev.erase(found); key.erase(0, found + 1); return true; } } /** * Expected data to parse in SDHR format: * Time|Alarm|Code|NativeCode|Severity|State|Description * Time|Item|Value * Time|Item1|Value1|Item2|Value2... */ void Adapter::processData(const string& data) { istringstream toParse(data); string key, value, dev; Device *device; getline(toParse, key, '|'); string time = key; getline(toParse, key, '|'); getline(toParse, value, '|'); DataItem *dataItem; if (splitKey(key, dev)) { device = mAgent->getDeviceByName(dev); } else { device = mDevice; } if (device != NULL) { dataItem = device->getDeviceDataItem(key); if (dataItem == NULL) { sLogger << LWARN << "Could not find data item: " << key; } else { string rest; if (dataItem->isCondition() || dataItem->isAlarm() || dataItem->isMessage()) { getline(toParse, rest); value = value + "|" + rest; } // Add key->value pairings dataItem->setDataSource(this); mAgent->addToBuffer(dataItem, toUpperCase(trim(value)), time); } } else { sLogger << LDEBUG << "Could not find device: " << dev; } // Look for more key->value pairings in the rest of the data while (getline(toParse, key, '|') && getline(toParse, value, '|')) { if (splitKey(key, dev)) { device = mAgent->getDeviceByName(dev); } else { device = mDevice; } if (device == NULL) { sLogger << LDEBUG << "Could not find device: " << dev; continue; } dataItem = device->getDeviceDataItem(key); if (dataItem == NULL) { sLogger << LWARN << "Could not find data item: " << key; } else { dataItem->setDataSource(this); mAgent->addToBuffer(dataItem, toUpperCase(trim(value)), time); } } } inline static void trim(std::string str) { size_t index = str.find_first_not_of(" \r\t"); if (index != string::npos) str.erase(0, index); index = str.find_last_not_of(" \r\t"); if (index != string::npos) str.erase(index); } void Adapter::protocolCommand(const std::string& data) { // Handle initial push of settings for uuid, serial number and manufacturer. // This will override the settings in the device from the xml size_t index = data.find(':', 2); if (index != string::npos) { // Slice from the second character to the :, without the colon string key = data.substr(2, index - 2); trim(key); string value = data.substr(index + 1); trim(value); if (key == "uuid") mDevice->setUuid(value); else if (key == "manufacturer") mDevice->setManufacturer(value); else if (key == "station") mDevice->setStation(value); else if (key == "serialNumber") mDevice->setSerialNumber(value); else sLogger << LWARN << "Unknown command '" << data << "' for device '" << mDeviceName; } } void Adapter::disconnected() { mAgent->disconnected(this, mDevice); } /* Adapter private methods */ void Adapter::thread() { // Start the connection to the socket while (mRunning) { connect(); // Try to reconnect every 10 seconds sLogger << LINFO << "Will try to reconnect in 10 seconds"; dlib::sleep(10 * 1000); } } <|endoftext|>
<commit_before>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file EC_Billboard.cpp * @brief EC_Billboard shows a billboard (3D sprite) that is attached to an entity. * @note The entity must have EC_Placeable component available in advance. */ #include "StableHeaders.h" #include "EC_Billboard.h" #include "IModule.h" #include "Renderer.h" #include "EC_Placeable.h" #include "Entity.h" #include "OgreMaterialUtils.h" #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("EC_Billboard"); #include <OgreBillboardSet.h> #include <OgreTextureManager.h> #include <OgreResource.h> #include <QTimer> EC_Billboard::EC_Billboard(IModule *module) : IComponent(module->GetFramework()), billboardSet_(0), billboard_(0), materialName_("") { } EC_Billboard::~EC_Billboard() { } void EC_Billboard::SetPosition(const Vector3df& position) { if (IsCreated()) billboard_->setPosition(Ogre::Vector3(position.x, position.y, position.z)); } void EC_Billboard::SetDimensions(float w, float h) { if (IsCreated()) billboardSet_->setDefaultDimensions(w, h); } void EC_Billboard::Show(const std::string &imageName, int timeToShow) { assert(GetFramework()); if (GetFramework()) return; boost::shared_ptr<OgreRenderer::Renderer> renderer = GetFramework()->GetServiceManager()->GetService <OgreRenderer::Renderer>(Service::ST_Renderer).lock(); if (!renderer) return; Ogre::SceneManager *scene = renderer->GetSceneManager(); assert(scene); if (!scene) return; Scene::Entity *entity = GetParentEntity(); assert(entity); if (!entity) return; EC_Placeable *placeable = entity->GetComponent<EC_Placeable>().get(); if (!placeable) return; Ogre::SceneNode *node = placeable->GetSceneNode(); assert(node); if (!node) return; if (imageName.empty()) return; bool succesful = CreateOgreTextureResource(imageName); if (!succesful) return; if (!IsCreated()) { // Billboard not created yet, create it now. billboardSet_ = scene->createBillboardSet(renderer->GetUniqueObjectName("EC_Billboard"), 1); assert(billboardSet_); materialName_ = renderer->GetUniqueObjectName("EC_Billboard_material"); Ogre::MaterialPtr material = OgreRenderer::CloneMaterial("UnlitTexturedSoftAlpha", materialName_); OgreRenderer::SetTextureUnitOnMaterial(material, imageName); billboardSet_->setMaterialName(materialName_); billboard_ = billboardSet_->createBillboard(Ogre::Vector3(0, 0, 1.5f)); assert(billboard_); billboardSet_->setDefaultDimensions(0.5f, 0.5f); node->attachObject(billboardSet_); } else { // Billboard already created Set new texture for the material assert(!materialName_.empty()); if (!materialName_.empty()) { Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton(); Ogre::MaterialPtr material = mgr.getByName(materialName_); assert(material.get()); OgreRenderer::SetTextureUnitOnMaterial(material, imageName); } } Show(timeToShow); } void EC_Billboard::Show(int timeToShow) { if (IsCreated()) { billboardSet_->setVisible(true); clamp(timeToShow, -1, 86401); if (timeToShow > 0) QTimer::singleShot(1000*timeToShow, this, SLOT(Hide())); } } void EC_Billboard::Hide() { if (IsCreated()) billboardSet_->setVisible(false); } bool EC_Billboard::CreateOgreTextureResource(const std::string &imageName) { Ogre::TextureManager &manager = Ogre::TextureManager::getSingleton(); Ogre::Texture *tex = dynamic_cast<Ogre::Texture *>(manager.getByName(imageName).get()); if (!tex) { ///\bug OGRE doesn't seem to add all texture to the resource group although the texture /// exists in folder spesified in the resource.cfg LogWarning("Ogre Texture \"" +imageName + "\" not found from the default resource group"); Ogre::ResourcePtr rp = manager.create(imageName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (!rp.isNull()) { LogInfo("But should be now..."); return true; } return false; } return true; } <commit_msg>EC_Billboard: fixed bug if clause that returned always in Show(). Note: this ec is not declared by any module, shoud add?<commit_after>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file EC_Billboard.cpp * @brief EC_Billboard shows a billboard (3D sprite) that is attached to an entity. * @note The entity must have EC_Placeable component available in advance. */ #include "StableHeaders.h" #include "EC_Billboard.h" #include "IModule.h" #include "Renderer.h" #include "EC_Placeable.h" #include "Entity.h" #include "OgreMaterialUtils.h" #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("EC_Billboard"); #include <OgreBillboardSet.h> #include <OgreTextureManager.h> #include <OgreResource.h> #include <QTimer> EC_Billboard::EC_Billboard(IModule *module) : IComponent(module->GetFramework()), billboardSet_(0), billboard_(0), materialName_("") { } EC_Billboard::~EC_Billboard() { } void EC_Billboard::SetPosition(const Vector3df& position) { if (IsCreated()) billboard_->setPosition(Ogre::Vector3(position.x, position.y, position.z)); } void EC_Billboard::SetDimensions(float w, float h) { if (IsCreated()) billboardSet_->setDefaultDimensions(w, h); } void EC_Billboard::Show(const std::string &imageName, int timeToShow) { if (!GetFramework()) return; boost::shared_ptr<OgreRenderer::Renderer> renderer = GetFramework()->GetServiceManager()->GetService <OgreRenderer::Renderer>(Service::ST_Renderer).lock(); if (!renderer) return; Ogre::SceneManager *scene = renderer->GetSceneManager(); assert(scene); if (!scene) return; Scene::Entity *entity = GetParentEntity(); assert(entity); if (!entity) return; EC_Placeable *placeable = entity->GetComponent<EC_Placeable>().get(); if (!placeable) return; Ogre::SceneNode *node = placeable->GetSceneNode(); assert(node); if (!node) return; if (imageName.empty()) return; bool succesful = CreateOgreTextureResource(imageName); if (!succesful) return; if (!IsCreated()) { // Billboard not created yet, create it now. billboardSet_ = scene->createBillboardSet(renderer->GetUniqueObjectName("EC_Billboard"), 1); assert(billboardSet_); materialName_ = renderer->GetUniqueObjectName("EC_Billboard_material"); Ogre::MaterialPtr material = OgreRenderer::CloneMaterial("UnlitTexturedSoftAlpha", materialName_); OgreRenderer::SetTextureUnitOnMaterial(material, imageName); billboardSet_->setMaterialName(materialName_); billboard_ = billboardSet_->createBillboard(Ogre::Vector3(0, 0, 1.5f)); assert(billboard_); billboardSet_->setDefaultDimensions(0.5f, 0.5f); node->attachObject(billboardSet_); } else { // Billboard already created Set new texture for the material assert(!materialName_.empty()); if (!materialName_.empty()) { Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton(); Ogre::MaterialPtr material = mgr.getByName(materialName_); assert(material.get()); OgreRenderer::SetTextureUnitOnMaterial(material, imageName); } } Show(timeToShow); } void EC_Billboard::Show(int timeToShow) { if (IsCreated()) { billboardSet_->setVisible(true); clamp(timeToShow, -1, 86401); if (timeToShow > 0) QTimer::singleShot(1000*timeToShow, this, SLOT(Hide())); } } void EC_Billboard::Hide() { if (IsCreated()) billboardSet_->setVisible(false); } bool EC_Billboard::CreateOgreTextureResource(const std::string &imageName) { Ogre::TextureManager &manager = Ogre::TextureManager::getSingleton(); Ogre::Texture *tex = dynamic_cast<Ogre::Texture *>(manager.getByName(imageName).get()); if (!tex) { ///\bug OGRE doesn't seem to add all texture to the resource group although the texture /// exists in folder spesified in the resource.cfg LogWarning("Ogre Texture \"" +imageName + "\" not found from the default resource group"); Ogre::ResourcePtr rp = manager.create(imageName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (!rp.isNull()) { LogInfo("But should be now..."); return true; } return false; } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <boost/asio.hpp> #include <boost/asio/yield.hpp> #include "msg_helper.hh" #include "examples.hh" namespace echo_server_asio_stackless { using boost::asio::ip::tcp; class TcpServer final : private coro::UnCopyable, public boost::asio::coroutine { tcp::acceptor acceptor_; tcp::socket socket_; coro::net::Status status_{coro::net::Status::INIT_ACK}; coro::msg::ReadBuf rbuf_; coro::msg::WriteBuf wbuf_; struct _ref { TcpServer* s_{}; _ref(TcpServer* s) noexcept : s_{s} {} void operator()(std::error_code ec, coro::sz_t n = 0) { (*s_)(ec, n); } }; public: TcpServer(boost::asio::io_context& io_context, coro::u16_t port) noexcept : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) , socket_(io_context) , rbuf_(1024) { } void operator()(std::error_code ec, coro::sz_t n = 0) { reenter(this) for (;;) { yield acceptor_.async_accept(socket_, _ref(this)); if (!ec) { yield boost::asio::async_write( socket_, boost::asio::buffer("*", 1), _ref(this)); status_ = coro::net::Status::WAIT_MSG; wbuf_.clear(); while (!ec) { yield socket_.async_read_some(boost::asio::buffer(rbuf_), _ref(this)); if (!ec) { for (int i = 0; i < n; ++i) { switch (status_) { case coro::net::Status::INIT_ACK: break; case coro::net::Status::WAIT_MSG: if (rbuf_[i] == '^') status_ = coro::net::Status::READ_MSG; break; case coro::net::Status::READ_MSG: if (rbuf_[i] == '$') status_ = coro::net::Status::WAIT_MSG; else wbuf_.push_back(rbuf_[i] + 1); break; } } yield boost::asio::async_write( socket_, boost::asio::buffer(wbuf_), _ref(this)); wbuf_.clear(); } } } socket_.close(); } } }; void launch() { boost::asio::io_context io_context; auto server = std::make_shared<TcpServer>(io_context, 5555); (*server)(std::error_code()); io_context.run(); } } CORO_EXAMPLE(EchoServerAsioStackless, esasiol, "an easy echo server use boost.asio with stackless coroutine") { echo_server_asio_stackless::launch(); } <commit_msg>:bug: fix(warning): fixed compiling warning in linux<commit_after>// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <boost/asio.hpp> #include <boost/asio/yield.hpp> #include "msg_helper.hh" #include "examples.hh" namespace echo_server_asio_stackless { using boost::asio::ip::tcp; class TcpServer final : private coro::UnCopyable, public boost::asio::coroutine { tcp::acceptor acceptor_; tcp::socket socket_; coro::net::Status status_{coro::net::Status::INIT_ACK}; coro::msg::ReadBuf rbuf_; coro::msg::WriteBuf wbuf_; struct _ref { TcpServer* s_{}; _ref(TcpServer* s) noexcept : s_{s} {} void operator()(std::error_code ec, coro::sz_t n = 0) { (*s_)(ec, n); } }; public: TcpServer(boost::asio::io_context& io_context, coro::u16_t port) noexcept : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) , socket_(io_context) , rbuf_(1024) { } void operator()(std::error_code ec, coro::sz_t n = 0) { reenter(this) for (;;) { yield acceptor_.async_accept(socket_, _ref(this)); if (!ec) { yield boost::asio::async_write( socket_, boost::asio::buffer("*", 1), _ref(this)); status_ = coro::net::Status::WAIT_MSG; wbuf_.clear(); while (!ec) { yield socket_.async_read_some(boost::asio::buffer(rbuf_), _ref(this)); if (!ec) { for (coro::sz_t i = 0; i < n; ++i) { switch (status_) { case coro::net::Status::INIT_ACK: break; case coro::net::Status::WAIT_MSG: if (rbuf_[i] == '^') status_ = coro::net::Status::READ_MSG; break; case coro::net::Status::READ_MSG: if (rbuf_[i] == '$') status_ = coro::net::Status::WAIT_MSG; else wbuf_.push_back(rbuf_[i] + 1); break; } } yield boost::asio::async_write( socket_, boost::asio::buffer(wbuf_), _ref(this)); wbuf_.clear(); } } } socket_.close(); } } }; void launch() { boost::asio::io_context io_context; auto server = std::make_shared<TcpServer>(io_context, 5555); (*server)(std::error_code()); io_context.run(); } } CORO_EXAMPLE(EchoServerAsioStackless, esasiol, "an easy echo server use boost.asio with stackless coroutine") { echo_server_asio_stackless::launch(); } <|endoftext|>
<commit_before>// neighbor_testing_utils.hpp // // Dig // // Created by DB on 9/15/16 // Copyright © 2016 D Blalock. All rights reserved. #ifndef __NEIGHBOR_TESTING_UTILS_HPP #define __NEIGHBOR_TESTING_UTILS_HPP #include "euclidean.hpp" #include "nn_utils.hpp" using dist_t = Neighbor::dist_t; //void require_neighbors_same(const Neighbor& nn, const Neighbor& trueNN) { // REQUIRE(nn.idx == trueNN.idx); // REQUIRE(std::abs(nn.dist - trueNN.dist) < .0001); //} // macro so that, if it fails, failing line is within the test #define REQUIRE_NEIGHBORS_SAME(nn, trueNN) \ REQUIRE(nn.idx == trueNN.idx); \ REQUIRE(std::abs(nn.dist - trueNN.dist) < .0001); template<class Container> vector<typename Neighbor::idx_t> idxs_from_neighbors(const Container& neighbors) { return ar::map([](const Neighbor& n) { return n.idx; }, neighbors); } template<class Container> vector<typename Neighbor::dist_t> dists_from_neighbors(const Container& neighbors) { return ar::map([](const Neighbor& n) { return n.dist; }, neighbors); } template<class Container1, class Container2> void require_neighbor_lists_same(const Container1& nn, const Container2& trueNN) { CAPTURE(ar::to_string(idxs_from_neighbors(nn))); CAPTURE(ar::to_string(idxs_from_neighbors(trueNN))); CAPTURE(ar::to_string(dists_from_neighbors(nn))); CAPTURE(ar::to_string(dists_from_neighbors(trueNN))); REQUIRE(nn.size() == trueNN.size()); for (int i = 0; i < nn.size(); i++) { REQUIRE_NEIGHBORS_SAME(nn[i], trueNN[i]); } } template<class Container1, class Container2> void require_neighbor_idx_lists_same(const Container1& nn_idxs, const Container2& trueNN_idxs) { REQUIRE(nn_idxs.size() == trueNN_idxs.size()); REQUIRE(ar::all_eq(nn_idxs, trueNN_idxs)); } template<class MatrixT, class VectorT, class DistT = typename MatrixT::Scalar> inline vector<Neighbor> radius_simple(const MatrixT& X, const VectorT& q, DistT radius_sq) { vector<Neighbor> trueKnn; for (int32_t i = 0; i < X.rows(); i++) { DistT d = (X.row(i) - q).squaredNorm(); if (d < radius_sq) { trueKnn.emplace_back(i, d); } } return trueKnn; } template<class MatrixT, class VectorT> inline Neighbor onenn_simple(const MatrixT& X, const VectorT& q) { Neighbor trueNN; double d_bsf = INFINITY; for (int32_t i = 0; i < X.rows(); i++) { double d = (X.row(i) - q).squaredNorm(); // double dist2 = dist_sq(X.row(i).data(), q.data(), q.size()); // double dist2 = dist::dist_sq(X.row(i), q); // REQUIRE(approxEq(dist1, dist2)); if (d < d_bsf) { d_bsf = d; trueNN = Neighbor{i, d}; } } return trueNN; } template<class MatrixT, class VectorT> inline vector<Neighbor> knn_simple(const MatrixT& X, const VectorT& q, int k) { assert(k <= X.rows()); vector<Neighbor> trueKnn; for (int32_t i = 0; i < k; i++) { auto dist = (X.row(i) - q).squaredNorm(); trueKnn.emplace_back(i, dist); } nn::sort_neighbors_ascending_distance(trueKnn); typename MatrixT::Scalar d_bsf = INFINITY; for (int32_t i = k; i < X.rows(); i++) { auto dist = dist::simple::dist_sq(X.row(i), q); nn::maybe_insert_neighbor(trueKnn, dist, i); } return trueKnn; } // struct undef; template<class MatrixT, class IndexT, class QueryT> inline void _test_index_with_query(MatrixT& X, IndexT& index, QueryT& q) { for (int i = 0; i < 100; i++) { // for (int i = 0; i < 10; i++) { // for (int i = 0; i < 1; i++) { q.setRandom(); // ------------------------ onenn auto nn = index.onenn(q); auto trueNN = onenn_simple(X, q); CAPTURE(nn.dist); CAPTURE(trueNN.dist); REQUIRE_NEIGHBORS_SAME(nn, trueNN); auto nn_idx = index.onenn_idxs(q); auto trueNN_idx = trueNN.idx; CAPTURE(nn_idx); CAPTURE(trueNN_idx); REQUIRE(nn_idx == trueNN_idx); // ------------------------ radius auto reasonable_dist = (X.row(0) - q).squaredNorm() + .00001; auto allnn = index.radius(q, reasonable_dist); auto all_trueNN = radius_simple(X, q, reasonable_dist); require_neighbor_lists_same(allnn, all_trueNN); auto allnn_idxs = index.radius_idxs(q, reasonable_dist); auto trueNN_idxs = idxs_from_neighbors(all_trueNN); CAPTURE(ar::to_string(allnn_idxs)); CAPTURE(ar::to_string(trueNN_idxs)); require_neighbor_idx_lists_same(allnn_idxs, trueNN_idxs); // ------------------------ knn for (int k = 1; k <= 5; k += 2) { auto knn = index.knn(q, k); auto trueKnn = knn_simple(X, q, k); require_neighbor_lists_same(knn, trueKnn); auto knn_idxs = index.knn_idxs(q, k); auto trueKnn_idxs = idxs_from_neighbors(trueKnn); CAPTURE(k); CAPTURE(knn[0].dist); CAPTURE(knn[0].idx); CAPTURE(trueKnn[0].dist); CAPTURE(trueKnn[0].idx); CAPTURE(ar::to_string(knn_idxs)); CAPTURE(ar::to_string(trueKnn_idxs)); REQUIRE(ar::all_eq(knn_idxs, trueKnn_idxs)); } } } template<class IndexT> void _test_index(int64_t N=100, int64_t D=16) { using Scalar = typename IndexT::Scalar; RowMatrix<Scalar> X(N, D); X.setRandom(); IndexT index(X); RowVector<Scalar> q(D); _test_index_with_query(X, index, q); } template<class IndexT> void _test_cluster_index(int64_t N=100, int64_t D=16, int num_clusters=2) { using Scalar = typename IndexT::Scalar; RowMatrix<Scalar> X(N, D); X.setRandom(); IndexT index(X, num_clusters); RowVector<Scalar> q(D); _test_index_with_query(X, index, q); } #endif // __NEIGHBOR_TESTING_UTILS_HPP <commit_msg>FIX vulneratiblity to slight numerical differences in unit tests<commit_after>// neighbor_testing_utils.hpp // // Dig // // Created by DB on 9/15/16 // Copyright © 2016 D Blalock. All rights reserved. #ifndef __NEIGHBOR_TESTING_UTILS_HPP #define __NEIGHBOR_TESTING_UTILS_HPP #include "euclidean.hpp" #include "nn_utils.hpp" #include "debug_utils.hpp" using dist_t = Neighbor::dist_t; // macro so that, if it fails, failing line is within the test #define REQUIRE_NEIGHBORS_SAME(nn, trueNN) \ REQUIRE(nn.idx == trueNN.idx); \ REQUIRE(std::abs(nn.dist - trueNN.dist) < .0001); template<class Container> vector<typename Neighbor::idx_t> idxs_from_neighbors(const Container& neighbors) { return ar::map([](const Neighbor& n) { return n.idx; }, neighbors); } template<class Container> vector<typename Neighbor::dist_t> dists_from_neighbors(const Container& neighbors) { return ar::map([](const Neighbor& n) { return n.dist; }, neighbors); } template<class Container1, class Container2> void require_neighbor_lists_same(const Container1& nn, const Container2& trueNN) { auto dists = dists_from_neighbors(nn); auto true_dists = dists_from_neighbors(trueNN); auto sorted_dists = ar::sort(dists); auto true_sorted_dists = ar::sort(true_dists); CAPTURE(ar::to_string(ar::sort(idxs_from_neighbors( nn ) ) )); CAPTURE(ar::to_string(ar::sort(idxs_from_neighbors(trueNN)))); CAPTURE(ar :: to_string ( sorted_dists )); // spacing to align output CAPTURE(ar::to_string(true_sorted_dists)); // print out last elements to check if failures stem from numerical errors; // we manually check whether there will be a problem because Catch refuses // to catpure these variables for no clear reason if (nn.size() != trueNN.size()) { if (auto sz = sorted_dists.size()) { PRINT_VAR(sorted_dists[sz-1]); } if (auto sz = true_sorted_dists.size()) { PRINT_VAR(true_sorted_dists[sz-1]); } } REQUIRE(nn.size() == trueNN.size()); for (int i = 0; i < nn.size(); i++) { REQUIRE_NEIGHBORS_SAME(nn[i], trueNN[i]); } } template<class Container1, class Container2> void require_neighbor_idx_lists_same(const Container1& nn_idxs, const Container2& trueNN_idxs) { REQUIRE(nn_idxs.size() == trueNN_idxs.size()); REQUIRE(ar::all_eq(nn_idxs, trueNN_idxs)); } template<class MatrixT, class VectorT, class DistT = typename MatrixT::Scalar> inline vector<Neighbor> radius_simple(const MatrixT& X, const VectorT& q, DistT radius_sq) { vector<Neighbor> trueKnn; for (int32_t i = 0; i < X.rows(); i++) { DistT d = (X.row(i) - q).squaredNorm(); if (d < radius_sq) { trueKnn.emplace_back(i, d); } } return trueKnn; } template<class MatrixT, class VectorT> inline Neighbor onenn_simple(const MatrixT& X, const VectorT& q) { Neighbor trueNN; double d_bsf = INFINITY; for (int32_t i = 0; i < X.rows(); i++) { double d = (X.row(i) - q).squaredNorm(); // double dist2 = dist_sq(X.row(i).data(), q.data(), q.size()); // double dist2 = dist::dist_sq(X.row(i), q); // REQUIRE(approxEq(dist1, dist2)); if (d < d_bsf) { d_bsf = d; trueNN = Neighbor{i, d}; } } return trueNN; } template<class MatrixT, class VectorT> inline vector<Neighbor> knn_simple(const MatrixT& X, const VectorT& q, int k) { assert(k <= X.rows()); vector<Neighbor> trueKnn; for (int32_t i = 0; i < k; i++) { auto dist = (X.row(i) - q).squaredNorm(); trueKnn.emplace_back(i, dist); } nn::sort_neighbors_ascending_distance(trueKnn); typename MatrixT::Scalar d_bsf = INFINITY; for (int32_t i = k; i < X.rows(); i++) { auto dist = dist::simple::dist_sq(X.row(i), q); nn::maybe_insert_neighbor(trueKnn, dist, i); } return trueKnn; } template<class MatrixT, class IndexT, class QueryT> inline void _test_index_with_query(MatrixT& X, IndexT& index, QueryT& q) { for (int i = 0; i < 100; i++) { // for (int i = 0; i < 10; i++) { // for (int i = 0; i < 1; i++) { q.setRandom(); // ------------------------ onenn auto nn = index.onenn(q); auto trueNN = onenn_simple(X, q); CAPTURE(nn.dist); CAPTURE(trueNN.dist); REQUIRE_NEIGHBORS_SAME(nn, trueNN); auto nn_idx = index.onenn_idxs(q); auto trueNN_idx = trueNN.idx; CAPTURE(nn_idx); CAPTURE(trueNN_idx); REQUIRE(nn_idx == trueNN_idx); // ------------------------ radius // use the dist to the first point as a radius that should include // about half of the points; we round to a few decimal places to avoid // numerical errors in distance computations causing test failures auto reasonable_dist = (X.row(0) - q).squaredNorm(); reasonable_dist = round(reasonable_dist * 1024.f - 1) / 1024.f; auto allnn = index.radius(q, reasonable_dist); auto all_trueNN = radius_simple(X, q, reasonable_dist); CAPTURE(reasonable_dist); require_neighbor_lists_same(allnn, all_trueNN); auto allnn_idxs = index.radius_idxs(q, reasonable_dist); auto trueNN_idxs = idxs_from_neighbors(all_trueNN); CAPTURE(ar::to_string(ar::sort(allnn_idxs ))); CAPTURE(ar::to_string(ar::sort(trueNN_idxs))); require_neighbor_idx_lists_same(allnn_idxs, trueNN_idxs); // ------------------------ knn for (int k = 1; k <= 5; k += 2) { auto knn = index.knn(q, k); auto trueKnn = knn_simple(X, q, k); require_neighbor_lists_same(knn, trueKnn); auto knn_idxs = index.knn_idxs(q, k); auto trueKnn_idxs = idxs_from_neighbors(trueKnn); CAPTURE(k); CAPTURE(knn[0].dist); CAPTURE(knn[0].idx); CAPTURE(trueKnn[0].dist); CAPTURE(trueKnn[0].idx); CAPTURE(ar::to_string(ar::sort(knn_idxs ))); CAPTURE(ar::to_string(ar::sort(trueKnn_idxs))); REQUIRE(ar::all_eq(knn_idxs, trueKnn_idxs)); } } } template<class IndexT> void _test_index(int64_t N=100, int64_t D=16) { using Scalar = typename IndexT::Scalar; RowMatrix<Scalar> X(N, D); X.setRandom(); IndexT index(X); RowVector<Scalar> q(D); _test_index_with_query(X, index, q); } template<class IndexT> void _test_cluster_index(int64_t N=100, int64_t D=16, int num_clusters=2) { using Scalar = typename IndexT::Scalar; RowMatrix<Scalar> X(N, D); X.setRandom(); IndexT index(X, num_clusters); RowVector<Scalar> q(D); _test_index_with_query(X, index, q); } #endif // __NEIGHBOR_TESTING_UTILS_HPP <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: implementationentry.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 09:18:34 $ * * 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 _CPPUHELPER_IMPLEMENATIONENTRY_HXX_ #define _CPPUHELPER_IMPLEMENATIONENTRY_HXX_ #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif namespace cppu { /** One struct instance represents all data necessary for registering one service implementation. */ struct ImplementationEntry { /** Function, that creates an instance of the implemenation */ ComponentFactoryFunc create; /** Function, that returns the implemenation-name of the implemenation (same as XServiceInfo.getImplementationName() ). */ rtl::OUString ( SAL_CALL * getImplementationName )(); /** Function, that returns all supported servicenames of the implemenation ( same as XServiceInfo.getSupportedServiceNames() ). */ com::sun::star::uno::Sequence< rtl::OUString > ( SAL_CALL * getSupportedServiceNames ) (); /** Function, that creates a SingleComponentFactory. */ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleComponentFactory > ( SAL_CALL * createFactory )( ComponentFactoryFunc fptr, ::rtl::OUString const & rImplementationName, ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames, rtl_ModuleCount * pModCount ); /** The shared-library module-counter of the implemenation. Maybe 0. The module-counter is used during by the createFactory()-function. */ rtl_ModuleCount * moduleCounter; /** Must be set to 0 ! For future extensions. */ sal_Int32 nFlags; }; /** Helper function for implementation of the component_writeInfo()-function. @param pServiceManager The first parameter passed to component_writeInfo()-function (This is an instance of the service manager, that creates the factory). @param pRegistryKey The second parameter passed to the component_writeInfo()-function. This is a reference to the registry key, into which the implementation data shall be written to. @param entries Each element of the entries-array must contains a function pointer table for registering an implemenation. The end of the array must be marked with a 0 entry in the create-function. @return sal_True, if all implementations could be registered, otherwise sal_False. */ sal_Bool component_writeInfoHelper( void *pServiceManager, void *pRegistryKey , const struct ImplementationEntry entries[] ); /** Helper function for implementation of the component_getFactory()-function, that must be implemented by every shared library component. @param pImplName The implementation-name to be instantiated ( This is the first parameter passed to the component_getFactory @param pServiceManager The first parameter passed to component_writeInfo()-function (This is a of the service manager, that creates the factory). @param pRegistryKey The second parameter passed to the component_writeInfo()-function. This is a reference to the registry key, where the implementation data has been written to. @param entries Each element of the entries-array must contains a function pointer table for creating a factor of the implementation. The end of the array must be marked with a 0 entry in the create-function. @return 0 if the helper failed to instantiate a factory, otherwise an acquired pointer to a factory. */ void *component_getFactoryHelper( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey, const struct ImplementationEntry entries[] ); } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.140); FILE MERGED 2008/04/01 10:54:25 thb 1.2.140.2: #i85898# Stripping all external header guards 2008/03/28 15:25:21 rt 1.2.140.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: implementationentry.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CPPUHELPER_IMPLEMENATIONENTRY_HXX_ #define _CPPUHELPER_IMPLEMENATIONENTRY_HXX_ #include <cppuhelper/factory.hxx> namespace cppu { /** One struct instance represents all data necessary for registering one service implementation. */ struct ImplementationEntry { /** Function, that creates an instance of the implemenation */ ComponentFactoryFunc create; /** Function, that returns the implemenation-name of the implemenation (same as XServiceInfo.getImplementationName() ). */ rtl::OUString ( SAL_CALL * getImplementationName )(); /** Function, that returns all supported servicenames of the implemenation ( same as XServiceInfo.getSupportedServiceNames() ). */ com::sun::star::uno::Sequence< rtl::OUString > ( SAL_CALL * getSupportedServiceNames ) (); /** Function, that creates a SingleComponentFactory. */ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleComponentFactory > ( SAL_CALL * createFactory )( ComponentFactoryFunc fptr, ::rtl::OUString const & rImplementationName, ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames, rtl_ModuleCount * pModCount ); /** The shared-library module-counter of the implemenation. Maybe 0. The module-counter is used during by the createFactory()-function. */ rtl_ModuleCount * moduleCounter; /** Must be set to 0 ! For future extensions. */ sal_Int32 nFlags; }; /** Helper function for implementation of the component_writeInfo()-function. @param pServiceManager The first parameter passed to component_writeInfo()-function (This is an instance of the service manager, that creates the factory). @param pRegistryKey The second parameter passed to the component_writeInfo()-function. This is a reference to the registry key, into which the implementation data shall be written to. @param entries Each element of the entries-array must contains a function pointer table for registering an implemenation. The end of the array must be marked with a 0 entry in the create-function. @return sal_True, if all implementations could be registered, otherwise sal_False. */ sal_Bool component_writeInfoHelper( void *pServiceManager, void *pRegistryKey , const struct ImplementationEntry entries[] ); /** Helper function for implementation of the component_getFactory()-function, that must be implemented by every shared library component. @param pImplName The implementation-name to be instantiated ( This is the first parameter passed to the component_getFactory @param pServiceManager The first parameter passed to component_writeInfo()-function (This is a of the service manager, that creates the factory). @param pRegistryKey The second parameter passed to the component_writeInfo()-function. This is a reference to the registry key, where the implementation data has been written to. @param entries Each element of the entries-array must contains a function pointer table for creating a factor of the implementation. The end of the array must be marked with a 0 entry in the create-function. @return 0 if the helper failed to instantiate a factory, otherwise an acquired pointer to a factory. */ void *component_getFactoryHelper( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey, const struct ImplementationEntry entries[] ); } #endif <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // RRLOG // // This program can be used by server admins to // examine their record/replay files in detail. // // system headers #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #ifndef _WIN32 # include <sys/time.h> # include <unistd.h> typedef int64_t s64; #else typedef __int64 s64; #endif // common headers #include "common.h" #include "global.h" #include "Protocol.h" #include "Pack.h" #include "TextUtils.h" #include "version.h" // bzfs headers #include "RecordReplay.h" // local headers #include "MsgStrings.h" // Type Definitions // ---------------- typedef uint16_t u16; typedef uint32_t u32; typedef s64 RRtime; typedef struct RRpacket { struct RRpacket *next; struct RRpacket *prev; u16 mode; u16 code; u32 len; u32 nextFilePos; u32 prevFilePos; RRtime timestamp; char *data; } RRpacket; static const int RRpacketHdrSize = sizeof(RRpacket) - (2 * sizeof(RRpacket*) - sizeof(char*)); typedef struct { u32 magic; // record file type identifier u32 version; // record file version u32 offset; // length of the full header RRtime filetime; // amount of time in the file u32 player; // player that saved this record file u32 flagsSize; // size of the flags data u32 worldSize; // size of world database char callSign[CallSignLen]; // player's callsign char email[EmailLen]; // player's email char serverVersion[8]; // BZFS protocol version char appVersion[MessageLen]; // BZFS application version char realHash[64]; // hash of worldDatabase char worldSettings[4 + WorldSettingsSize]; // the game settings char *flags; // a list of the flags types char *world; // the world } ReplayHeader; static const int ReplayHeaderSize = sizeof(ReplayHeader) - (2 * sizeof(char*)); // Function Prototypes // ------------------- static void printHelp(const char* execName); static bool loadHeader(ReplayHeader *h, FILE *f); static RRpacket *loadPacket(FILE *f); static void *nboUnpackRRtime(void *buf, RRtime& value); static std::string strRRtime(RRtime timestamp); int debugLevel = 0; static int outputLevel = 0; /****************************************************************************/ int main(int argc, char** argv) { FILE *file = NULL; ReplayHeader header; RRpacket *p; const char* execName = argv[0]; bool useColor = true; bool useEmail = true; bool onlyMessages = false; printf("\nRRLOG-%s\nProtocol BZFS%s: %i known packet types\n\n", getAppVersion(), getProtocolVersion(), MsgStrings::knownPacketTypes()); if (argc < 2) { printHelp(execName); exit(1); } while (argc > 1) { if (strcmp("-h", argv[1]) == 0) { printHelp(execName); exit(0); } else if (strcmp("-o", argv[1]) == 0) { if (argc < 3) { printf("* Missing the -o parameter or the filename\n\n"); printHelp(execName); exit(1); } else { outputLevel = atoi(argv[2]); argc = argc - 2; argv = argv + 2; } } else if (strcmp("-c", argv[1]) == 0) { useColor = false; argc--; argv++; } else if (strcmp("-e", argv[1]) == 0) { useEmail = false; argc--; argv++; } else if (strcmp("-m", argv[1]) == 0) { onlyMessages = true; argc--; argv++; } else { argc++; break; } } if (argc < 2) { printf("* Missing filename\n\n"); printHelp(execName); exit(1); } file = fopen(argv[1], "rb"); if (file == NULL) { perror("fopen"); exit(1); } if (!loadHeader(&header, file)) { printf("Couldn't load file header\n"); fclose(file); exit(1); } unsigned int secs = header.filetime / 1000000; unsigned int days = secs / (24 * 60 * 60); secs = secs % (24 * 60 * 60); unsigned int hours = secs / (60 * 60); secs = secs % (60 * 60); unsigned int minutes = secs / 60; secs = secs % 60; unsigned int usecs = header.filetime % 1000000; printf("magic: 0x%04X\n", header.magic); printf("replay: version %i\n", header.version); printf("offset: %i\n", header.offset); printf("time: %i days, %i hours, %i minutes, %i seconds, %i usecs\n", days, hours, minutes, secs, usecs); printf("author: %s (%s)\n", header.callSign, header.email); printf("bzfs: bzfs-%s\n", header.appVersion); printf("protocol: %.8s\n", header.serverVersion); printf("flagSize: %i\n", header.flagsSize); printf("worldSize: %i\n", header.worldSize); printf("worldHash: %s\n", header.realHash); printf("\n"); MsgStrings::init(); MsgStrings::colorize(useColor); MsgStrings::showEmail(useEmail); // MsgStrings::colorize(false); bool needUpdate = true; while ((p = loadPacket(file)) != NULL) { if (needUpdate && (p->mode == RealPacket)) { needUpdate = false; } if ((p->mode == RealPacket) || (p->mode == HiddenPacket) || ((p->mode == StatePacket) && needUpdate)) { if (!onlyMessages || (p->code == MsgMessage)) { int i, j; MsgStringList list = MsgStrings::msgFromServer (p->len, p->code, p->data); for (i = 0; i < (int) list.size(); i++) { if (list[i].level > outputLevel) { break; } if (i == 0) { std::cout << strRRtime(p->timestamp) << ": "; } for (j = 0; j < list[i].level; j++) { std::cout << " "; } std::cout << list[i].color; std::cout << list[i].text; if (useColor) { std::cout << "\033[0m"; } std::cout << std::endl; } } } else if (p->mode == StatePacket) { MsgStrings::msgFromServer(p->len, p->code, p->data); } else if (p->mode == UpdatePacket) { std::cout << strRRtime(p->timestamp) << ": UPDATE PACKET" << std::endl; } delete[] p->data; delete p; } delete[] header.world; delete[] header.flags; fclose(file); return 0; } /****************************************************************************/ static void printHelp(const char* execName) { printf("usage:\t%s [options] <filename>\n\n", execName); printf(" -h : print help\n"); printf(" -o <level> : set output level\n"); printf(" -c : disable printing ANSI colors\n"); // printf(" -e : disable printing emails\n"); // printf(" -m : only print message packets\n"); printf("\n"); return; } /****************************************************************************/ static bool loadHeader(ReplayHeader *h, FILE *f) { char buffer[ReplayHeaderSize]; void *buf; if (fread(buffer, ReplayHeaderSize, 1, f) <= 0) { return false; } buf = nboUnpackUInt(buffer, h->magic); buf = nboUnpackUInt(buf, h->version); buf = nboUnpackUInt(buf, h->offset); buf = nboUnpackRRtime(buf, h->filetime); buf = nboUnpackUInt(buf, h->player); buf = nboUnpackUInt(buf, h->flagsSize); buf = nboUnpackUInt(buf, h->worldSize); buf = nboUnpackString(buf, h->callSign, sizeof(h->callSign)); buf = nboUnpackString(buf, h->email, sizeof(h->email)); buf = nboUnpackString(buf, h->serverVersion, sizeof(h->serverVersion)); buf = nboUnpackString(buf, h->appVersion, sizeof(h->appVersion)); buf = nboUnpackString(buf, h->realHash, sizeof(h->realHash)); // load the flags, if there are any if (h->flagsSize > 0) { h->flags = new char [h->flagsSize]; if (fread(h->flags, h->flagsSize, 1, f) == 0) { return false; } } else { h->flags = NULL; } // load the world database h->world = new char [h->worldSize]; if (fread(h->world, h->worldSize, 1, f) == 0) { return false; } return true; } /****************************************************************************/ static RRpacket* loadPacket(FILE *f) { RRpacket *p; char bufStart[RRpacketHdrSize]; void *buf; if (f == NULL) { return false; } p = new RRpacket; if (fread(bufStart, RRpacketHdrSize, 1, f) <= 0) { delete p; return NULL; } buf = nboUnpackUShort(bufStart, p->mode); buf = nboUnpackUShort(buf, p->code); buf = nboUnpackUInt(buf, p->len); buf = nboUnpackUInt(buf, p->nextFilePos); buf = nboUnpackUInt(buf, p->prevFilePos); buf = nboUnpackRRtime(buf, p->timestamp); if (p->len > (MaxPacketLen - ((int)sizeof(u16) * 2))) { fprintf(stderr, "loadPacket: ERROR, packtlen = %i\n", p->len); delete p; return NULL; } if (p->len == 0) { p->data = NULL; } else { p->data = new char [p->len]; if (fread(p->data, p->len, 1, f) <= 0) { delete[] p->data; delete p; return NULL; } } return p; } /****************************************************************************/ static void* nboUnpackRRtime(void *buf, RRtime& value) { u32 msb, lsb; buf = nboUnpackUInt(buf, msb); buf = nboUnpackUInt(buf, lsb); value = ((RRtime)msb << 32) + (RRtime)lsb; return buf; } static std::string strRRtime(RRtime timestamp) { time_t date = (time_t)(timestamp / 1000000); char buffer[32]; strftime(buffer, 32, "%Y/%m/%d %T", gmtime(&date)); std::string str = buffer; unsigned int millisecs = (timestamp % 1000000) / 1000; str += TextUtils::format(" (%03i ms)", millisecs); return str; } /****************************************************************************/ // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>more header timing info, cleaned up the tab/space mess<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // RRLOG // // This program can be used by server admins to // examine their record/replay files in detail. // // system headers #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #ifndef _WIN32 # include <sys/time.h> # include <unistd.h> typedef int64_t s64; #else typedef __int64 s64; #endif // common headers #include "common.h" #include "global.h" #include "Protocol.h" #include "Pack.h" #include "TextUtils.h" #include "version.h" // bzfs headers #include "RecordReplay.h" // local headers #include "MsgStrings.h" // Type Definitions // ---------------- typedef uint16_t u16; typedef uint32_t u32; typedef s64 RRtime; typedef struct RRpacket { struct RRpacket *next; struct RRpacket *prev; u16 mode; u16 code; u32 len; u32 nextFilePos; u32 prevFilePos; RRtime timestamp; char *data; } RRpacket; static const int RRpacketHdrSize = sizeof(RRpacket) - (2 * sizeof(RRpacket*) - sizeof(char*)); typedef struct { u32 magic; // record file type identifier u32 version; // record file version u32 offset; // length of the full header RRtime filetime; // amount of time in the file u32 player; // player that saved this record file u32 flagsSize; // size of the flags data u32 worldSize; // size of world database char callSign[CallSignLen]; // player's callsign char email[EmailLen]; // player's email char serverVersion[8]; // BZFS protocol version char appVersion[MessageLen]; // BZFS application version char realHash[64]; // hash of worldDatabase char worldSettings[4 + WorldSettingsSize]; // the game settings char *flags; // a list of the flags types char *world; // the world } ReplayHeader; static const int ReplayHeaderSize = sizeof(ReplayHeader) - (2 * sizeof(char*)); // Function Prototypes // ------------------- static void printHelp(const char* execName); static bool loadHeader(ReplayHeader *h, FILE *f); static RRpacket *loadPacket(FILE *f); static void *nboUnpackRRtime(void *buf, RRtime& value); static std::string strRRtime(RRtime timestamp); int debugLevel = 0; static int outputLevel = 0; /****************************************************************************/ int main(int argc, char** argv) { FILE *file = NULL; ReplayHeader header; RRpacket *p; const char* execName = argv[0]; bool useColor = true; bool useEmail = true; bool onlyMessages = false; printf("\nRRLOG-%s\nProtocol BZFS%s: %i known packet types\n\n", getAppVersion(), getProtocolVersion(), MsgStrings::knownPacketTypes()); if (argc < 2) { printHelp(execName); exit(1); } while (argc > 1) { if (strcmp("-h", argv[1]) == 0) { printHelp(execName); exit(0); } else if (strcmp("-o", argv[1]) == 0) { if (argc < 3) { printf("* Missing the -o parameter or the filename\n\n"); printHelp(execName); exit(1); } else { outputLevel = atoi(argv[2]); argc = argc - 2; argv = argv + 2; } } else if (strcmp("-c", argv[1]) == 0) { useColor = false; argc--; argv++; } else if (strcmp("-e", argv[1]) == 0) { useEmail = false; argc--; argv++; } else if (strcmp("-m", argv[1]) == 0) { onlyMessages = true; argc--; argv++; } else { argc++; break; } } if (argc < 2) { printf("* Missing filename\n\n"); printHelp(execName); exit(1); } file = fopen(argv[1], "rb"); if (file == NULL) { perror("fopen"); exit(1); } if (!loadHeader(&header, file)) { printf("Couldn't load file header\n"); fclose(file); exit(1); } unsigned int secs = header.filetime / 1000000; unsigned int days = secs / (24 * 60 * 60); secs = secs % (24 * 60 * 60); unsigned int hours = secs / (60 * 60); secs = secs % (60 * 60); unsigned int minutes = secs / 60; secs = secs % 60; unsigned int usecs = header.filetime % 1000000; // load the first packet for its timestamp p = loadPacket(file); time_t startTime, endTime; if (p != NULL) { startTime = (time_t)(p->timestamp / 1000000); endTime = (time_t)((header.filetime + p->timestamp) / 1000000); } else { startTime = endTime = 0; } printf("magic: 0x%04X\n", header.magic); printf("replay: version %i\n", header.version); printf("offset: %i\n", header.offset); printf("length: %-i days, %i hours, %i minutes, %i seconds, %i usecs\n", days, hours, minutes, secs, usecs); printf("start: %s", ctime(&startTime)); printf("end: %s", ctime(&endTime)); printf("author: %s (%s)\n", header.callSign, header.email); printf("bzfs: bzfs-%s\n", header.appVersion); printf("protocol: %.8s\n", header.serverVersion); printf("flagSize: %i\n", header.flagsSize); printf("worldSize: %i\n", header.worldSize); printf("worldHash: %s\n", header.realHash); printf("\n"); MsgStrings::init(); MsgStrings::colorize(useColor); MsgStrings::showEmail(useEmail); // MsgStrings::colorize(false); bool needUpdate = true; do { if (needUpdate && (p->mode == RealPacket)) { needUpdate = false; } if ((p->mode == RealPacket) || (p->mode == HiddenPacket) || ((p->mode == StatePacket) && needUpdate)) { if (!onlyMessages || (p->code == MsgMessage)) { int i, j; MsgStringList list = MsgStrings::msgFromServer (p->len, p->code, p->data); for (i = 0; i < (int) list.size(); i++) { if (list[i].level > outputLevel) { break; } if (i == 0) { std::cout << strRRtime(p->timestamp) << ": "; } for (j = 0; j < list[i].level; j++) { std::cout << " "; } std::cout << list[i].color; std::cout << list[i].text; if (useColor) { std::cout << "\033[0m"; } std::cout << std::endl; } } } else if (p->mode == StatePacket) { MsgStrings::msgFromServer(p->len, p->code, p->data); } else if (p->mode == UpdatePacket) { std::cout << strRRtime(p->timestamp) << ": UPDATE PACKET" << std::endl; } delete[] p->data; delete p; } while ((p = loadPacket(file)) != NULL); delete[] header.world; delete[] header.flags; fclose(file); return 0; } /****************************************************************************/ static void printHelp(const char* execName) { printf("usage:\t%s [options] <filename>\n\n", execName); printf(" -h : print help\n"); printf(" -o <level> : set output level\n"); printf(" -c : disable printing ANSI colors\n"); // printf(" -e : disable printing emails\n"); // printf(" -m : only print message packets\n"); printf("\n"); return; } /****************************************************************************/ static bool loadHeader(ReplayHeader *h, FILE *f) { char buffer[ReplayHeaderSize]; void *buf; if (fread(buffer, ReplayHeaderSize, 1, f) <= 0) { return false; } buf = nboUnpackUInt(buffer, h->magic); buf = nboUnpackUInt(buf, h->version); buf = nboUnpackUInt(buf, h->offset); buf = nboUnpackRRtime(buf, h->filetime); buf = nboUnpackUInt(buf, h->player); buf = nboUnpackUInt(buf, h->flagsSize); buf = nboUnpackUInt(buf, h->worldSize); buf = nboUnpackString(buf, h->callSign, sizeof(h->callSign)); buf = nboUnpackString(buf, h->email, sizeof(h->email)); buf = nboUnpackString(buf, h->serverVersion, sizeof(h->serverVersion)); buf = nboUnpackString(buf, h->appVersion, sizeof(h->appVersion)); buf = nboUnpackString(buf, h->realHash, sizeof(h->realHash)); // load the flags, if there are any if (h->flagsSize > 0) { h->flags = new char [h->flagsSize]; if (fread(h->flags, h->flagsSize, 1, f) == 0) { return false; } } else { h->flags = NULL; } // load the world database h->world = new char [h->worldSize]; if (fread(h->world, h->worldSize, 1, f) == 0) { return false; } return true; } /****************************************************************************/ static RRpacket* loadPacket(FILE *f) { RRpacket *p; char bufStart[RRpacketHdrSize]; void *buf; if (f == NULL) { return false; } p = new RRpacket; if (fread(bufStart, RRpacketHdrSize, 1, f) <= 0) { delete p; return NULL; } buf = nboUnpackUShort(bufStart, p->mode); buf = nboUnpackUShort(buf, p->code); buf = nboUnpackUInt(buf, p->len); buf = nboUnpackUInt(buf, p->nextFilePos); buf = nboUnpackUInt(buf, p->prevFilePos); buf = nboUnpackRRtime(buf, p->timestamp); if (p->len > (MaxPacketLen - ((int)sizeof(u16) * 2))) { fprintf(stderr, "loadPacket: ERROR, packtlen = %i\n", p->len); delete p; return NULL; } if (p->len == 0) { p->data = NULL; } else { p->data = new char [p->len]; if (fread(p->data, p->len, 1, f) <= 0) { delete[] p->data; delete p; return NULL; } } return p; } /****************************************************************************/ static void* nboUnpackRRtime(void *buf, RRtime& value) { u32 msb, lsb; buf = nboUnpackUInt(buf, msb); buf = nboUnpackUInt(buf, lsb); value = ((RRtime)msb << 32) + (RRtime)lsb; return buf; } static std::string strRRtime(RRtime timestamp) { time_t date = (time_t)(timestamp / 1000000); char buffer[32]; strftime(buffer, 32, "%Y/%m/%d %T", gmtime(&date)); std::string str = buffer; unsigned int millisecs = (timestamp % 1000000) / 1000; str += TextUtils::format(" (%03i ms)", millisecs); return str; } /****************************************************************************/ // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief V8 enigne configuration /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "ApplicationV8.h" #include "Basics/ConditionLocker.h" #include "Logger/Logger.h" #include "V8/v8-conv.h" #include "V8/v8-shell.h" #include "V8/v8-utils.h" #include "V8Server/v8-actions.h" #include "V8Server/v8-query.h" #include "V8Server/v8-vocbase.h" using namespace triagens::basics; using namespace triagens::arango; using namespace std; #include "js/common/bootstrap/js-modules.h" #include "js/common/bootstrap/js-print.h" #include "js/common/bootstrap/js-errors.h" #include "js/server/js-ahuacatl.h" #include "js/server/js-server.h" // ----------------------------------------------------------------------------- // --SECTION-- class V8GcThread // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// namespace { //////////////////////////////////////////////////////////////////////////////// /// @brief garbage collector //////////////////////////////////////////////////////////////////////////////// class V8GcThread : public Thread { public: V8GcThread (ApplicationV8* applicationV8) : Thread("v8-gc"), _applicationV8(applicationV8) { } public: void run () { _applicationV8->collectGarbage(); } private: ApplicationV8* _applicationV8; }; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- class ApplicationV8 // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// ApplicationV8::ApplicationV8 (string const& binaryPath) : ApplicationFeature("V8"), _startupPath(), _startupModules("js/modules"), _actionPath(), _gcInterval(1000), _startupLoader(), _actionLoader(), _vocbase(0), _nrInstances(0), _contexts(0), _contextCondition(), _freeContexts(), _dirtyContexts(), _stopping(0) { // ............................................................................. // use relative system paths // ............................................................................. #ifdef TRI_ENABLE_RELATIVE_SYSTEM _actionPath = binaryPath + "/../share/arango/js/actions/system"; _startupModules = binaryPath + "/../share/arango/js/server/modules" + ";" + binaryPath + "/../share/arango/js/common/modules"; #else // ............................................................................. // use relative development paths // ............................................................................. #ifdef TRI_ENABLE_RELATIVE_DEVEL #ifdef TRI_SYSTEM_ACTION_PATH _actionPath = TRI_SYSTEM_ACTION_PATH; #else _actionPath = binaryPath + "/../js/actions/system"; #endif #ifdef TRI_STARTUP_MODULES_PATH _startupModules = TRI_STARTUP_MODULES_PATH; #else _startupModules = binaryPath + "/../js/server/modules" + ";" + binaryPath + "/../js/common/modules"; #endif // ............................................................................. // use absolute paths // ............................................................................. #else #ifdef _PKGDATADIR_ _actionPath = string(_PKGDATADIR_) + "/js/actions/system"; _startupModules = string(_PKGDATADIR_) + "/js/server/modules" + ";" + string(_PKGDATADIR_) + "/js/common/modules"; #endif #endif #endif } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// ApplicationV8::~ApplicationV8 () { } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief sets the concurrency //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::setConcurrency (size_t n) { _nrInstances = n; } //////////////////////////////////////////////////////////////////////////////// /// @brief sets the database //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::setVocbase (TRI_vocbase_t* vocbase) { _vocbase = vocbase; } //////////////////////////////////////////////////////////////////////////////// /// @brief enters an context //////////////////////////////////////////////////////////////////////////////// ApplicationV8::V8Context* ApplicationV8::enterContext () { CONDITION_LOCKER(guard, _contextCondition); while (_freeContexts.empty()) { LOGGER_DEBUG << "waiting for unused V8 context"; guard.wait(); } LOGGER_TRACE << "found unused V8 context"; V8Context* context = _freeContexts.back(); _freeContexts.pop_back(); context->_locker = new v8::Locker(context->_isolate); context->_isolate->Enter(); context->_context->Enter(); return context; } //////////////////////////////////////////////////////////////////////////////// /// @brief exists an context //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::exitContext (V8Context* context) { context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; ++context->_dirt; { CONDITION_LOCKER(guard, _contextCondition); if (context->_dirt < _gcInterval) { _freeContexts.push_back(context); } else { _dirtyContexts.push_back(context); } guard.broadcast(); } LOGGER_TRACE << "returned dirty V8 context"; } //////////////////////////////////////////////////////////////////////////////// /// @brief runs the garbage collection //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::collectGarbage () { while (_stopping == 0) { V8Context* context = 0; { CONDITION_LOCKER(guard, _contextCondition); if (_dirtyContexts.empty()) { guard.wait(); } if (! _dirtyContexts.empty()) { context = _dirtyContexts.back(); _dirtyContexts.pop_back(); } } if (context != 0) { LOGGER_TRACE << "collecting V8 garbage"; context->_locker = new v8::Locker(context->_isolate); context->_isolate->Enter(); context->_context->Enter(); while (!v8::V8::IdleNotification()) { } context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; context->_dirt = 0; { CONDITION_LOCKER(guard, _contextCondition); _freeContexts.push_back(context); guard.broadcast(); } } } } //////////////////////////////////////////////////////////////////////////////// /// @brief disables actions //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::disableActions () { _actionPath.clear(); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ApplicationFeature methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::setupOptions (map<string, basics::ProgramOptionsDescription>& options) { options["JAVASCRIPT Options:help-admin"] ("javascript.gc-interval", &_gcInterval, "JavaScript garbage collection interval (each x requests)") ; options["DIRECTORY Options:help-admin"] ("javascript.action-directory", &_actionPath, "path to the JavaScript action directory") ("javascript.modules-path", &_startupModules, "one or more directories separated by (semi-) colons") ("javascript.startup-directory", &_startupPath, "path to the directory containing alternate JavaScript startup scripts") ; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::prepare () { LOGGER_INFO << "using JavaScript modules path '" << _startupModules << "'"; // set up the startup loader if (_startupPath.empty()) { LOGGER_INFO << "using built-in JavaScript startup files"; _startupLoader.defineScript("common/bootstrap/modules.js", JS_common_bootstrap_modules); _startupLoader.defineScript("common/bootstrap/print.js", JS_common_bootstrap_print); _startupLoader.defineScript("common/bootstrap/errors.js", JS_common_bootstrap_errors); _startupLoader.defineScript("server/ahuacatl.js", JS_server_ahuacatl); _startupLoader.defineScript("server/server.js", JS_server_server); } else { LOGGER_INFO << "using JavaScript startup files at '" << _startupPath << "'"; _startupLoader.setDirectory(_startupPath); } // set up action loader if (! _actionPath.empty()) { LOGGER_INFO << "using JavaScript action files at '" << _actionPath << "'"; _actionLoader.setDirectory(_actionPath); } // setup instances _contexts = new V8Context*[_nrInstances]; for (size_t i = 0; i < _nrInstances; ++i) { bool ok = prepareV8Instance(i); if (! ok) { return false; } } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::isStartable () { return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::start () { _gcThread = new V8GcThread(this); _gcThread->start(); return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::isStarted () { return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::beginShutdown () { _stopping = 1; _contextCondition.broadcast(); } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::shutdown () { _gcThread->stop(); for (size_t i = 0; i < _nrInstances; ++i) { shutdownV8Instance(i); } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief prepares a V8 instance //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::prepareV8Instance (size_t i) { static char const* files[] = { "common/bootstrap/modules.js", "common/bootstrap/print.js", "common/bootstrap/errors.js", "server/ahuacatl.js", "server/server.js" }; LOGGER_TRACE << "initialising V8 context #" << i; V8Context* context = _contexts[i] = new V8Context(); // enter a new isolate context->_isolate = v8::Isolate::New(); context->_locker = new v8::Locker(context->_isolate); context->_isolate->Enter(); // create the context context->_context = v8::Context::New(); if (context->_context.IsEmpty()) { LOGGER_FATAL << "cannot initialize V8 engine"; context->_isolate->Exit(); delete context->_locker; return false; } context->_context->Enter(); TRI_InitV8VocBridge(context->_context, _vocbase); TRI_InitV8Queries(context->_context); if (! _actionPath.empty()) { TRI_InitV8Actions(context->_context, this); } TRI_InitV8Conversions(context->_context); TRI_InitV8Utils(context->_context, _startupModules); TRI_InitV8Shell(context->_context); // load all init files for (i = 0; i < sizeof(files) / sizeof(files[0]); ++i) { bool ok = _startupLoader.loadScript(context->_context, files[i]); if (! ok) { LOGGER_FATAL << "cannot load JavaScript utilities from file '" << files[i] << "'"; context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; return false; } } // load all actions if (! _actionPath.empty()) { bool ok = _actionLoader.executeAllScripts(context->_context); if (! ok) { LOGGER_FATAL << "cannot load JavaScript actions from directory '" << _actionLoader.getDirectory() << "'"; context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; return false; } } // and return from the context context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; LOGGER_TRACE << "initialised V8 context #" << i; _freeContexts.push_back(context); return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief shut downs a V8 instances //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::shutdownV8Instance (size_t i) { LOGGER_TRACE << "shutting down V8 context #" << i; V8Context* context = _contexts[i]; context->_isolate->Enter(); context->_context->Enter(); while (!v8::V8::IdleNotification()) { } TRI_v8_global_t* v8g = (TRI_v8_global_t*) context->_isolate->GetData(); if (v8g) { delete v8g; } context->_context->Exit(); context->_context.Dispose(); context->_isolate->Exit(); context->_isolate->Dispose(); LOGGER_TRACE << "closed V8 context #" << i; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <commit_msg>fixed cleanup<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief V8 enigne configuration /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "ApplicationV8.h" #include "Basics/ConditionLocker.h" #include "Logger/Logger.h" #include "V8/v8-conv.h" #include "V8/v8-shell.h" #include "V8/v8-utils.h" #include "V8Server/v8-actions.h" #include "V8Server/v8-query.h" #include "V8Server/v8-vocbase.h" using namespace triagens::basics; using namespace triagens::arango; using namespace std; #include "js/common/bootstrap/js-modules.h" #include "js/common/bootstrap/js-print.h" #include "js/common/bootstrap/js-errors.h" #include "js/server/js-ahuacatl.h" #include "js/server/js-server.h" // ----------------------------------------------------------------------------- // --SECTION-- class V8GcThread // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// namespace { //////////////////////////////////////////////////////////////////////////////// /// @brief garbage collector //////////////////////////////////////////////////////////////////////////////// class V8GcThread : public Thread { public: V8GcThread (ApplicationV8* applicationV8) : Thread("v8-gc"), _applicationV8(applicationV8) { } public: void run () { _applicationV8->collectGarbage(); } private: ApplicationV8* _applicationV8; }; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- class ApplicationV8 // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// ApplicationV8::ApplicationV8 (string const& binaryPath) : ApplicationFeature("V8"), _startupPath(), _startupModules("js/modules"), _actionPath(), _gcInterval(1000), _startupLoader(), _actionLoader(), _vocbase(0), _nrInstances(0), _contexts(0), _contextCondition(), _freeContexts(), _dirtyContexts(), _stopping(0) { // ............................................................................. // use relative system paths // ............................................................................. #ifdef TRI_ENABLE_RELATIVE_SYSTEM _actionPath = binaryPath + "/../share/arango/js/actions/system"; _startupModules = binaryPath + "/../share/arango/js/server/modules" + ";" + binaryPath + "/../share/arango/js/common/modules"; #else // ............................................................................. // use relative development paths // ............................................................................. #ifdef TRI_ENABLE_RELATIVE_DEVEL #ifdef TRI_SYSTEM_ACTION_PATH _actionPath = TRI_SYSTEM_ACTION_PATH; #else _actionPath = binaryPath + "/../js/actions/system"; #endif #ifdef TRI_STARTUP_MODULES_PATH _startupModules = TRI_STARTUP_MODULES_PATH; #else _startupModules = binaryPath + "/../js/server/modules" + ";" + binaryPath + "/../js/common/modules"; #endif // ............................................................................. // use absolute paths // ............................................................................. #else #ifdef _PKGDATADIR_ _actionPath = string(_PKGDATADIR_) + "/js/actions/system"; _startupModules = string(_PKGDATADIR_) + "/js/server/modules" + ";" + string(_PKGDATADIR_) + "/js/common/modules"; #endif #endif #endif } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// ApplicationV8::~ApplicationV8 () { } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief sets the concurrency //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::setConcurrency (size_t n) { _nrInstances = n; } //////////////////////////////////////////////////////////////////////////////// /// @brief sets the database //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::setVocbase (TRI_vocbase_t* vocbase) { _vocbase = vocbase; } //////////////////////////////////////////////////////////////////////////////// /// @brief enters an context //////////////////////////////////////////////////////////////////////////////// ApplicationV8::V8Context* ApplicationV8::enterContext () { CONDITION_LOCKER(guard, _contextCondition); while (_freeContexts.empty()) { LOGGER_DEBUG << "waiting for unused V8 context"; guard.wait(); } LOGGER_TRACE << "found unused V8 context"; V8Context* context = _freeContexts.back(); _freeContexts.pop_back(); context->_locker = new v8::Locker(context->_isolate); context->_isolate->Enter(); context->_context->Enter(); return context; } //////////////////////////////////////////////////////////////////////////////// /// @brief exists an context //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::exitContext (V8Context* context) { context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; ++context->_dirt; { CONDITION_LOCKER(guard, _contextCondition); if (context->_dirt < _gcInterval) { _freeContexts.push_back(context); } else { _dirtyContexts.push_back(context); } guard.broadcast(); } LOGGER_TRACE << "returned dirty V8 context"; } //////////////////////////////////////////////////////////////////////////////// /// @brief runs the garbage collection //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::collectGarbage () { while (_stopping == 0) { V8Context* context = 0; { CONDITION_LOCKER(guard, _contextCondition); if (_dirtyContexts.empty()) { guard.wait(); } if (! _dirtyContexts.empty()) { context = _dirtyContexts.back(); _dirtyContexts.pop_back(); } } if (context != 0) { LOGGER_TRACE << "collecting V8 garbage"; context->_locker = new v8::Locker(context->_isolate); context->_isolate->Enter(); context->_context->Enter(); while (!v8::V8::IdleNotification()) { } context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; context->_dirt = 0; { CONDITION_LOCKER(guard, _contextCondition); _freeContexts.push_back(context); guard.broadcast(); } } } } //////////////////////////////////////////////////////////////////////////////// /// @brief disables actions //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::disableActions () { _actionPath.clear(); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ApplicationFeature methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::setupOptions (map<string, basics::ProgramOptionsDescription>& options) { options["JAVASCRIPT Options:help-admin"] ("javascript.gc-interval", &_gcInterval, "JavaScript garbage collection interval (each x requests)") ; options["DIRECTORY Options:help-admin"] ("javascript.action-directory", &_actionPath, "path to the JavaScript action directory") ("javascript.modules-path", &_startupModules, "one or more directories separated by (semi-) colons") ("javascript.startup-directory", &_startupPath, "path to the directory containing alternate JavaScript startup scripts") ; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::prepare () { LOGGER_INFO << "using JavaScript modules path '" << _startupModules << "'"; // set up the startup loader if (_startupPath.empty()) { LOGGER_INFO << "using built-in JavaScript startup files"; _startupLoader.defineScript("common/bootstrap/modules.js", JS_common_bootstrap_modules); _startupLoader.defineScript("common/bootstrap/print.js", JS_common_bootstrap_print); _startupLoader.defineScript("common/bootstrap/errors.js", JS_common_bootstrap_errors); _startupLoader.defineScript("server/ahuacatl.js", JS_server_ahuacatl); _startupLoader.defineScript("server/server.js", JS_server_server); } else { LOGGER_INFO << "using JavaScript startup files at '" << _startupPath << "'"; _startupLoader.setDirectory(_startupPath); } // set up action loader if (! _actionPath.empty()) { LOGGER_INFO << "using JavaScript action files at '" << _actionPath << "'"; _actionLoader.setDirectory(_actionPath); } // setup instances _contexts = new V8Context*[_nrInstances]; for (size_t i = 0; i < _nrInstances; ++i) { bool ok = prepareV8Instance(i); if (! ok) { return false; } } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::isStartable () { return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::start () { _gcThread = new V8GcThread(this); _gcThread->start(); return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::isStarted () { return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::beginShutdown () { _stopping = 1; _contextCondition.broadcast(); } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::shutdown () { _contextCondition.broadcast(); usleep(1000); _gcThread->stop(); for (size_t i = 0; i < _nrInstances; ++i) { shutdownV8Instance(i); } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief prepares a V8 instance //////////////////////////////////////////////////////////////////////////////// bool ApplicationV8::prepareV8Instance (size_t i) { static char const* files[] = { "common/bootstrap/modules.js", "common/bootstrap/print.js", "common/bootstrap/errors.js", "server/ahuacatl.js", "server/server.js" }; LOGGER_TRACE << "initialising V8 context #" << i; V8Context* context = _contexts[i] = new V8Context(); // enter a new isolate context->_isolate = v8::Isolate::New(); context->_locker = new v8::Locker(context->_isolate); context->_isolate->Enter(); // create the context context->_context = v8::Context::New(); if (context->_context.IsEmpty()) { LOGGER_FATAL << "cannot initialize V8 engine"; context->_isolate->Exit(); delete context->_locker; return false; } context->_context->Enter(); TRI_InitV8VocBridge(context->_context, _vocbase); TRI_InitV8Queries(context->_context); if (! _actionPath.empty()) { TRI_InitV8Actions(context->_context, this); } TRI_InitV8Conversions(context->_context); TRI_InitV8Utils(context->_context, _startupModules); TRI_InitV8Shell(context->_context); // load all init files for (i = 0; i < sizeof(files) / sizeof(files[0]); ++i) { bool ok = _startupLoader.loadScript(context->_context, files[i]); if (! ok) { LOGGER_FATAL << "cannot load JavaScript utilities from file '" << files[i] << "'"; context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; return false; } } // load all actions if (! _actionPath.empty()) { bool ok = _actionLoader.executeAllScripts(context->_context); if (! ok) { LOGGER_FATAL << "cannot load JavaScript actions from directory '" << _actionLoader.getDirectory() << "'"; context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; return false; } } // and return from the context context->_context->Exit(); context->_isolate->Exit(); delete context->_locker; LOGGER_TRACE << "initialised V8 context #" << i; _freeContexts.push_back(context); return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief shut downs a V8 instances //////////////////////////////////////////////////////////////////////////////// void ApplicationV8::shutdownV8Instance (size_t i) { LOGGER_TRACE << "shutting down V8 context #" << i; V8Context* context = _contexts[i]; context->_locker = new v8::Locker(context->_isolate); context->_isolate->Enter(); context->_context->Enter(); while (!v8::V8::IdleNotification()) { } TRI_v8_global_t* v8g = (TRI_v8_global_t*) context->_isolate->GetData(); if (v8g) { delete v8g; } context->_context->Exit(); context->_context.Dispose(); context->_isolate->Exit(); delete context->_locker; context->_isolate->Dispose(); LOGGER_TRACE << "closed V8 context #" << i; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef GUARD_FORD_HPP #define GUARD_FORD_HPP #include <algorithm> #include <array> #include <cassert> #include <cmath> #include <functional> #include <miopen/each_args.hpp> #include <miopen/returns.hpp> #include <numeric> #include <vector> #ifdef __MINGW32__ #include <mingw.thread.h> #else #include <thread> #endif #include <future> // An improved async, that doesn't block template <class Function> std::future<typename std::result_of<Function()>::type> detach_async(Function&& f) { using result_type = typename std::result_of<Function ()>::type; std::packaged_task<result_type()> task(std::forward<Function>(f)); auto fut = task.get_future(); std::thread(std::move(task)).detach(); return std::move(fut); } struct joinable_thread : std::thread { template <class... Xs> joinable_thread(Xs&&... xs) : std::thread(std::forward<Xs>(xs)...) // NOLINT { } joinable_thread& operator=(joinable_thread&& other) = default; joinable_thread(joinable_thread&& other) = default; ~joinable_thread() { if(this->joinable()) this->join(); } }; struct thread_factory { template <class F> joinable_thread operator()(std::size_t& work, std::size_t n, std::size_t grainsize, F f) const { auto result = joinable_thread([=] { std::size_t start = work; std::size_t last = std::min(n, work + grainsize); for(std::size_t i = start; i < last; i++) { f(i); } }); work += grainsize; return result; } }; template <class F> void par_for_impl(std::size_t n, std::size_t threadsize, F f) { if(threadsize <= 1) { for(std::size_t i = 0; i < n; i++) f(i); } else { std::vector<joinable_thread> threads(threadsize); const std::size_t grainsize = std::ceil(static_cast<double>(n) / threads.size()); std::size_t work = 0; std::generate(threads.begin(), threads.end(), std::bind(thread_factory{}, std::ref(work), n, grainsize, f)); assert(work >= n); } } template <class F> void par_for(std::size_t n, std::size_t min_grain, F f) { const auto threadsize = std::min<std::size_t>(std::thread::hardware_concurrency(), n / min_grain); par_for_impl(n, threadsize, f); } template <class F> void par_for(std::size_t n, F f) { const int min_grain = 8; par_for(n, min_grain, f); } template <class T> struct ford_wrapper { template <class... Ts> auto operator()(Ts... xs) const MIOPEN_RETURNS(std::bind(T{}, std::placeholders::_1, xs...)); }; // Multidimensional for loop struct ford_impl { template <class F> void operator()(F f) const { f(); } template <class F, class T, class... Ts> void operator()(F f, T x, Ts... xs) const { // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55914 for(T i = 0; i < x; i++) { (*this)([&](Ts... is) { f(i, is...); }, xs...); } } }; static constexpr ford_wrapper<ford_impl> ford{}; struct par_ford_impl { template <class F, class... Ts> void operator()(F f, Ts... xs) const { using array_type = std::array<std::size_t, sizeof...(Ts)>; array_type lens = {{static_cast<std::size_t>(xs)...}}; array_type strides; strides.fill(1); std::partial_sum( lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<std::size_t>()); auto size = std::accumulate(lens.begin(), lens.end(), 1, std::multiplies<std::size_t>()); par_for(size, [&](std::size_t i) { array_type indices; std::transform(strides.begin(), strides.end(), lens.begin(), indices.begin(), [&](size_t stride, size_t len) { return (i / stride) % len; }); miopen::unpack(f, indices); }); } }; static constexpr ford_wrapper<par_ford_impl> par_ford{}; #endif <commit_msg>Formatting<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef GUARD_FORD_HPP #define GUARD_FORD_HPP #include <algorithm> #include <array> #include <cassert> #include <cmath> #include <functional> #include <miopen/each_args.hpp> #include <miopen/returns.hpp> #include <numeric> #include <vector> #ifdef __MINGW32__ #include <mingw.thread.h> #else #include <thread> #endif #include <future> // An improved async, that doesn't block template <class Function> std::future<typename std::result_of<Function()>::type> detach_async(Function&& f) { using result_type = typename std::result_of<Function()>::type; std::packaged_task<result_type()> task(std::forward<Function>(f)); auto fut = task.get_future(); std::thread(std::move(task)).detach(); return std::move(fut); } struct joinable_thread : std::thread { template <class... Xs> joinable_thread(Xs&&... xs) : std::thread(std::forward<Xs>(xs)...) // NOLINT { } joinable_thread& operator=(joinable_thread&& other) = default; joinable_thread(joinable_thread&& other) = default; ~joinable_thread() { if(this->joinable()) this->join(); } }; struct thread_factory { template <class F> joinable_thread operator()(std::size_t& work, std::size_t n, std::size_t grainsize, F f) const { auto result = joinable_thread([=] { std::size_t start = work; std::size_t last = std::min(n, work + grainsize); for(std::size_t i = start; i < last; i++) { f(i); } }); work += grainsize; return result; } }; template <class F> void par_for_impl(std::size_t n, std::size_t threadsize, F f) { if(threadsize <= 1) { for(std::size_t i = 0; i < n; i++) f(i); } else { std::vector<joinable_thread> threads(threadsize); const std::size_t grainsize = std::ceil(static_cast<double>(n) / threads.size()); std::size_t work = 0; std::generate(threads.begin(), threads.end(), std::bind(thread_factory{}, std::ref(work), n, grainsize, f)); assert(work >= n); } } template <class F> void par_for(std::size_t n, std::size_t min_grain, F f) { const auto threadsize = std::min<std::size_t>(std::thread::hardware_concurrency(), n / min_grain); par_for_impl(n, threadsize, f); } template <class F> void par_for(std::size_t n, F f) { const int min_grain = 8; par_for(n, min_grain, f); } template <class T> struct ford_wrapper { template <class... Ts> auto operator()(Ts... xs) const MIOPEN_RETURNS(std::bind(T{}, std::placeholders::_1, xs...)); }; // Multidimensional for loop struct ford_impl { template <class F> void operator()(F f) const { f(); } template <class F, class T, class... Ts> void operator()(F f, T x, Ts... xs) const { // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55914 for(T i = 0; i < x; i++) { (*this)([&](Ts... is) { f(i, is...); }, xs...); } } }; static constexpr ford_wrapper<ford_impl> ford{}; struct par_ford_impl { template <class F, class... Ts> void operator()(F f, Ts... xs) const { using array_type = std::array<std::size_t, sizeof...(Ts)>; array_type lens = {{static_cast<std::size_t>(xs)...}}; array_type strides; strides.fill(1); std::partial_sum( lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<std::size_t>()); auto size = std::accumulate(lens.begin(), lens.end(), 1, std::multiplies<std::size_t>()); par_for(size, [&](std::size_t i) { array_type indices; std::transform(strides.begin(), strides.end(), lens.begin(), indices.begin(), [&](size_t stride, size_t len) { return (i / stride) % len; }); miopen::unpack(f, indices); }); } }; static constexpr ford_wrapper<par_ford_impl> par_ford{}; #endif <|endoftext|>
<commit_before>#include "tcp_server.h" #include <iostream> #include <regex> #include <boost/program_options.hpp> #include <apr_errno.h> namespace po=boost::program_options; using namespace Akumuli; static void static_logger(int tag, const char * msg) { static Logger logger = Logger("Main", 32); switch(tag) { case AKU_LOG_ERROR: logger.error() << msg; break; case AKU_LOG_INFO: logger.info() << msg; break; case AKU_LOG_TRACE: logger.trace() << msg; break; } } void create_db(const char* name, const char* path, int32_t nvolumes, uint32_t compression_threshold, uint64_t window_size, uint32_t max_cache_size) { auto status = aku_create_database(name, path, path, nvolumes, compression_threshold, window_size, max_cache_size, &static_logger); if (status != AKU_SUCCESS) { std::cout << "Error creating database" << std::endl; char buffer[1024]; apr_strerror(status, buffer, 1024); std::cout << buffer << std::endl; } else { std::cout << "Database created" << std::endl; std::cout << "- path: " << path << std::endl; std::cout << "- name: " << name << std::endl; } } void run_server(std::string path) { auto connection = std::make_shared<AkumuliConnection>(path.c_str(), false, AkumuliConnection::MaxDurability); TcpServer server(connection, 4); server.start(); server.wait(); server.stop(); } uint64_t str2unixtime(std::string t) { std::regex regex("(\\d)+\\s?(min|sec|s|m)"); std::smatch sm; std::regex_match(t, sm, regex); if (sm.size() != 2) { throw std::runtime_error("Bad window size"); } std::string snum = sm[0].str(); auto num = boost::lexical_cast<uint64_t>(snum); if (sm[1].str() == "m" || sm[1].str() == "min") { return num * 60; } return num; } int main(int argc, char** argv) { po::options_description desc("Akumuli options"); desc.add_options() ("help", "Produce help message") ("path", po::value<std::string>(), "Path to database files") ("create", "Create database") ("name", po::value<std::string>(), "Database name (create)") ("nvolumes", po::value<int32_t>(), "Number of volumes to create (create)") ("window", po::value<std::string>(), "Window size (create)") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 0; } if (!vm.count("path")) { std::cout << desc << std::endl; return -1; } std::string path = vm["path"].as<std::string>(); if (vm.count("create") == 0) { run_server(path); } else { if (vm.count("nvolumes") == 0 || vm.count("name") == 0 || vm.count("window") == 0) { std::cout << desc << std::endl; return -1; } std::string name = vm["name"].as<std::string>(); int32_t nvol = vm["nvolumes"].as<int32_t>(); std::string window = vm["window"].as<std::string>(); create_db(name.c_str(), path.c_str(), nvol, 10000, str2unixtime(window), 100000); // TODO: use correct numbers } return 0; } <commit_msg>Small fixes to akumulid/main<commit_after>#include "tcp_server.h" #include <iostream> #include <regex> #include <boost/program_options.hpp> #include <apr_errno.h> namespace po=boost::program_options; using namespace Akumuli; static void static_logger(int tag, const char * msg) { static Logger logger = Logger("Main", 32); switch(tag) { case AKU_LOG_ERROR: logger.error() << msg; break; case AKU_LOG_INFO: logger.info() << msg; break; case AKU_LOG_TRACE: logger.trace() << msg; break; } } void create_db(const char* name, const char* path, int32_t nvolumes, uint32_t compression_threshold, uint64_t window_size, uint32_t max_cache_size) { auto status = aku_create_database(name, path, path, nvolumes, compression_threshold, window_size, max_cache_size, &static_logger); if (status != AKU_SUCCESS) { std::cout << "Error creating database" << std::endl; char buffer[1024]; apr_strerror(status, buffer, 1024); std::cout << buffer << std::endl; } else { std::cout << "Database created" << std::endl; std::cout << "- path: " << path << std::endl; std::cout << "- name: " << name << std::endl; } } void run_server(std::string path) { auto connection = std::make_shared<AkumuliConnection>(path.c_str(), false, AkumuliConnection::MaxDurability); auto server = std::make_shared<TcpServer>(connection, 4); server->start(); server->wait(); server->stop(); } uint64_t str2unixtime(std::string t) { std::regex regex("(\\d)+\\s?(min|sec|s|m)"); std::smatch sm; std::regex_match(t, sm, regex); if (sm.size() != 2) { throw std::runtime_error("Bad window size"); } std::string snum = sm[0].str(); auto num = boost::lexical_cast<uint64_t>(snum); if (sm[1].str() == "m" || sm[1].str() == "min") { return num * 60; } return num; } int main(int argc, char** argv) { aku_initialize(nullptr); po::options_description desc("Akumuli options"); desc.add_options() ("help", "Produce help message") ("path", po::value<std::string>(), "Path to database files") ("create", "Create database") ("name", po::value<std::string>(), "Database name (create)") ("nvolumes", po::value<int32_t>(), "Number of volumes to create (create)") ("window", po::value<std::string>(), "Window size (create)") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 0; } if (!vm.count("path")) { std::cout << desc << std::endl; return -1; } std::string path = vm["path"].as<std::string>(); if (vm.count("create") == 0) { run_server(path); } else { if (vm.count("nvolumes") == 0 || vm.count("name") == 0 || vm.count("window") == 0) { std::cout << desc << std::endl; return -1; } std::string name = vm["name"].as<std::string>(); int32_t nvol = vm["nvolumes"].as<int32_t>(); std::string window = vm["window"].as<std::string>(); create_db(name.c_str(), path.c_str(), nvol, 10000, str2unixtime(window), 100000); // TODO: use correct numbers } return 0; } <|endoftext|>
<commit_before>#include <gmi_mesh.h> #include <ma.h> #include <apf.h> #include <apfMesh2.h> #include <apfMDS.h> #include <PCU.h> #include <parma.h> #include <cassert> namespace { const char* modelFile = 0; const char* meshFile = 0; void freeMesh(apf::Mesh* m) { m->destroyNative(); apf::destroyMesh(m); } void getConfig(int argc, char** argv) { assert(argc==4); modelFile = argv[1]; meshFile = argv[2]; } apf::MeshTag* applyUnitWeight(apf::Mesh* m) { apf::MeshTag* wtag = m->createDoubleTag("ghostUnitWeight",1); apf::MeshEntity* e; for(int d=0; d <= m->getDimension(); d++) { apf::MeshIterator* itr = m->begin(d); double w = 1; while( (e = m->iterate(itr)) ) m->setDoubleTag(e, wtag, &w); m->end(itr); } return wtag; } void runParma(apf::Mesh* m) { apf::MeshTag* weights = applyUnitWeight(m); const int layers = 1; const double stepFactor = 0.5; const int verbosity = 2; apf::Balancer* ghost = Parma_MakeGhostDiffuser(m, layers, stepFactor, verbosity); ghost->balance(weights, 1.05); m->destroyTag(weights); delete ghost; } } int main(int argc, char** argv) { int provided; MPI_Init_thread(&argc,&argv,MPI_THREAD_MULTIPLE,&provided); assert(provided==MPI_THREAD_MULTIPLE); PCU_Comm_Init(); PCU_Debug_Open(); gmi_register_mesh(); getConfig(argc,argv); apf::Mesh2* m = apf::loadMdsMesh(modelFile,meshFile); runParma(m); apf::writeVtkFiles(argv[3],m); freeMesh(m); PCU_Comm_Free(); MPI_Finalize(); } <commit_msg>fun3d weights<commit_after>#include <gmi_mesh.h> #include <apf.h> #include <apfMesh2.h> #include <apfMDS.h> #include <PCU.h> #include <parma.h> #include <cassert> namespace { const char* modelFile = 0; const char* meshFile = 0; void freeMesh(apf::Mesh* m) { m->destroyNative(); apf::destroyMesh(m); } void getConfig(int argc, char** argv) { assert(argc==4); modelFile = argv[1]; meshFile = argv[2]; } double getFun3dElmW(int type) { assert(type >= apf::Mesh::TET && type <= apf::Mesh::PYRAMID); const double tetw = 1.0; const double pyrw = 6.8; const double przw = 7.5; const double hexw = 13.8; const double elmWeights[4] = {tetw, hexw, przw, pyrw}; const int offset = apf::Mesh::TET; return elmWeights[type-offset]; } apf::MeshTag* applyFun3dWeight(apf::Mesh* m) { assert(3 == m->getDimension()); apf::MeshTag* wtag = m->createDoubleTag("ghostWeight",1); apf::MeshEntity* e; for(int d=0; d < m->getDimension(); d++) { apf::MeshIterator* itr = m->begin(d); double w = 1; while( (e = m->iterate(itr)) ) m->setDoubleTag(e, wtag, &w); m->end(itr); } apf::MeshIterator* itr = m->begin(3); while( (e = m->iterate(itr)) ) { double w = getFun3dElmW(m->getType(e)); m->setDoubleTag(e, wtag, &w); } m->end(itr); return wtag; } void runParma(apf::Mesh* m, apf::MeshTag* weights) { const int layers = 1; const double stepFactor = 0.5; const int verbosity = 2; apf::Balancer* ghost = Parma_MakeGhostDiffuser(m, layers, stepFactor, verbosity); ghost->balance(weights, 1.05); delete ghost; } } int main(int argc, char** argv) { int provided; MPI_Init_thread(&argc,&argv,MPI_THREAD_MULTIPLE,&provided); assert(provided==MPI_THREAD_MULTIPLE); PCU_Comm_Init(); PCU_Debug_Open(); gmi_register_mesh(); getConfig(argc,argv); apf::Mesh2* m = apf::loadMdsMesh(modelFile,meshFile); apf::MeshTag* weights = applyFun3dWeight(m); runParma(m,weights); m->destroyTag(weights); apf::writeVtkFiles(argv[3],m); freeMesh(m); PCU_Comm_Free(); MPI_Finalize(); } <|endoftext|>
<commit_before> /* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkPathUtils.h" #include "SkRandom.h" #include "SkTime.h" #define NUM_IT 100000 #define ON 0xFF000000 // black pixel #define OFF 0x00000000 // transparent pixel class SkBitmap; //this function is redefined for sample, test, and bench. is there anywhere // I can put it to avoid code duplcation? static void fillRandomBits( int chars, char* bits ){ SkTime time; SkMWCRandom rand = SkMWCRandom( time.GetMSecs() ); for (int i = 0; i < chars; ++i){ bits[i] = rand.nextU(); } } //also defined within PathUtils.cpp, but not in scope here. Anyway to call it // without re-defining it? static int getBit( const char* buffer, int x ) { int byte = x >> 3; int bit = x & 7; return buffer[byte] & (1 << bit); } static void bin2SkBitmap(const char* bin_bmp, SkBitmap* sk_bmp, int h, int w, int stride){ //init the SkBitmap sk_bmp->setConfig(SkBitmap::kARGB_8888_Config, w, h); sk_bmp->allocPixels(); for (int y = 0; y < h; ++y) { // for every row const char* curLine = &bin_bmp[y * stride]; for (int x = 0; x < w; ++x) {// for every pixel if (getBit(curLine, x)) { *sk_bmp->getAddr32(x,y) = ON; } else { *sk_bmp->getAddr32(x,y) = OFF; } } } } static bool test_bmp(skiatest::Reporter* reporter, const SkBitmap* bmp1, const SkBitmap* bmp2, int h, int w) { for (int y = 0; y < h; ++y) { // loop through all pixels for (int x = 0; x < w; ++x) { REPORTER_ASSERT( reporter, *bmp1->getAddr32(x,y) == *bmp1->getAddr32(x,y) ); } } return true; } static void test_path_eq(skiatest::Reporter* reporter, const SkPath* path, const SkBitmap* truth, int h, int w){ // make paint SkPaint bmpPaint; bmpPaint.setAntiAlias(true); // Black paint for bitmap bmpPaint.setStyle(SkPaint::kFill_Style); bmpPaint.setColor(SK_ColorBLACK); // make bmp SkBitmap bmp; bmp.setConfig(SkBitmap::kARGB_8888_Config, w, h); bmp.allocPixels(); SkCanvas(bmp).drawPath(*path, bmpPaint); // test bmp test_bmp(reporter, &bmp, truth, h, w); } static void test_path(skiatest::Reporter* reporter, const SkBitmap* truth, const char* bin_bmp, int h, int w, int stride){ // make path SkPath path; SkPathUtils::BitsToPath_Path(&path, bin_bmp, h, w, stride); //test for correctness test_path_eq(reporter, &path, truth, h, w); } static void test_region(skiatest::Reporter* reporter, const SkBitmap* truth, const char* bin_bmp, int h, int w, int stride){ //generate bitmap SkPath path; SkPathUtils::BitsToPath_Region(&path, bin_bmp, h, w, stride); //test for correctness test_path_eq(reporter, &path, truth, h, w); } static void TestPathUtils(skiatest::Reporter* reporter) { const int w[4] = {4, 8, 12, 16}; int h = 8, stride = 4; char bits[ h * stride ]; static char* bin_bmp = &bits[0]; //loop to run randomized test lots of times for (int it = 0; it < NUM_IT; ++it) { // generate a random binary bitmap fillRandomBits( h * stride, bin_bmp); // generate random bitmap // for each bitmap width, use subset of binary bitmap for (int i = 0; i < 4; ++i) { // generate truth bitmap SkBitmap bmpTruth; bin2SkBitmap(bin_bmp, &bmpTruth, h, w[i], stride); test_path(reporter, &bmpTruth, bin_bmp, h, w[i], stride); test_region(reporter, &bmpTruth, bin_bmp, h, w[i], stride); } } } #include "TestClassDef.h" DEFINE_TESTCLASS("PathUtils", PathUtils, TestPathUtils) <commit_msg>Fixed non-constant array size in test.<commit_after> /* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkPathUtils.h" #include "SkRandom.h" #include "SkTime.h" #define NUM_IT 1000 #define ON 0xFF000000 // black pixel #define OFF 0x00000000 // transparent pixel class SkBitmap; //this function is redefined for sample, test, and bench. is there anywhere // I can put it to avoid code duplcation? static void fillRandomBits( int chars, char* bits ){ SkTime time; SkMWCRandom rand = SkMWCRandom( time.GetMSecs() ); for (int i = 0; i < chars; ++i){ bits[i] = rand.nextU(); } } //also defined within PathUtils.cpp, but not in scope here. Anyway to call it // without re-defining it? static int getBit( const char* buffer, int x ) { int byte = x >> 3; int bit = x & 7; return buffer[byte] & (1 << bit); } static void bin2SkBitmap(const char* bin_bmp, SkBitmap* sk_bmp, int h, int w, int stride){ //init the SkBitmap sk_bmp->setConfig(SkBitmap::kARGB_8888_Config, w, h); sk_bmp->allocPixels(); for (int y = 0; y < h; ++y) { // for every row const char* curLine = &bin_bmp[y * stride]; for (int x = 0; x < w; ++x) {// for every pixel if (getBit(curLine, x)) { *sk_bmp->getAddr32(x,y) = ON; } else { *sk_bmp->getAddr32(x,y) = OFF; } } } } static bool test_bmp(skiatest::Reporter* reporter, const SkBitmap* bmp1, const SkBitmap* bmp2, int h, int w) { for (int y = 0; y < h; ++y) { // loop through all pixels for (int x = 0; x < w; ++x) { REPORTER_ASSERT( reporter, *bmp1->getAddr32(x,y) == *bmp1->getAddr32(x,y) ); } } return true; } static void test_path_eq(skiatest::Reporter* reporter, const SkPath* path, const SkBitmap* truth, int h, int w){ // make paint SkPaint bmpPaint; bmpPaint.setAntiAlias(true); // Black paint for bitmap bmpPaint.setStyle(SkPaint::kFill_Style); bmpPaint.setColor(SK_ColorBLACK); // make bmp SkBitmap bmp; bmp.setConfig(SkBitmap::kARGB_8888_Config, w, h); bmp.allocPixels(); SkCanvas(bmp).drawPath(*path, bmpPaint); // test bmp test_bmp(reporter, &bmp, truth, h, w); } static void test_path(skiatest::Reporter* reporter, const SkBitmap* truth, const char* bin_bmp, int h, int w, int stride){ // make path SkPath path; SkPathUtils::BitsToPath_Path(&path, bin_bmp, h, w, stride); //test for correctness test_path_eq(reporter, &path, truth, h, w); } static void test_region(skiatest::Reporter* reporter, const SkBitmap* truth, const char* bin_bmp, int h, int w, int stride){ //generate bitmap SkPath path; SkPathUtils::BitsToPath_Region(&path, bin_bmp, h, w, stride); //test for correctness test_path_eq(reporter, &path, truth, h, w); } #define W_tests 4 static void TestPathUtils(skiatest::Reporter* reporter) { const int w[W_tests] = {4, 8, 12, 16}; const int h = 8, stride = 4; char bits[ h * stride ]; static char* bin_bmp = &bits[0]; //loop to run randomized test lots of times for (int it = 0; it < NUM_IT; ++it) { // generate a random binary bitmap fillRandomBits( h * stride, bin_bmp); // generate random bitmap // for each bitmap width, use subset of binary bitmap for (int i = 0; i < W_tests; ++i) { // generate truth bitmap SkBitmap bmpTruth; bin2SkBitmap(bin_bmp, &bmpTruth, h, w[i], stride); test_path(reporter, &bmpTruth, bin_bmp, h, w[i], stride); test_region(reporter, &bmpTruth, bin_bmp, h, w[i], stride); } } } #include "TestClassDef.h" DEFINE_TESTCLASS("PathUtils", PathUtils, TestPathUtils) <|endoftext|>
<commit_before>/** * Mergesort * ========= * * Mergesort an array on the heap. */ #include <iostream> #include <vector> void _merge(int low, int mid, int high, std::vector<int> *uv, std::vector<int> *tv) { int i, j, n; for (i = low, j = mid + 1, n = low; i <= mid && j <= high; ++n) { if ((*uv)[i] <= (*uv)[j]) (*tv)[n] = (*uv)[i++]; else (*tv)[n] = (*uv)[j++]; } while (i <= mid) (*tv)[n++] = (*uv)[i++]; while (j <= high) (*tv)[n++] = (*uv)[j++]; for (n = low; n <= high; ++n) (*uv)[n] = (*tv)[n]; } void _sort(int low, int high, std::vector<int> *uv, std::vector<int> *tv) { int mid; if (low < high) { mid = (low + high) / 2; _sort(low, mid, uv, tv); _sort(mid + 1, high, uv, tv); _merge(low, mid, high, uv, tv); } } void mergesort(std::vector<int> *v) { int low = 0; int high = v->size() - 1; std::vector<int> *tv = new std::vector<int>(v->size()); _sort(low, high, v, tv); delete tv; } int main(int argc, const char *argv[]) { std::vector<int> *v = new std::vector<int>{0, 9, 8, 7, 6, 5, 4, 3, 2, 1}; mergesort(v); std::cout << "[ "; for (auto r : *v) std::cout << r << ", "; std::cout << "]" << std::endl; return 0; } <commit_msg>updated mergesort: edge cases<commit_after>/** * Mergesort * ========= * * Mergesort an vector on the heap. */ #include <iostream> #include <vector> void _merge(int low, int mid, int high, std::vector<int> *uv, std::vector<int> *tv) { int i, j, n; for (i = low, j = mid + 1, n = low; i <= mid && j <= high; ++n) { if ((*uv)[i] <= (*uv)[j]) (*tv)[n] = (*uv)[i++]; else (*tv)[n] = (*uv)[j++]; } while (i <= mid) (*tv)[n++] = (*uv)[i++]; while (j <= high) (*tv)[n++] = (*uv)[j++]; for (n = low; n <= high; ++n) (*uv)[n] = (*tv)[n]; } void _sort(int low, int high, std::vector<int> *uv, std::vector<int> *tv) { int mid; if (low < high) { mid = (low + high) / 2; _sort(low, mid, uv, tv); _sort(mid + 1, high, uv, tv); _merge(low, mid, high, uv, tv); } } void mergesort(std::vector<int> *v) { if (v == nullptr || v->size() == 0) return; int low = 0; int high = v->size() - 1; std::vector<int> *tv = new std::vector<int>(v->size()); _sort(low, high, v, tv); delete tv; } int main(int argc, const char *argv[]) { std::vector<int> *v = new std::vector<int>{0, 9, 8, 7, 6, 5, 4, 3, 2, 1}; mergesort(v); std::cout << "[ "; for (auto r : *v) std::cout << r << ", "; std::cout << "]" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2013-2016 Daniel Nicoletti <dantti12@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "clearsilver_p.h" #include "context.h" #include "action.h" #include "response.h" #include <QString> #include <QFile> #include <QtCore/QLoggingCategory> Q_LOGGING_CATEGORY(CUTELYST_CLEARSILVER, "cutelyst.clearsilver") using namespace Cutelyst; ClearSilver::ClearSilver(QObject *parent) : View(parent) , d_ptr(new ClearSilverPrivate) { } ClearSilver::~ClearSilver() { delete d_ptr; } QStringList ClearSilver::includePaths() const { Q_D(const ClearSilver); return d->includePaths; } void ClearSilver::setIncludePaths(const QStringList &paths) { Q_D(ClearSilver); d->includePaths = paths; } QString ClearSilver::templateExtension() const { Q_D(const ClearSilver); return d->extension; } void ClearSilver::setTemplateExtension(const QString &extension) { Q_D(ClearSilver); d->extension = extension; } QString ClearSilver::wrapper() const { Q_D(const ClearSilver); return d->wrapper; } void ClearSilver::setWrapper(const QString &name) { Q_D(ClearSilver); d->wrapper = name; } NEOERR* cutelyst_render(void *user, char *data) { QByteArray *body = static_cast<QByteArray*>(user); if (body) { body->append(data); } // qDebug() << "_render" << body << data; return 0; } QByteArray ClearSilver::render(Context *c) const { Q_D(const ClearSilver); const QVariantHash &stash = c->stash(); QString templateFile = stash.value(QStringLiteral("template")).toString(); if (templateFile.isEmpty()) { if (c->action() && !c->action()->reverse().isEmpty()) { templateFile = c->action()->reverse() + d->extension; } if (templateFile.isEmpty()) { c->error(QStringLiteral("Cannot render template, template name or template stash key not defined")); return QByteArray(); } } qCDebug(CUTELYST_CLEARSILVER) << "Rendering template" <<templateFile; QByteArray output; if (!d->render(c, templateFile, stash, output)) { return QByteArray(); } if (!d->wrapper.isEmpty()) { QString wrapperFile = d->wrapper; QVariantHash data = stash; data.insert(QStringLiteral("content"), output); if (!d->render(c, wrapperFile, data, output)) { return QByteArray(); } } return output; } NEOERR* findFile(void *c, HDF *hdf, const char *filename, char **contents) { const ClearSilverPrivate *priv = static_cast<ClearSilverPrivate*>(c); if (!priv) { return nerr_raise(NERR_NOMEM, "Cound not cast ClearSilverPrivate"); } for (const QString &includePath : priv->includePaths) { QFile file(includePath + QLatin1Char('/') + QString::fromLatin1(filename)); if (file.exists()) { if (!file.open(QFile::ReadOnly)) { return nerr_raise(NERR_IO, "Cound not open file: %s", file.errorString().toLatin1().data()); } *contents = qstrdup(file.readAll().constData()); qCDebug(CUTELYST_CLEARSILVER) << "Rendering template:" << file.fileName(); return 0; } } return nerr_raise(NERR_NOT_FOUND, "Cound not find file: %s", filename); } bool ClearSilverPrivate::render(Context *c, const QString &filename, const QVariantHash &stash, QByteArray &output) const { HDF *hdf = hdfForStash(c, stash); CSPARSE *cs; NEOERR *error; error = cs_init(&cs, hdf); if (error) { STRING *msg = new STRING; string_init(msg); nerr_error_traceback(error, msg); QString errorMsg; errorMsg = QStringLiteral("Failed to init ClearSilver:\n+1").arg(QString::fromLatin1(msg->buf, msg->len)); renderError(c, errorMsg); hdf_destroy(&hdf); nerr_ignore(&error); return false; } cs_register_fileload(cs, const_cast<ClearSilverPrivate*>(this), findFile); error = cs_parse_file(cs, filename.toLatin1().data()); if (error) { STRING *msg = new STRING; string_init(msg); nerr_error_traceback(error, msg); QString errorMsg; errorMsg = QStringLiteral("Failed to parse template file: +1\n+2").arg(filename, QString::fromLatin1(msg->buf, msg->len)); renderError(c, errorMsg); nerr_log_error(error); hdf_destroy(&hdf); nerr_ignore(&error); return false; } cs_render(cs, &output, cutelyst_render); cs_destroy(&cs); hdf_destroy(&hdf); return true; } void ClearSilverPrivate::renderError(Context *c, const QString &error) const { c->error(error); c->res()->body() = error.toUtf8(); } HDF *ClearSilverPrivate::hdfForStash(Context *c, const QVariantHash &stash) const { HDF *hdf = 0; hdf_init(&hdf); serializeHash(hdf, stash); const QMetaObject *meta = c->metaObject(); for (int i = 0; i < meta->propertyCount(); ++i) { QMetaProperty prop = meta->property(i); QString name = QLatin1String("c.") + QString::fromLatin1(prop.name()); QVariant value = prop.read(c); serializeVariant(hdf, value, name); } return hdf; } void ClearSilverPrivate::serializeHash(HDF *hdf, const QVariantHash &hash, const QString &prefix) const { QString _prefix; if (!prefix.isEmpty()) { _prefix = prefix + QLatin1Char('.'); } auto it = hash.constBegin(); while (it != hash.constEnd()) { serializeVariant(hdf, it.value(), _prefix + it.key()); ++it; } } void ClearSilverPrivate::serializeMap(HDF *hdf, const QVariantMap &map, const QString &prefix) const { QString _prefix; if (!prefix.isEmpty()) { _prefix = prefix + QLatin1Char('.'); } auto it = map.constBegin(); while (it != map.constEnd()) { serializeVariant(hdf, it.value(), _prefix + it.key()); ++it; } } void ClearSilverPrivate::serializeVariant(HDF *hdf, const QVariant &value, const QString &key) const { // qDebug() << key; switch (value.type()) { case QMetaType::QString: hdf_set_value(hdf, key.toLatin1().data(), value.toString().toLatin1().data()); break; case QMetaType::Int: hdf_set_int_value(hdf, key.toLatin1().data(), value.toInt()); break; case QMetaType::QVariantHash: serializeHash(hdf, value.toHash(), key); break; case QMetaType::QVariantMap: serializeMap(hdf, value.toMap(), key); break; default: if (value.canConvert(QMetaType::QString)) { hdf_set_value(hdf, key.toLatin1().data(), value.toString().toLatin1().data()); } break; } } #include "moc_clearsilver.cpp" <commit_msg>Fix clearsilver memleak<commit_after>/* * Copyright (C) 2013-2016 Daniel Nicoletti <dantti12@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "clearsilver_p.h" #include "context.h" #include "action.h" #include "response.h" #include <QString> #include <QFile> #include <QtCore/QLoggingCategory> Q_LOGGING_CATEGORY(CUTELYST_CLEARSILVER, "cutelyst.clearsilver") using namespace Cutelyst; ClearSilver::ClearSilver(QObject *parent) : View(parent) , d_ptr(new ClearSilverPrivate) { } ClearSilver::~ClearSilver() { delete d_ptr; } QStringList ClearSilver::includePaths() const { Q_D(const ClearSilver); return d->includePaths; } void ClearSilver::setIncludePaths(const QStringList &paths) { Q_D(ClearSilver); d->includePaths = paths; } QString ClearSilver::templateExtension() const { Q_D(const ClearSilver); return d->extension; } void ClearSilver::setTemplateExtension(const QString &extension) { Q_D(ClearSilver); d->extension = extension; } QString ClearSilver::wrapper() const { Q_D(const ClearSilver); return d->wrapper; } void ClearSilver::setWrapper(const QString &name) { Q_D(ClearSilver); d->wrapper = name; } NEOERR* cutelyst_render(void *user, char *data) { QByteArray *body = static_cast<QByteArray*>(user); if (body) { body->append(data); } // qDebug() << "_render" << body << data; return 0; } QByteArray ClearSilver::render(Context *c) const { Q_D(const ClearSilver); const QVariantHash &stash = c->stash(); QString templateFile = stash.value(QStringLiteral("template")).toString(); if (templateFile.isEmpty()) { if (c->action() && !c->action()->reverse().isEmpty()) { templateFile = c->action()->reverse() + d->extension; } if (templateFile.isEmpty()) { c->error(QStringLiteral("Cannot render template, template name or template stash key not defined")); return QByteArray(); } } qCDebug(CUTELYST_CLEARSILVER) << "Rendering template" <<templateFile; QByteArray output; if (!d->render(c, templateFile, stash, output)) { return QByteArray(); } if (!d->wrapper.isEmpty()) { QString wrapperFile = d->wrapper; QVariantHash data = stash; data.insert(QStringLiteral("content"), output); if (!d->render(c, wrapperFile, data, output)) { return QByteArray(); } } return output; } NEOERR* findFile(void *c, HDF *hdf, const char *filename, char **contents) { const ClearSilverPrivate *priv = static_cast<ClearSilverPrivate*>(c); if (!priv) { return nerr_raise(NERR_NOMEM, "Cound not cast ClearSilverPrivate"); } for (const QString &includePath : priv->includePaths) { QFile file(includePath + QLatin1Char('/') + QString::fromLatin1(filename)); if (file.exists()) { if (!file.open(QFile::ReadOnly)) { return nerr_raise(NERR_IO, "Cound not open file: %s", file.errorString().toLatin1().data()); } *contents = qstrdup(file.readAll().constData()); qCDebug(CUTELYST_CLEARSILVER) << "Rendering template:" << file.fileName(); return 0; } } return nerr_raise(NERR_NOT_FOUND, "Cound not find file: %s", filename); } bool ClearSilverPrivate::render(Context *c, const QString &filename, const QVariantHash &stash, QByteArray &output) const { HDF *hdf = hdfForStash(c, stash); CSPARSE *cs; NEOERR *error; error = cs_init(&cs, hdf); if (error) { STRING msg; string_init(&msg); nerr_error_traceback(error, &msg); QString errorMsg; errorMsg = QStringLiteral("Failed to init ClearSilver:\n+1").arg(QString::fromLatin1(msg.buf, msg.len)); renderError(c, errorMsg); string_clear(&msg); hdf_destroy(&hdf); nerr_ignore(&error); return false; } cs_register_fileload(cs, const_cast<ClearSilverPrivate*>(this), findFile); error = cs_parse_file(cs, filename.toLatin1().data()); if (error) { STRING msg; string_init(&msg); nerr_error_traceback(error, &msg); QString errorMsg; errorMsg = QStringLiteral("Failed to parse template file: +1\n+2").arg(filename, QString::fromLatin1(msg.buf, msg.len)); renderError(c, errorMsg); nerr_log_error(error); string_clear(&msg); hdf_destroy(&hdf); nerr_ignore(&error); return false; } cs_render(cs, &output, cutelyst_render); cs_destroy(&cs); hdf_destroy(&hdf); return true; } void ClearSilverPrivate::renderError(Context *c, const QString &error) const { c->error(error); c->res()->body() = error.toUtf8(); } HDF *ClearSilverPrivate::hdfForStash(Context *c, const QVariantHash &stash) const { HDF *hdf = 0; hdf_init(&hdf); serializeHash(hdf, stash); const QMetaObject *meta = c->metaObject(); for (int i = 0; i < meta->propertyCount(); ++i) { QMetaProperty prop = meta->property(i); QString name = QLatin1String("c.") + QString::fromLatin1(prop.name()); QVariant value = prop.read(c); serializeVariant(hdf, value, name); } return hdf; } void ClearSilverPrivate::serializeHash(HDF *hdf, const QVariantHash &hash, const QString &prefix) const { QString _prefix; if (!prefix.isEmpty()) { _prefix = prefix + QLatin1Char('.'); } auto it = hash.constBegin(); while (it != hash.constEnd()) { serializeVariant(hdf, it.value(), _prefix + it.key()); ++it; } } void ClearSilverPrivate::serializeMap(HDF *hdf, const QVariantMap &map, const QString &prefix) const { QString _prefix; if (!prefix.isEmpty()) { _prefix = prefix + QLatin1Char('.'); } auto it = map.constBegin(); while (it != map.constEnd()) { serializeVariant(hdf, it.value(), _prefix + it.key()); ++it; } } void ClearSilverPrivate::serializeVariant(HDF *hdf, const QVariant &value, const QString &key) const { // qDebug() << key; switch (value.type()) { case QMetaType::QString: hdf_set_value(hdf, key.toLatin1().data(), value.toString().toLatin1().data()); break; case QMetaType::Int: hdf_set_int_value(hdf, key.toLatin1().data(), value.toInt()); break; case QMetaType::QVariantHash: serializeHash(hdf, value.toHash(), key); break; case QMetaType::QVariantMap: serializeMap(hdf, value.toMap(), key); break; default: if (value.canConvert(QMetaType::QString)) { hdf_set_value(hdf, key.toLatin1().data(), value.toString().toLatin1().data()); } break; } } #include "moc_clearsilver.cpp" <|endoftext|>
<commit_before>#ifndef ALEPH_TOPOLOGY_CLIQUE_GRAPH_HH__ #define ALEPH_TOPOLOGY_CLIQUE_GRAPH_HH__ #include "topology/SimplicialComplex.hh" #include <list> #include <map> #include <stdexcept> #include <vector> namespace aleph { namespace topology { /** Given a simplicial complex, extracts its corresponding clique graph. The clique graph is defined as the graph in which each node corresponds to a k-simplex and an edge connects two nodes if there is a $(k-1)$-face that connects the two simplices. Note that the graph is represented as a simplicial complex. It makes any other operations easier. */ template <class Simplex> SimplicialComplex<Simplex> getCliqueGraph( const SimplicialComplex<Simplex>& K, unsigned k ) { // Maps k-simplices to their corresponding index in the filtration order of // the simplicial complex. This simplifies the creation of edges. std::map<Simplex, std::size_t> simplexMap; // Stores the co-faces of (k-1)-dimensional simplices. This is required for // the edge creation. Whenever two (or more) k-simplices appear in this map // they will be connected by an edge. std::map<Simplex, std::vector<std::size_t> > cofaceMap; for( auto itPair = K.range(k); itPair.first != itPair.second; ++itPair.first ) simplexMap[ *itPair.first ] = K.index( *itPair.first ); for( auto&& pair : simplexMap ) { auto&& simplex = pair.first; auto&& index = pair.second; // TODO: Is the number of co-faces bounded? If so, I could reserve // sufficient memory in the map. for( auto itFace = simplex.begin_boundary(); itFace != simplex.end_boundary(); ++itFace ) cofaceMap[ *itFace ].push_back( index ); } // Create vertices --------------------------------------------------- std::vector<Simplex> vertices; vertices.reserve( simplexMap.size() ); using VertexType = typename Simplex::VertexType; for( auto&& pair : simplexMap ) { auto&& simplex = pair.first; auto&& index = pair.second; vertices.push_back( Simplex( VertexType(index), simplex.data() ) ); } // Create edges ------------------------------------------------------ // Since the number of edges is unknown beforehand, it makes sense to use a // list rather than a vector here. Else, the allocation of larger swaths of // memory will be problematic. std::list<Simplex> edges; for( auto&& pair : cofaceMap ) { auto&& indices = pair.second; if( indices.size() >= 2 ) { for( std::size_t i = 0; i < indices.size(); i++ ) { auto uIndex = indices[i]; for( std::size_t j = i+1; j < indices.size(); j++ ) { auto vIndex = indices[j]; // TODO: What happens if the indices are invalid? Do I need to // prepare for this situation explicitly? auto&& s = K.at( uIndex ); auto&& t = K.at( vIndex ); // TODO: Does it make sense to make this configurable? As of now, I // am restricting the weights to the usual maximum filtration, i.e. // I am assuming a growth process here. auto data = std::max( s.data(), t.data() ); edges.push_back( Simplex( {VertexType(uIndex), VertexType(vIndex)}, data ) ); } } } } std::vector<Simplex> simplices; simplices.reserve( vertices.size() + edges.size() ); simplices.insert( simplices.end(), vertices.begin(), vertices.end() ); simplices.insert( simplices.end(), edges.begin() , edges.end() ); return SimplicialComplex<Simplex>( simplices.begin(), simplices.end() ); } } // namespace topology } // namespace aleph #endif <commit_msg>Reducing memory footprint of clique graph calculation<commit_after>#ifndef ALEPH_TOPOLOGY_CLIQUE_GRAPH_HH__ #define ALEPH_TOPOLOGY_CLIQUE_GRAPH_HH__ #include "topology/SimplicialComplex.hh" #include <list> #include <map> #include <stdexcept> #include <vector> namespace aleph { namespace topology { /** Given a simplicial complex, extracts its corresponding clique graph. The clique graph is defined as the graph in which each node corresponds to a k-simplex and an edge connects two nodes if there is a $(k-1)$-face that connects the two simplices. Note that the graph is represented as a simplicial complex. It makes any other operations easier. */ template <class Simplex> SimplicialComplex<Simplex> getCliqueGraph( const SimplicialComplex<Simplex>& K, unsigned k ) { // Stores the co-faces of (k-1)-dimensional simplices. This is required for // the edge creation. Whenever two (or more) k-simplices appear in this map // they will be connected by an edge. std::map<Simplex, std::vector<std::size_t> > cofaceMap; std::vector<Simplex> vertices; using VertexType = typename Simplex::VertexType; { // Maps k-simplices to their corresponding index in the filtration order of // the simplicial complex. This simplifies the creation of edges. std::map<Simplex, std::size_t> simplexMap; for( auto itPair = K.range(k); itPair.first != itPair.second; ++itPair.first ) simplexMap[ *itPair.first ] = K.index( *itPair.first ); for( auto&& pair : simplexMap ) { auto&& simplex = pair.first; auto&& index = pair.second; // TODO: Is the number of co-faces bounded? If so, I could reserve // sufficient memory in the map. for( auto itFace = simplex.begin_boundary(); itFace != simplex.end_boundary(); ++itFace ) cofaceMap[ *itFace ].push_back( index ); } // Create vertices ------------------------------------------------- vertices.reserve( simplexMap.size() ); for( auto&& pair : simplexMap ) { auto&& simplex = pair.first; auto&& index = pair.second; vertices.push_back( Simplex( VertexType(index), simplex.data() ) ); } } // Create edges ------------------------------------------------------ // Since the number of edges is unknown beforehand, it makes sense to use a // list rather than a vector here. Else, the allocation of larger swaths of // memory will be problematic. std::list<Simplex> edges; for( auto&& pair : cofaceMap ) { auto&& indices = pair.second; if( indices.size() >= 2 ) { for( std::size_t i = 0; i < indices.size(); i++ ) { auto uIndex = indices[i]; for( std::size_t j = i+1; j < indices.size(); j++ ) { auto vIndex = indices[j]; // TODO: What happens if the indices are invalid? Do I need to // prepare for this situation explicitly? auto&& s = K.at( uIndex ); auto&& t = K.at( vIndex ); // TODO: Does it make sense to make this configurable? As of now, I // am restricting the weights to the usual maximum filtration, i.e. // I am assuming a growth process here. auto data = std::max( s.data(), t.data() ); edges.push_back( Simplex( {VertexType(uIndex), VertexType(vIndex)}, data ) ); } } } } std::vector<Simplex> simplices; simplices.reserve( vertices.size() + edges.size() ); simplices.insert( simplices.end(), vertices.begin(), vertices.end() ); simplices.insert( simplices.end(), edges.begin() , edges.end() ); return SimplicialComplex<Simplex>( simplices.begin(), simplices.end() ); } } // namespace topology } // namespace aleph #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep08/call_host_set_voltages.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /******************************************************************************/ // Includes /******************************************************************************/ #include <stdint.h> #include <trace/interface.H> #include <errl/errlentry.H> #include <initservice/isteps_trace.H> #include <initservice/initserviceif.H> #include <isteps/hwpisteperror.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/utilFilter.H> #include <errl/errlmanager.H> #include <fapi2/target.H> #include <fapi2/plat_hwp_invoker.H> #include <p9_setup_evid.H> #include <hbToHwsvVoltageMsg.H> using namespace TARGETING; using namespace ERRORLOG; using namespace ISTEP_ERROR; namespace ISTEP_08 { //***************************************************************************** // call_host_set_voltages() //***************************************************************************** void* call_host_set_voltages(void *io_pArgs) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_host_set_voltages enter"); errlHndl_t l_err = NULL; TargetHandleList l_procList; IStepError l_stepError; bool l_noError = true; do { // Get the system's procs getAllChips( l_procList, TYPE_PROC, true ); // true: return functional procs // Iterate over the found procs calling p9_setup_evid for( const auto & l_procTarget : l_procList ) { // Cast to fapi2 target const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapiProcTarget( l_procTarget ); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Running p9_setup_evid HWP on processor target %.8X", get_huid( l_procTarget ) ); FAPI_INVOKE_HWP( l_err, p9_setup_evid, l_fapiProcTarget, APPLY_VOLTAGE_SETTINGS); if( l_err ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Error running p9_setup_evid on processor target %.8X", get_huid( l_procTarget ) ); l_stepError.addErrorDetails( l_err ); errlCommit( l_err, HWPF_COMP_ID ); l_noError = false; } } // Processor Loop if( l_noError ) { #if 0 // TODO RTC: 160517 - Uncomment the call to send processor voltage data to HWSV //If FSP is present, send voltage information to HWSV if( INITSERVICE::spBaseServicesEnabled() ) { l_err = platform_set_nest_voltages(); if( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Error in call_host_set_voltages::platform_set_nest_voltages()") // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); //Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } } #endif } }while( 0 ); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_host_set_voltages exit"); // end task, returning any errorlogs to IStepDisp return l_stepError.getErrorHandle(); } }; // end namespace <commit_msg>Uncomment call to send processor voltage data to HWSV<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep08/call_host_set_voltages.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /******************************************************************************/ // Includes /******************************************************************************/ #include <stdint.h> #include <trace/interface.H> #include <errl/errlentry.H> #include <initservice/isteps_trace.H> #include <initservice/initserviceif.H> #include <isteps/hwpisteperror.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/utilFilter.H> #include <errl/errlmanager.H> #include <fapi2/target.H> #include <fapi2/plat_hwp_invoker.H> #include <p9_setup_evid.H> #include <hbToHwsvVoltageMsg.H> using namespace TARGETING; using namespace ERRORLOG; using namespace ISTEP_ERROR; namespace ISTEP_08 { //***************************************************************************** // call_host_set_voltages() //***************************************************************************** void* call_host_set_voltages(void *io_pArgs) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_host_set_voltages enter"); errlHndl_t l_err = NULL; TargetHandleList l_procList; IStepError l_stepError; bool l_noError = true; do { // Get the system's procs getAllChips( l_procList, TYPE_PROC, true ); // true: return functional procs // Iterate over the found procs calling p9_setup_evid for( const auto & l_procTarget : l_procList ) { // Cast to fapi2 target const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapiProcTarget( l_procTarget ); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Running p9_setup_evid HWP on processor target %.8X", get_huid( l_procTarget ) ); FAPI_INVOKE_HWP( l_err, p9_setup_evid, l_fapiProcTarget, APPLY_VOLTAGE_SETTINGS); if( l_err ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Error running p9_setup_evid on processor target %.8X", get_huid( l_procTarget ) ); l_stepError.addErrorDetails( l_err ); errlCommit( l_err, HWPF_COMP_ID ); l_noError = false; } } // Processor Loop if( l_noError ) { //If FSP is present, send voltage information to HWSV if( INITSERVICE::spBaseServicesEnabled() ) { l_err = platform_set_nest_voltages(); if( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Error in call_host_set_voltages::platform_set_nest_voltages()") // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); //Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } } } }while( 0 ); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_host_set_voltages exit"); // end task, returning any errorlogs to IStepDisp return l_stepError.getErrorHandle(); } }; // end namespace <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. */ #include <oper/interface_common.h> #include <uve/interface_uve_stats_table.h> #include <uve/agent_uve.h> InterfaceUveStatsTable::InterfaceUveStatsTable(Agent *agent, uint32_t default_intvl) : InterfaceUveTable(agent, default_intvl) { } InterfaceUveStatsTable::~InterfaceUveStatsTable() { } bool InterfaceUveStatsTable::FrameInterfaceStatsMsg(UveInterfaceEntry* entry, UveVMInterfaceAgent *uve) const { uint64_t in_band, out_band; vector<VmInterfaceStats> if_stats_list; VmInterfaceStats if_stats; vector<VmFloatingIPStats> agg_fip_list; vector<VmFloatingIPStats> diff_fip_list; const VmInterface *vm_intf = entry->intf_; assert(!entry->deleted_); if (vm_intf->cfg_name().empty()) { return false; } uve->set_name(vm_intf->cfg_name()); entry->SetVnVmInfo(uve); const Interface *intf = static_cast<const Interface *>(vm_intf); AgentUve *agent_uve = static_cast<AgentUve *>(agent_->uve()); StatsManager::InterfaceStats *s = agent_uve->stats_manager()->GetInterfaceStats(intf); if (s == NULL) { return false; } /* Only diff since previous send needs to be sent as we export * stats via StatsOracle infra provided by analytics module */ uint64_t in_b, in_p, out_b, out_p; s->GetDiffStats(&in_b, &in_p, &out_b, &out_p); if_stats.set_in_pkts(in_p); if_stats.set_in_bytes(in_b); if_stats.set_out_pkts(out_p); if_stats.set_out_bytes(out_b); in_band = GetVmPortBandwidth(s, true); out_band = GetVmPortBandwidth(s, false); if_stats.set_in_bw_usage(in_band); if_stats.set_out_bw_usage(out_band); s->stats_time = UTCTimestampUsec(); /* Make sure that update of prev_in_bytes and prev_out_bytes are done only * after GetVmPortBandwidth is done for both directions as they get used * in those APIs. */ s->UpdatePrevStats(); PortBucketBitmap map; L4PortBitmap &port_bmap = entry->port_bitmap_; port_bmap.Encode(map); uve->set_port_bucket_bmap(map); FrameFipStatsMsg(vm_intf, agg_fip_list, diff_fip_list); if (entry->FipAggStatsChanged(agg_fip_list)) { uve->set_fip_agg_stats(agg_fip_list); entry->uve_info_.set_fip_agg_stats(agg_fip_list); } /* Diff stats are sent always regardless of whether there are * any changes are not. */ uve->set_fip_diff_stats(diff_fip_list); if_stats_list.push_back(if_stats); uve->set_if_stats(if_stats_list); return true; } void InterfaceUveStatsTable::SendInterfaceStatsMsg(UveInterfaceEntry* entry) { if (entry->deleted_) { return; } UveVMInterfaceAgent uve; bool send = FrameInterfaceStatsMsg(entry, &uve); if (send) { DispatchInterfaceMsg(uve); } } void InterfaceUveStatsTable::SendInterfaceStats(void) { InterfaceMap::iterator it = interface_tree_.begin(); while (it != interface_tree_.end()) { UveInterfaceEntry* entry = it->second.get(); SendInterfaceStatsMsg(entry); it++; } } uint64_t InterfaceUveStatsTable::GetVmPortBandwidth (StatsManager::InterfaceStats *s, bool dir_in) const { if (s->stats_time == 0) { return 0; } uint64_t bits; if (dir_in) { bits = (s->in_bytes - s->prev_in_bytes) * 8; } else { bits = (s->out_bytes - s->prev_out_bytes) * 8; } uint64_t cur_time = UTCTimestampUsec(); uint64_t b_intvl = agent_->uve()->bandwidth_intvl(); uint64_t diff_seconds = (cur_time - s->stats_time) / b_intvl; if (diff_seconds == 0) { return 0; } return bits/diff_seconds; } void InterfaceUveStatsTable::UpdateFloatingIpStats(const FipInfo &fip_info) { Interface *intf = InterfaceTable::GetInstance()->FindInterface (fip_info.fip_vm_port_id_); VmInterface *vmi = static_cast<VmInterface *>(intf); InterfaceMap::iterator intf_it = interface_tree_.find(vmi->cfg_name()); /* * 1. VM interface with floating-ip becomes active * 2. Flow is created on this interface and interface floating ip info is * stored in flow record * 3. VM Interface is disassociated from VM * 4. VM Interface info is removed from interface_tree_ because of * disassociation * 5. FlowStats collection task initiates export of flow stats * 6. Since interface is absent in interface_tree_ we cannot update * stats in this case */ if (intf_it != interface_tree_.end()) { UveInterfaceEntry *entry = intf_it->second.get(); entry->UpdateFloatingIpStats(fip_info); } } bool InterfaceUveStatsTable::FrameFipStatsMsg(const VmInterface *itf, vector<VmFloatingIPStats> &fip_list, vector<VmFloatingIPStats> &diff_list) const { bool changed = false; InterfaceMap::const_iterator it = interface_tree_.find(itf->cfg_name()); if (it != interface_tree_.end()) { UveInterfaceEntry *entry = it->second.get(); changed = entry->FillFloatingIpStats(fip_list, diff_list); } return changed; } void InterfaceUveStatsTable::UpdatePortBitmap (const string &name, uint8_t proto, uint16_t sport, uint16_t dport) { InterfaceMap::const_iterator it = interface_tree_.find(name); if (it != interface_tree_.end()) { UveInterfaceEntry *entry = it->second.get(); entry->port_bitmap_.AddPort(proto, sport, dport); } } InterfaceUveTable::FloatingIp * InterfaceUveStatsTable::FipEntry (uint32_t fip, const string &vn, Interface *intf) { VmInterface *vmi = static_cast<VmInterface *>(intf); InterfaceMap::iterator intf_it = interface_tree_.find(vmi->cfg_name()); assert (intf_it != interface_tree_.end()); UveInterfaceEntry *entry = intf_it->second.get(); return entry->FipEntry(fip, vn); } <commit_msg>Fix contrail-vrouter-agent crash during Floating-Ip stats updation.<commit_after>/* * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. */ #include <oper/interface_common.h> #include <uve/interface_uve_stats_table.h> #include <uve/agent_uve.h> InterfaceUveStatsTable::InterfaceUveStatsTable(Agent *agent, uint32_t default_intvl) : InterfaceUveTable(agent, default_intvl) { } InterfaceUveStatsTable::~InterfaceUveStatsTable() { } bool InterfaceUveStatsTable::FrameInterfaceStatsMsg(UveInterfaceEntry* entry, UveVMInterfaceAgent *uve) const { uint64_t in_band, out_band; vector<VmInterfaceStats> if_stats_list; VmInterfaceStats if_stats; vector<VmFloatingIPStats> agg_fip_list; vector<VmFloatingIPStats> diff_fip_list; const VmInterface *vm_intf = entry->intf_; assert(!entry->deleted_); if (vm_intf->cfg_name().empty()) { return false; } uve->set_name(vm_intf->cfg_name()); entry->SetVnVmInfo(uve); const Interface *intf = static_cast<const Interface *>(vm_intf); AgentUve *agent_uve = static_cast<AgentUve *>(agent_->uve()); StatsManager::InterfaceStats *s = agent_uve->stats_manager()->GetInterfaceStats(intf); if (s == NULL) { return false; } /* Only diff since previous send needs to be sent as we export * stats via StatsOracle infra provided by analytics module */ uint64_t in_b, in_p, out_b, out_p; s->GetDiffStats(&in_b, &in_p, &out_b, &out_p); if_stats.set_in_pkts(in_p); if_stats.set_in_bytes(in_b); if_stats.set_out_pkts(out_p); if_stats.set_out_bytes(out_b); in_band = GetVmPortBandwidth(s, true); out_band = GetVmPortBandwidth(s, false); if_stats.set_in_bw_usage(in_band); if_stats.set_out_bw_usage(out_band); s->stats_time = UTCTimestampUsec(); /* Make sure that update of prev_in_bytes and prev_out_bytes are done only * after GetVmPortBandwidth is done for both directions as they get used * in those APIs. */ s->UpdatePrevStats(); PortBucketBitmap map; L4PortBitmap &port_bmap = entry->port_bitmap_; port_bmap.Encode(map); uve->set_port_bucket_bmap(map); FrameFipStatsMsg(vm_intf, agg_fip_list, diff_fip_list); if (entry->FipAggStatsChanged(agg_fip_list)) { uve->set_fip_agg_stats(agg_fip_list); entry->uve_info_.set_fip_agg_stats(agg_fip_list); } /* Diff stats are sent always regardless of whether there are * any changes are not. */ uve->set_fip_diff_stats(diff_fip_list); if_stats_list.push_back(if_stats); uve->set_if_stats(if_stats_list); return true; } void InterfaceUveStatsTable::SendInterfaceStatsMsg(UveInterfaceEntry* entry) { if (entry->deleted_) { return; } UveVMInterfaceAgent uve; bool send = FrameInterfaceStatsMsg(entry, &uve); if (send) { DispatchInterfaceMsg(uve); } } void InterfaceUveStatsTable::SendInterfaceStats(void) { InterfaceMap::iterator it = interface_tree_.begin(); while (it != interface_tree_.end()) { UveInterfaceEntry* entry = it->second.get(); SendInterfaceStatsMsg(entry); it++; } } uint64_t InterfaceUveStatsTable::GetVmPortBandwidth (StatsManager::InterfaceStats *s, bool dir_in) const { if (s->stats_time == 0) { return 0; } uint64_t bits; if (dir_in) { bits = (s->in_bytes - s->prev_in_bytes) * 8; } else { bits = (s->out_bytes - s->prev_out_bytes) * 8; } uint64_t cur_time = UTCTimestampUsec(); uint64_t b_intvl = agent_->uve()->bandwidth_intvl(); uint64_t diff_seconds = (cur_time - s->stats_time) / b_intvl; if (diff_seconds == 0) { return 0; } return bits/diff_seconds; } void InterfaceUveStatsTable::UpdateFloatingIpStats(const FipInfo &fip_info) { Interface *intf = InterfaceTable::GetInstance()->FindInterface (fip_info.fip_vm_port_id_); if (intf == NULL) { return; } VmInterface *vmi = static_cast<VmInterface *>(intf); InterfaceMap::iterator intf_it = interface_tree_.find(vmi->cfg_name()); /* * 1. VM interface with floating-ip becomes active * 2. Flow is created on this interface and interface floating ip info is * stored in flow record * 3. VM Interface is disassociated from VM * 4. VM Interface info is removed from interface_tree_ because of * disassociation * 5. FlowStats collection task initiates export of flow stats * 6. Since interface is absent in interface_tree_ we cannot update * stats in this case */ if (intf_it != interface_tree_.end()) { UveInterfaceEntry *entry = intf_it->second.get(); entry->UpdateFloatingIpStats(fip_info); } } bool InterfaceUveStatsTable::FrameFipStatsMsg(const VmInterface *itf, vector<VmFloatingIPStats> &fip_list, vector<VmFloatingIPStats> &diff_list) const { bool changed = false; InterfaceMap::const_iterator it = interface_tree_.find(itf->cfg_name()); if (it != interface_tree_.end()) { UveInterfaceEntry *entry = it->second.get(); changed = entry->FillFloatingIpStats(fip_list, diff_list); } return changed; } void InterfaceUveStatsTable::UpdatePortBitmap (const string &name, uint8_t proto, uint16_t sport, uint16_t dport) { InterfaceMap::const_iterator it = interface_tree_.find(name); if (it != interface_tree_.end()) { UveInterfaceEntry *entry = it->second.get(); entry->port_bitmap_.AddPort(proto, sport, dport); } } InterfaceUveTable::FloatingIp * InterfaceUveStatsTable::FipEntry (uint32_t fip, const string &vn, Interface *intf) { VmInterface *vmi = static_cast<VmInterface *>(intf); InterfaceMap::iterator intf_it = interface_tree_.find(vmi->cfg_name()); assert (intf_it != interface_tree_.end()); UveInterfaceEntry *entry = intf_it->second.get(); return entry->FipEntry(fip, vn); } <|endoftext|>
<commit_before>/* * Object to filter common types of MIDI events out of raw MIDI event dictionaries * Copyright © 2011, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTGraphObjectBase.h" #include "TTMidiFilter.h" #ifdef TT_PLATFORM_WIN #include <algorithm> #endif #define thisTTClass TTMidiFilter #define thisTTClassName "midi.filter" #define thisTTClassTags "midi" TT_OBJECT_CONSTRUCTOR, mType(kTTSymEmpty) { addAttribute(Type, kTypeSymbol); addMessageWithArguments(dictionary); setAttributeValue(TT("type"), TT("note")); } TTMidiFilter::~TTMidiFilter() { ; } TTErr TTMidiFilter::dictionary(const TTValue& input, TTValue& output) { TTDictionaryPtr d = NULL; TTSymbol schema; //input.get(0, (TTPtr*)(&d)); d = TTDictionaryPtr(TTPtr(input[0])); schema = d->getSchema(); if (schema == TT("RawMidiEvent")) { TTValue statusByteValue; TTValue dataByte1Value; TTValue dataByte2Value; TTUInt8 statusByte; d->lookup(TT("status"), statusByteValue); d->lookup(TT("data1"), dataByte1Value); d->lookup(TT("data2"), dataByte2Value); statusByteValue.get(0, statusByte); if (mType == TT("note")) { bool noteon = false; bool noteoff = false; if (statusByte > 127 && statusByte < 144) noteoff = true; else if (statusByte > 143 && statusByte < 160) noteon = true; else goto out; { TTValue v; v.resize(3); v.set(0, TTUInt8(dataByte1Value)); if (noteon) { v.set(1, TTUInt8(dataByte2Value)); v.set(2, statusByte - 143); } else { v.set(1, TTUInt8(0)); v.set(2, statusByte - 127); } d->setSchema(TT("MidiNoteEvent")); d->setValue(v); return kTTErrNone; } } out: d->clear(); output.set(0, TTPtr(d)); return kTTErrNone; } else { return kTTErrInvalidType; } } <commit_msg>replacing deprecated get() & set() calls. see #253<commit_after>/* * Object to filter common types of MIDI events out of raw MIDI event dictionaries * Copyright © 2011, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTGraphObjectBase.h" #include "TTMidiFilter.h" #ifdef TT_PLATFORM_WIN #include <algorithm> #endif #define thisTTClass TTMidiFilter #define thisTTClassName "midi.filter" #define thisTTClassTags "midi" TT_OBJECT_CONSTRUCTOR, mType(kTTSymEmpty) { addAttribute(Type, kTypeSymbol); addMessageWithArguments(dictionary); setAttributeValue(TT("type"), TT("note")); } TTMidiFilter::~TTMidiFilter() { ; } TTErr TTMidiFilter::dictionary(const TTValue& input, TTValue& output) { TTDictionaryPtr d = NULL; TTSymbol schema; //input.get(0, (TTPtr*)(&d)); d = TTDictionaryPtr(TTPtr(input[0])); schema = d->getSchema(); if (schema == TT("RawMidiEvent")) { TTValue statusByteValue; TTValue dataByte1Value; TTValue dataByte2Value; TTUInt8 statusByte; d->lookup(TT("status"), statusByteValue); d->lookup(TT("data1"), dataByte1Value); d->lookup(TT("data2"), dataByte2Value); statusByte = statusByteValue[0]; if (mType == TT("note")) { bool noteon = false; bool noteoff = false; if (statusByte > 127 && statusByte < 144) noteoff = true; else if (statusByte > 143 && statusByte < 160) noteon = true; else goto out; { TTValue v; v.resize(3); v[0] = TTUInt8(dataByte1Value); if (noteon) { v[1] = TTUInt8(dataByte2Value); v[2] = statusByte - 143; } else { v[1] = TTUInt8(0); v[2] = statusByte - 127; } d->setSchema(TT("MidiNoteEvent")); d->setValue(v); return kTTErrNone; } } out: d->clear(); output[0] = TTPtr(d); return kTTErrNone; } else { return kTTErrInvalidType; } } <|endoftext|>
<commit_before>// Copyright 2020 Microsoft, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/printing/print_view_manager_electron.h" #include <utility> #include "build/build_config.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/mojom/print.mojom.h" #include "printing/page_range.h" #include "third_party/abseil-cpp/absl/types/variant.h" #if BUILDFLAG(ENABLE_PRINT_PREVIEW) #include "mojo/public/cpp/bindings/message.h" #endif namespace electron { namespace { #if BUILDFLAG(ENABLE_PRINT_PREVIEW) constexpr char kInvalidUpdatePrintSettingsCall[] = "Invalid UpdatePrintSettings Call"; constexpr char kInvalidSetupScriptedPrintPreviewCall[] = "Invalid SetupScriptedPrintPreview Call"; constexpr char kInvalidShowScriptedPrintPreviewCall[] = "Invalid ShowScriptedPrintPreview Call"; constexpr char kInvalidRequestPrintPreviewCall[] = "Invalid RequestPrintPreview Call"; #endif } // namespace // This file subclasses printing::PrintViewManagerBase // but the implementations are duplicated from // components/printing/browser/print_to_pdf/pdf_print_manager.cc. PrintViewManagerElectron::PrintViewManagerElectron( content::WebContents* web_contents) : printing::PrintViewManagerBase(web_contents), content::WebContentsUserData<PrintViewManagerElectron>(*web_contents) {} PrintViewManagerElectron::~PrintViewManagerElectron() = default; // static void PrintViewManagerElectron::BindPrintManagerHost( mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver, content::RenderFrameHost* rfh) { auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) return; auto* print_manager = PrintViewManagerElectron::FromWebContents(web_contents); if (!print_manager) return; print_manager->BindReceiver(std::move(receiver), rfh); } // static std::string PrintViewManagerElectron::PrintResultToString(PrintResult result) { switch (result) { case PRINT_SUCCESS: return std::string(); // no error message case PRINTING_FAILED: return "Printing failed"; case INVALID_PRINTER_SETTINGS: return "Show invalid printer settings error"; case INVALID_MEMORY_HANDLE: return "Invalid memory handle"; case METAFILE_MAP_ERROR: return "Map to shared memory error"; case METAFILE_INVALID_HEADER: return "Invalid metafile header"; case METAFILE_GET_DATA_ERROR: return "Get data from metafile error"; case SIMULTANEOUS_PRINT_ACTIVE: return "The previous printing job hasn't finished"; case PAGE_RANGE_SYNTAX_ERROR: return "Page range syntax error"; case PAGE_RANGE_INVALID_RANGE: return "Page range is invalid (start > end)"; case PAGE_COUNT_EXCEEDED: return "Page range exceeds page count"; default: NOTREACHED(); return "Unknown PrintResult"; } } void PrintViewManagerElectron::PrintToPdf( content::RenderFrameHost* rfh, const std::string& page_ranges, printing::mojom::PrintPagesParamsPtr print_pages_params, PrintToPDFCallback callback) { DCHECK(callback); if (callback_) { std::move(callback).Run(SIMULTANEOUS_PRINT_ACTIVE, base::MakeRefCounted<base::RefCountedString>()); return; } if (!rfh->IsRenderFrameLive()) { std::move(callback).Run(PRINTING_FAILED, base::MakeRefCounted<base::RefCountedString>()); return; } absl::variant<printing::PageRanges, print_to_pdf::PageRangeError> parsed_ranges = print_to_pdf::TextPageRangesToPageRanges(page_ranges); if (absl::holds_alternative<print_to_pdf::PageRangeError>(parsed_ranges)) { PrintResult print_result; switch (absl::get<print_to_pdf::PageRangeError>(parsed_ranges)) { case print_to_pdf::PageRangeError::kSyntaxError: print_result = PAGE_RANGE_SYNTAX_ERROR; break; case print_to_pdf::PageRangeError::kInvalidRange: print_result = PAGE_RANGE_INVALID_RANGE; break; } std::move(callback).Run(print_result, base::MakeRefCounted<base::RefCountedString>()); return; } printing_rfh_ = rfh; print_pages_params->pages = absl::get<printing::PageRanges>(parsed_ranges); auto cookie = print_pages_params->params->document_cookie; set_cookie(cookie); headless_jobs_.emplace_back(cookie); callback_ = std::move(callback); GetPrintRenderFrame(rfh)->PrintWithParams(std::move(print_pages_params)); } void PrintViewManagerElectron::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { if (printing_rfh_) { LOG(ERROR) << "Scripted print is not supported"; std::move(callback).Run(printing::mojom::PrintParams::New()); } else { PrintViewManagerBase::GetDefaultPrintSettings(std::move(callback)); } } void PrintViewManagerElectron::ScriptedPrint( printing::mojom::ScriptedPrintParamsPtr params, ScriptedPrintCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), params->cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::ScriptedPrint(std::move(params), std::move(callback)); return; } auto default_param = printing::mojom::PrintPagesParams::New(); default_param->params = printing::mojom::PrintParams::New(); LOG(ERROR) << "Scripted print is not supported"; std::move(callback).Run(std::move(default_param), /*cancelled*/ false); } void PrintViewManagerElectron::ShowInvalidPrinterSettingsError() { ReleaseJob(INVALID_PRINTER_SETTINGS); } void PrintViewManagerElectron::PrintingFailed( int32_t cookie, printing::mojom::PrintFailureReason reason) { ReleaseJob(reason == printing::mojom::PrintFailureReason::kInvalidPageRange ? PAGE_COUNT_EXCEEDED : PRINTING_FAILED); } #if BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerElectron::UpdatePrintSettings( int32_t cookie, base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::UpdatePrintSettings(cookie, std::move(job_settings), std::move(callback)); return; } mojo::ReportBadMessage(kInvalidUpdatePrintSettingsCall); } void PrintViewManagerElectron::SetupScriptedPrintPreview( SetupScriptedPrintPreviewCallback callback) { mojo::ReportBadMessage(kInvalidSetupScriptedPrintPreviewCall); } void PrintViewManagerElectron::ShowScriptedPrintPreview( bool source_is_modifiable) { mojo::ReportBadMessage(kInvalidShowScriptedPrintPreviewCall); } void PrintViewManagerElectron::RequestPrintPreview( printing::mojom::RequestPrintPreviewParamsPtr params) { mojo::ReportBadMessage(kInvalidRequestPrintPreviewCall); } void PrintViewManagerElectron::CheckForCancel(int32_t preview_ui_id, int32_t request_id, CheckForCancelCallback callback) { std::move(callback).Run(false); } #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerElectron::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { PrintViewManagerBase::RenderFrameDeleted(render_frame_host); if (printing_rfh_ != render_frame_host) return; if (callback_) { std::move(callback_).Run(PRINTING_FAILED, base::MakeRefCounted<base::RefCountedString>()); } Reset(); } void PrintViewManagerElectron::DidGetPrintedPagesCount(int32_t cookie, uint32_t number_pages) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::DidGetPrintedPagesCount(cookie, number_pages); } } void PrintViewManagerElectron::DidPrintDocument( printing::mojom::DidPrintDocumentParamsPtr params, DidPrintDocumentCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), params->document_cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::DidPrintDocument(std::move(params), std::move(callback)); return; } auto& content = *params->content; if (!content.metafile_data_region.IsValid()) { ReleaseJob(INVALID_MEMORY_HANDLE); std::move(callback).Run(false); return; } base::ReadOnlySharedMemoryMapping map = content.metafile_data_region.Map(); if (!map.IsValid()) { ReleaseJob(METAFILE_MAP_ERROR); std::move(callback).Run(false); return; } data_ = std::string(static_cast<const char*>(map.memory()), map.size()); headless_jobs_.erase(entry); std::move(callback).Run(true); ReleaseJob(PRINT_SUCCESS); } void PrintViewManagerElectron::Reset() { printing_rfh_ = nullptr; callback_.Reset(); data_.clear(); } void PrintViewManagerElectron::ReleaseJob(PrintResult result) { if (callback_) { DCHECK(result == PRINT_SUCCESS || data_.empty()); std::move(callback_).Run(result, base::RefCountedString::TakeString(&data_)); if (printing_rfh_ && printing_rfh_->IsRenderFrameLive()) { GetPrintRenderFrame(printing_rfh_)->PrintingDone(result == PRINT_SUCCESS); } Reset(); } } WEB_CONTENTS_USER_DATA_KEY_IMPL(PrintViewManagerElectron); } // namespace electron <commit_msg>fix: delegate to `PrintViewManagerBase` on failed print (#34893)<commit_after>// Copyright 2020 Microsoft, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/printing/print_view_manager_electron.h" #include <utility> #include "build/build_config.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/mojom/print.mojom.h" #include "printing/page_range.h" #include "third_party/abseil-cpp/absl/types/variant.h" #if BUILDFLAG(ENABLE_PRINT_PREVIEW) #include "mojo/public/cpp/bindings/message.h" #endif namespace electron { namespace { #if BUILDFLAG(ENABLE_PRINT_PREVIEW) constexpr char kInvalidUpdatePrintSettingsCall[] = "Invalid UpdatePrintSettings Call"; constexpr char kInvalidSetupScriptedPrintPreviewCall[] = "Invalid SetupScriptedPrintPreview Call"; constexpr char kInvalidShowScriptedPrintPreviewCall[] = "Invalid ShowScriptedPrintPreview Call"; constexpr char kInvalidRequestPrintPreviewCall[] = "Invalid RequestPrintPreview Call"; #endif } // namespace // This file subclasses printing::PrintViewManagerBase // but the implementations are duplicated from // components/printing/browser/print_to_pdf/pdf_print_manager.cc. PrintViewManagerElectron::PrintViewManagerElectron( content::WebContents* web_contents) : printing::PrintViewManagerBase(web_contents), content::WebContentsUserData<PrintViewManagerElectron>(*web_contents) {} PrintViewManagerElectron::~PrintViewManagerElectron() = default; // static void PrintViewManagerElectron::BindPrintManagerHost( mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver, content::RenderFrameHost* rfh) { auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) return; auto* print_manager = PrintViewManagerElectron::FromWebContents(web_contents); if (!print_manager) return; print_manager->BindReceiver(std::move(receiver), rfh); } // static std::string PrintViewManagerElectron::PrintResultToString(PrintResult result) { switch (result) { case PRINT_SUCCESS: return std::string(); // no error message case PRINTING_FAILED: return "Printing failed"; case INVALID_PRINTER_SETTINGS: return "Show invalid printer settings error"; case INVALID_MEMORY_HANDLE: return "Invalid memory handle"; case METAFILE_MAP_ERROR: return "Map to shared memory error"; case METAFILE_INVALID_HEADER: return "Invalid metafile header"; case METAFILE_GET_DATA_ERROR: return "Get data from metafile error"; case SIMULTANEOUS_PRINT_ACTIVE: return "The previous printing job hasn't finished"; case PAGE_RANGE_SYNTAX_ERROR: return "Page range syntax error"; case PAGE_RANGE_INVALID_RANGE: return "Page range is invalid (start > end)"; case PAGE_COUNT_EXCEEDED: return "Page range exceeds page count"; default: NOTREACHED(); return "Unknown PrintResult"; } } void PrintViewManagerElectron::PrintToPdf( content::RenderFrameHost* rfh, const std::string& page_ranges, printing::mojom::PrintPagesParamsPtr print_pages_params, PrintToPDFCallback callback) { DCHECK(callback); if (callback_) { std::move(callback).Run(SIMULTANEOUS_PRINT_ACTIVE, base::MakeRefCounted<base::RefCountedString>()); return; } if (!rfh->IsRenderFrameLive()) { std::move(callback).Run(PRINTING_FAILED, base::MakeRefCounted<base::RefCountedString>()); return; } absl::variant<printing::PageRanges, print_to_pdf::PageRangeError> parsed_ranges = print_to_pdf::TextPageRangesToPageRanges(page_ranges); if (absl::holds_alternative<print_to_pdf::PageRangeError>(parsed_ranges)) { PrintResult print_result; switch (absl::get<print_to_pdf::PageRangeError>(parsed_ranges)) { case print_to_pdf::PageRangeError::kSyntaxError: print_result = PAGE_RANGE_SYNTAX_ERROR; break; case print_to_pdf::PageRangeError::kInvalidRange: print_result = PAGE_RANGE_INVALID_RANGE; break; } std::move(callback).Run(print_result, base::MakeRefCounted<base::RefCountedString>()); return; } printing_rfh_ = rfh; print_pages_params->pages = absl::get<printing::PageRanges>(parsed_ranges); auto cookie = print_pages_params->params->document_cookie; set_cookie(cookie); headless_jobs_.emplace_back(cookie); callback_ = std::move(callback); GetPrintRenderFrame(rfh)->PrintWithParams(std::move(print_pages_params)); } void PrintViewManagerElectron::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { if (printing_rfh_) { LOG(ERROR) << "Scripted print is not supported"; std::move(callback).Run(printing::mojom::PrintParams::New()); } else { PrintViewManagerBase::GetDefaultPrintSettings(std::move(callback)); } } void PrintViewManagerElectron::ScriptedPrint( printing::mojom::ScriptedPrintParamsPtr params, ScriptedPrintCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), params->cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::ScriptedPrint(std::move(params), std::move(callback)); return; } auto default_param = printing::mojom::PrintPagesParams::New(); default_param->params = printing::mojom::PrintParams::New(); LOG(ERROR) << "Scripted print is not supported"; std::move(callback).Run(std::move(default_param), /*cancelled*/ false); } void PrintViewManagerElectron::ShowInvalidPrinterSettingsError() { if (headless_jobs_.size() == 0) { PrintViewManagerBase::ShowInvalidPrinterSettingsError(); return; } ReleaseJob(INVALID_PRINTER_SETTINGS); } void PrintViewManagerElectron::PrintingFailed( int32_t cookie, printing::mojom::PrintFailureReason reason) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::PrintingFailed(cookie, reason); return; } ReleaseJob(reason == printing::mojom::PrintFailureReason::kInvalidPageRange ? PAGE_COUNT_EXCEEDED : PRINTING_FAILED); } #if BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerElectron::UpdatePrintSettings( int32_t cookie, base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::UpdatePrintSettings(cookie, std::move(job_settings), std::move(callback)); return; } mojo::ReportBadMessage(kInvalidUpdatePrintSettingsCall); } void PrintViewManagerElectron::SetupScriptedPrintPreview( SetupScriptedPrintPreviewCallback callback) { mojo::ReportBadMessage(kInvalidSetupScriptedPrintPreviewCall); } void PrintViewManagerElectron::ShowScriptedPrintPreview( bool source_is_modifiable) { mojo::ReportBadMessage(kInvalidShowScriptedPrintPreviewCall); } void PrintViewManagerElectron::RequestPrintPreview( printing::mojom::RequestPrintPreviewParamsPtr params) { mojo::ReportBadMessage(kInvalidRequestPrintPreviewCall); } void PrintViewManagerElectron::CheckForCancel(int32_t preview_ui_id, int32_t request_id, CheckForCancelCallback callback) { std::move(callback).Run(false); } #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerElectron::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { PrintViewManagerBase::RenderFrameDeleted(render_frame_host); if (printing_rfh_ != render_frame_host) return; if (callback_) { std::move(callback_).Run(PRINTING_FAILED, base::MakeRefCounted<base::RefCountedString>()); } Reset(); } void PrintViewManagerElectron::DidGetPrintedPagesCount(int32_t cookie, uint32_t number_pages) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::DidGetPrintedPagesCount(cookie, number_pages); } } void PrintViewManagerElectron::DidPrintDocument( printing::mojom::DidPrintDocumentParamsPtr params, DidPrintDocumentCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), params->document_cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::DidPrintDocument(std::move(params), std::move(callback)); return; } auto& content = *params->content; if (!content.metafile_data_region.IsValid()) { ReleaseJob(INVALID_MEMORY_HANDLE); std::move(callback).Run(false); return; } base::ReadOnlySharedMemoryMapping map = content.metafile_data_region.Map(); if (!map.IsValid()) { ReleaseJob(METAFILE_MAP_ERROR); std::move(callback).Run(false); return; } data_ = std::string(static_cast<const char*>(map.memory()), map.size()); headless_jobs_.erase(entry); std::move(callback).Run(true); ReleaseJob(PRINT_SUCCESS); } void PrintViewManagerElectron::Reset() { printing_rfh_ = nullptr; callback_.Reset(); data_.clear(); } void PrintViewManagerElectron::ReleaseJob(PrintResult result) { if (callback_) { DCHECK(result == PRINT_SUCCESS || data_.empty()); std::move(callback_).Run(result, base::RefCountedString::TakeString(&data_)); if (printing_rfh_ && printing_rfh_->IsRenderFrameLive()) { GetPrintRenderFrame(printing_rfh_)->PrintingDone(result == PRINT_SUCCESS); } Reset(); } } WEB_CONTENTS_USER_DATA_KEY_IMPL(PrintViewManagerElectron); } // namespace electron <|endoftext|>
<commit_before>#include "CppUTest/TestHarness.h" #include "timelib.h" #include <string.h> TEST_GROUP(transitions) { }; #define TEST_EXISTS(n,tz) \ TEST(transitions, n) { \ return; \ int error; \ timelib_tzinfo *tzi = timelib_parse_tzfile(tz, timelib_builtin_db(), &error); \ CHECK(tzi != NULL); \ CHECK(error == TIMELIB_ERROR_NO_ERROR || error == TIMELIB_ERROR_SLIM_FILE); \ timelib_dump_tzinfo(tzi); \ timelib_tzinfo_dtor(tzi); \ } #define TEST_TRANSITION(n,tz,ts,eab,eoff) \ TEST(transitions, n) { \ int error; \ timelib_time_offset *tto; \ timelib_tzinfo *tzi = timelib_parse_tzfile(tz, timelib_builtin_db(), &error); \ CHECK(tzi != NULL); \ tto = timelib_get_time_zone_info((ts), tzi); \ CHECK(tto != NULL); \ LONGS_EQUAL((eoff), tto->offset); \ STRCMP_EQUAL((eab), tto->abbr); \ timelib_time_offset_dtor(tto); \ timelib_tzinfo_dtor(tzi); \ } TEST_EXISTS(utc_00, "UTC") TEST_TRANSITION(utc_01, "UTC", INT64_MIN / 2, "UTC", 0) TEST_TRANSITION(utc_02, "UTC", 0, "UTC", 0) TEST_TRANSITION(utc_03, "UTC", INT64_MAX / 2, "UTC", 0) TEST_EXISTS(tokyo_00, "Asia/Tokyo") TEST_TRANSITION(tokyo_01, "Asia/Tokyo", INT64_MIN, "LMT", 33539) TEST_TRANSITION(tokyo_02, "Asia/Tokyo", -2587712401, "LMT", 33539) TEST_TRANSITION(tokyo_03, "Asia/Tokyo", -2587712400, "JST", 32400) TEST_TRANSITION(tokyo_04, "Asia/Tokyo", -2587712399, "JST", 32400) TEST_TRANSITION(tokyo_05, "Asia/Tokyo", -577962001, "JDT", 36000) TEST_TRANSITION(tokyo_06, "Asia/Tokyo", -577962000, "JST", 32400) TEST_TRANSITION(tokyo_07, "Asia/Tokyo", -577961999, "JST", 32400) TEST_TRANSITION(tokyo_08, "Asia/Tokyo", 0, "JST", 32400) TEST_TRANSITION(tokyo_09, "Asia/Tokyo", INT64_MAX, "JST", 32400) TEST_EXISTS(ams_00, "Europe/Amsterdam") TEST_TRANSITION(ams_01, "Europe/Amsterdam", INT64_MIN, "LMT", 1172) TEST_TRANSITION(ams_02, "Europe/Amsterdam", -4260212372, "AMT", 1172) TEST_TRANSITION(ams_03, "Europe/Amsterdam", -1025745573, "NST", 4772) TEST_TRANSITION(ams_04, "Europe/Amsterdam", -1025745572, "+0120", 4800) TEST_TRANSITION(ams_05, "Europe/Amsterdam", 811904399, "CEST", 7200) TEST_TRANSITION(ams_06, "Europe/Amsterdam", 811904440, "CET", 3600) TEST_TRANSITION(ams_07, "Europe/Amsterdam", 828234000, "CEST", 7200) TEST_TRANSITION(ams_08, "Europe/Amsterdam", 846377999, "CEST", 7200) TEST_TRANSITION(ams_09, "Europe/Amsterdam", 846378000, "CET", 3600) TEST_TRANSITION(ams_10, "Europe/Amsterdam", 846378001, "CET", 3600) TEST_TRANSITION(ams_11, "Europe/Amsterdam", 859683599, "CET", 3600) TEST_TRANSITION(ams_12, "Europe/Amsterdam", 859683600, "CEST", 7200) TEST_TRANSITION(ams_13, "Europe/Amsterdam", 859683600, "CEST", 7200) TEST_EXISTS(can_00, "Australia/Canberra") TEST_TRANSITION(can_01, "Australia/Canberra", 1193500799, "AEST", 36000) TEST_TRANSITION(can_02, "Australia/Canberra", 1193500800, "AEDT", 39600) TEST_TRANSITION(can_03, "Australia/Canberra", 1193500801, "AEDT", 39600) TEST_TRANSITION(can_04, "Australia/Canberra", 1207411199, "AEDT", 39600) TEST_TRANSITION(can_05, "Australia/Canberra", 1207411200, "AEST", 36000) TEST_TRANSITION(can_06, "Australia/Canberra", 1207411201, "AEST", 36000) TEST_TRANSITION(can_07, "Australia/Canberra", 1223135999, "AEST", 36000) TEST_TRANSITION(can_08, "Australia/Canberra", 1223136000, "AEDT", 39600) TEST_TRANSITION(can_09, "Australia/Canberra", 1223136001, "AEDT", 39600) TEST_TRANSITION(can_10, "Australia/Canberra", 1238860799, "AEDT", 39600) TEST_TRANSITION(can_11, "Australia/Canberra", 1238860800, "AEST", 36000) TEST_TRANSITION(can_12, "Australia/Canberra", 1238860801, "AEST", 36000) <commit_msg>Added test for half hour jump<commit_after>#include "CppUTest/TestHarness.h" #include "timelib.h" #include <string.h> TEST_GROUP(transitions) { }; #define TEST_EXISTS(n,tz) \ TEST(transitions, n) { \ return; \ int error; \ timelib_tzinfo *tzi = timelib_parse_tzfile(tz, timelib_builtin_db(), &error); \ CHECK(tzi != NULL); \ CHECK(error == TIMELIB_ERROR_NO_ERROR || error == TIMELIB_ERROR_SLIM_FILE); \ timelib_dump_tzinfo(tzi); \ timelib_tzinfo_dtor(tzi); \ } #define TEST_TRANSITION(n,tz,ts,eab,eoff) \ TEST(transitions, n) { \ int error; \ timelib_time_offset *tto; \ timelib_tzinfo *tzi = timelib_parse_tzfile(tz, timelib_builtin_db(), &error); \ CHECK(tzi != NULL); \ tto = timelib_get_time_zone_info((ts), tzi); \ CHECK(tto != NULL); \ LONGS_EQUAL((eoff), tto->offset); \ STRCMP_EQUAL((eab), tto->abbr); \ timelib_time_offset_dtor(tto); \ timelib_tzinfo_dtor(tzi); \ } TEST_EXISTS(utc_00, "UTC") TEST_TRANSITION(utc_01, "UTC", INT64_MIN / 2, "UTC", 0) TEST_TRANSITION(utc_02, "UTC", 0, "UTC", 0) TEST_TRANSITION(utc_03, "UTC", INT64_MAX / 2, "UTC", 0) TEST_EXISTS(tokyo_00, "Asia/Tokyo") TEST_TRANSITION(tokyo_01, "Asia/Tokyo", INT64_MIN, "LMT", 33539) TEST_TRANSITION(tokyo_02, "Asia/Tokyo", -2587712401, "LMT", 33539) TEST_TRANSITION(tokyo_03, "Asia/Tokyo", -2587712400, "JST", 32400) TEST_TRANSITION(tokyo_04, "Asia/Tokyo", -2587712399, "JST", 32400) TEST_TRANSITION(tokyo_05, "Asia/Tokyo", -577962001, "JDT", 36000) TEST_TRANSITION(tokyo_06, "Asia/Tokyo", -577962000, "JST", 32400) TEST_TRANSITION(tokyo_07, "Asia/Tokyo", -577961999, "JST", 32400) TEST_TRANSITION(tokyo_08, "Asia/Tokyo", 0, "JST", 32400) TEST_TRANSITION(tokyo_09, "Asia/Tokyo", INT64_MAX, "JST", 32400) TEST_EXISTS(ams_00, "Europe/Amsterdam") TEST_TRANSITION(ams_01, "Europe/Amsterdam", INT64_MIN, "LMT", 1172) TEST_TRANSITION(ams_02, "Europe/Amsterdam", -4260212372, "AMT", 1172) TEST_TRANSITION(ams_03, "Europe/Amsterdam", -1025745573, "NST", 4772) TEST_TRANSITION(ams_04, "Europe/Amsterdam", -1025745572, "+0120", 4800) TEST_TRANSITION(ams_05, "Europe/Amsterdam", 811904399, "CEST", 7200) TEST_TRANSITION(ams_06, "Europe/Amsterdam", 811904440, "CET", 3600) TEST_TRANSITION(ams_07, "Europe/Amsterdam", 828234000, "CEST", 7200) TEST_TRANSITION(ams_08, "Europe/Amsterdam", 846377999, "CEST", 7200) TEST_TRANSITION(ams_09, "Europe/Amsterdam", 846378000, "CET", 3600) TEST_TRANSITION(ams_10, "Europe/Amsterdam", 846378001, "CET", 3600) TEST_TRANSITION(ams_11, "Europe/Amsterdam", 859683599, "CET", 3600) TEST_TRANSITION(ams_12, "Europe/Amsterdam", 859683600, "CEST", 7200) TEST_TRANSITION(ams_13, "Europe/Amsterdam", 859683600, "CEST", 7200) TEST_EXISTS(can_00, "Australia/Canberra") TEST_TRANSITION(can_01, "Australia/Canberra", 1193500799, "AEST", 36000) TEST_TRANSITION(can_02, "Australia/Canberra", 1193500800, "AEDT", 39600) TEST_TRANSITION(can_03, "Australia/Canberra", 1193500801, "AEDT", 39600) TEST_TRANSITION(can_04, "Australia/Canberra", 1207411199, "AEDT", 39600) TEST_TRANSITION(can_05, "Australia/Canberra", 1207411200, "AEST", 36000) TEST_TRANSITION(can_06, "Australia/Canberra", 1207411201, "AEST", 36000) TEST_TRANSITION(can_07, "Australia/Canberra", 1223135999, "AEST", 36000) TEST_TRANSITION(can_08, "Australia/Canberra", 1223136000, "AEDT", 39600) TEST_TRANSITION(can_09, "Australia/Canberra", 1223136001, "AEDT", 39600) TEST_TRANSITION(can_10, "Australia/Canberra", 1238860799, "AEDT", 39600) TEST_TRANSITION(can_11, "Australia/Canberra", 1238860800, "AEST", 36000) TEST_TRANSITION(can_12, "Australia/Canberra", 1238860801, "AEST", 36000) TEST_EXISTS(lh_00, "Australia/Lord_Howe") TEST_TRANSITION(lh_01, "Australia/Lord_Howe", 1207407599, "+11", 39600) TEST_TRANSITION(lh_02, "Australia/Lord_Howe", 1207407600, "+1030", 37800) TEST_TRANSITION(lh_03, "Australia/Lord_Howe", 1207407601, "+1030", 37800) TEST_TRANSITION(lh_04, "Australia/Lord_Howe", 1317482999, "+1030", 37800) TEST_TRANSITION(lh_05, "Australia/Lord_Howe", 1317483000, "+11", 39600) TEST_TRANSITION(lh_06, "Australia/Lord_Howe", 1317483001, "+11", 39600) TEST_TRANSITION(lh_07, "Australia/Lord_Howe", 1365260399, "+11", 39600) TEST_TRANSITION(lh_08, "Australia/Lord_Howe", 1365260400, "+1030", 37800) TEST_TRANSITION(lh_09, "Australia/Lord_Howe", 1365260401, "+1030", 37800) // local new year 2011 TEST_TRANSITION(lh_10, "Australia/Lord_Howe", 1293800399, "+11", 39600) TEST_TRANSITION(lh_11, "Australia/Lord_Howe", 1293800400, "+11", 39600) TEST_TRANSITION(lh_12, "Australia/Lord_Howe", 1293800401, "+11", 39600) // UT new year 2011 TEST_TRANSITION(lh_13, "Australia/Lord_Howe", 1293839999, "+11", 39600) TEST_TRANSITION(lh_14, "Australia/Lord_Howe", 1293840000, "+11", 39600) TEST_TRANSITION(lh_15, "Australia/Lord_Howe", 1293840001, "+11", 39600) <|endoftext|>
<commit_before>/* \brief A tool to collect various counts of subsets of Solr records. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2016-2018, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include <ctime> #include "DbConnection.h" #include "DnsUtil.h" #include "FileUtil.h" #include "IniFile.h" #include "JSON.h" #include "Solr.h" #include "TextUtil.h" #include "TimeUtil.h" #include "util.h" namespace { const std::string RELBIB_EXTRA(" AND is_religious_studies:1"); void Usage() { std::cerr << "Usage: " << ::progname << " system_type output_file\n"; std::exit(EXIT_FAILURE); } void IssueQueryAndWriteOutput(const std::string &query, const std::string &system_type, const std::string &category, const std::string &variable, DbConnection * const db_connection) { static const time_t JOB_START_TIME(std::time(nullptr)); static const std::string HOSTNAME(DnsUtil::GetHostname()); std::string json_result, err_msg; if (not Solr::Query(query, /* fields = */"", &json_result, &err_msg, "localhost:8080", /* timeout in seconds = */Solr::DEFAULT_TIMEOUT, Solr::JSON, /* max_no_of_rows = */0)) LOG_ERROR("Solr query \"" + query + "\" failed! (" + err_msg + ")"); JSON::Parser parser(json_result); std::shared_ptr<JSON::JSONNode> tree_root; if (not parser.parse(&tree_root)) LOG_ERROR("JSON parser failed: " + parser.getErrorMessage()); const time_t NOW(std::time(nullptr)); db_connection->queryOrDie("INSERT INTO datenvolumen SET id_lauf=" + std::to_string(JOB_START_TIME) + ", timestamp=" + std::to_string(NOW) + ", Quellrechner='" + HOSTNAME + "', Zielrechner='" + HOSTNAME + "', Systemtyp='" + system_type + "', Kategorie='" + category + "', Unterkategorie='" + variable + ", value=" + std::to_string(JSON::LookupInteger("/response/numFound", tree_root))); } void CollectGeneralStats(const std::string &system_type, DbConnection * const db_connection) { const std::string EXTRA(system_type == "relbib" ? RELBIB_EXTRA : ""); IssueQueryAndWriteOutput("*:*" + EXTRA, system_type, "Gesamt", "Gesamttreffer", db_connection); IssueQueryAndWriteOutput("format:Book" + EXTRA, system_type, "Format", "Buch", db_connection); IssueQueryAndWriteOutput("format:Article" + EXTRA, system_type, "Format", "Artikel", db_connection); IssueQueryAndWriteOutput("mediatype:Electronic" + EXTRA, system_type, "Medientyp", "elektronisch", db_connection); IssueQueryAndWriteOutput("mediatype:Non-Electronic" + EXTRA, system_type, "Medientyp", "non-elektronisch", db_connection); } void CollectKrimDokSpecificStats(DbConnection * const db_connection) { IssueQueryAndWriteOutput("language:German", "krimdok", "Sprache", "Deutsch", db_connection); IssueQueryAndWriteOutput("language:English", "krimdok", "Sprache", "Englisch", db_connection); } void EmitNotationStats(const char notation_group, const std::string &system_type, const std::string &label, DbConnection * const db_connection) { const std::string EXTRA(system_type == "relbib" ? RELBIB_EXTRA : ""); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[1975 TO 2000]" + EXTRA, system_type, "IxTheo Notationen", label + "(Alle Medienarten, 1975-2000)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[2001 TO *]" + EXTRA, system_type, "IxTheo Notationen", label + "(Alle Medienarten, 2001-heute)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[1975 TO 2000] AND format:Book" + EXTRA, system_type, "IxTheo Notationen", label + "(Bücher, 1975-2000)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[2001 TO *] AND format:Book" + EXTRA, system_type, "IxTheo Notationen", label + "(Bücher, 2001-heute)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[1975 TO 2000] AND format:Article" + EXTRA, system_type, "IxTheo Notationen", label + "(Bücher, 1975-2000)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[2001 TO *] AND format:Article" + EXTRA, system_type, "IxTheo Notationen", label + "(Aufsätze, 2001-heute)", db_connection); } void CollectIxTheoOrRelBibSpecificStats(const std::string &system_type, DbConnection * const db_connection) { const std::string EXTRA(system_type == "relbib" ? RELBIB_EXTRA : ""); IssueQueryAndWriteOutput("dewey-raw:*" + EXTRA, system_type, "DDC", "Anzahl der Datensätze", db_connection); IssueQueryAndWriteOutput("rvk:*" + EXTRA, system_type, "RVK", "Anzahl der Datensätze", db_connection); IssueQueryAndWriteOutput("is_open_access:open-access" + EXTRA, system_type, "Open Access", "ja", db_connection); IssueQueryAndWriteOutput("is_open_access:non-open-access" + EXTRA, system_type, "Open Access", "nein", db_connection); IssueQueryAndWriteOutput("language:German" + EXTRA, system_type, "Sprache", "Deutsch", db_connection); IssueQueryAndWriteOutput("language:English" + EXTRA, system_type, "Sprache", "Englisch", db_connection); IssueQueryAndWriteOutput("language:French" + EXTRA, system_type, "Sprache", "Französisch", db_connection); IssueQueryAndWriteOutput("language:Italian" + EXTRA, system_type, "Sprache", "Italienisch", db_connection); IssueQueryAndWriteOutput("language:Latin" + EXTRA, system_type, "Sprache", "Latein", db_connection); IssueQueryAndWriteOutput("language:Spanish" + EXTRA, system_type, "Sprache", "Spanisch", db_connection); IssueQueryAndWriteOutput("language:Dutch" + EXTRA, system_type, "Sprache", "Holländisch", db_connection); IssueQueryAndWriteOutput("language:\"Ancient Greek\"" + EXTRA, system_type, "Sprache", "Altgriechisch", db_connection); IssueQueryAndWriteOutput("language:Hebrew" + EXTRA, system_type, "Sprache", "Hebräisch", db_connection); IssueQueryAndWriteOutput("language:Portugese" + EXTRA, system_type, "Sprache", "Portugiesisch", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:*" + EXTRA, system_type, "IxTheo Notationen", "Mit Notation", db_connection); IssueQueryAndWriteOutput("-ixtheo_notation:*" + EXTRA, system_type, "IxTheo Notationen", "Ohne Notation", db_connection); EmitNotationStats('A', system_type, "Religionswissenschaft allgemein", db_connection); EmitNotationStats('B', system_type, "Einzelne Religionen", db_connection); EmitNotationStats('C', system_type, "Christentum", db_connection); EmitNotationStats('F', system_type, "Christliche Theologie", db_connection); EmitNotationStats('H', system_type, "Bibel; Bibelwissenschaft", db_connection); EmitNotationStats('K', system_type, "Kirchen- und Theologiegeschichte; Konfessionskunde", db_connection); EmitNotationStats('N', system_type, "Systematische Theologie", db_connection); EmitNotationStats('R', system_type, "Praktische Theologie", db_connection); EmitNotationStats('S', system_type, "Kirchenrecht", db_connection); EmitNotationStats('T', system_type, "(Profan-) Geschichte", db_connection); EmitNotationStats('V', system_type, "Philosophie", db_connection); EmitNotationStats('X', system_type, "Recht allgemein", db_connection); EmitNotationStats('Z', system_type, "Sozialwissenschaften", db_connection); } } // unnamed namespace int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 3) Usage(); const std::string system_type(argv[1]); if (system_type != "ixtheo" and system_type != "relbib" and system_type != "krimdok") LOG_ERROR("system type must be one of {ixtheo, relbib, krimdok}!"); std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[2])); try { const IniFile ini_file("/usr/local/var/lib/tuelib/collect_solr_stats_data.ini"); DbConnection db_connection(ini_file); CollectGeneralStats(system_type, &db_connection); if (system_type == "krimdok") CollectKrimDokSpecificStats(&db_connection); else CollectIxTheoOrRelBibSpecificStats(system_type, &db_connection); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } } <commit_msg>Fixed the table name.<commit_after>/* \brief A tool to collect various counts of subsets of Solr records. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2016-2018, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include <ctime> #include "DbConnection.h" #include "DnsUtil.h" #include "FileUtil.h" #include "IniFile.h" #include "JSON.h" #include "Solr.h" #include "TextUtil.h" #include "TimeUtil.h" #include "util.h" namespace { const std::string RELBIB_EXTRA(" AND is_religious_studies:1"); void Usage() { std::cerr << "Usage: " << ::progname << " system_type output_file\n"; std::exit(EXIT_FAILURE); } void IssueQueryAndWriteOutput(const std::string &query, const std::string &system_type, const std::string &category, const std::string &variable, DbConnection * const db_connection) { static const time_t JOB_START_TIME(std::time(nullptr)); static const std::string HOSTNAME(DnsUtil::GetHostname()); std::string json_result, err_msg; if (not Solr::Query(query, /* fields = */"", &json_result, &err_msg, "localhost:8080", /* timeout in seconds = */Solr::DEFAULT_TIMEOUT, Solr::JSON, /* max_no_of_rows = */0)) LOG_ERROR("Solr query \"" + query + "\" failed! (" + err_msg + ")"); JSON::Parser parser(json_result); std::shared_ptr<JSON::JSONNode> tree_root; if (not parser.parse(&tree_root)) LOG_ERROR("JSON parser failed: " + parser.getErrorMessage()); const time_t NOW(std::time(nullptr)); db_connection->queryOrDie("INSERT INTO solr SET id_lauf=" + std::to_string(JOB_START_TIME) + ", timestamp=" + std::to_string(NOW) + ", Quellrechner='" + HOSTNAME + "', Zielrechner='" + HOSTNAME + "', Systemtyp='" + system_type + "', Kategorie='" + category + "', Unterkategorie='" + variable + ", value=" + std::to_string(JSON::LookupInteger("/response/numFound", tree_root))); } void CollectGeneralStats(const std::string &system_type, DbConnection * const db_connection) { const std::string EXTRA(system_type == "relbib" ? RELBIB_EXTRA : ""); IssueQueryAndWriteOutput("*:*" + EXTRA, system_type, "Gesamt", "Gesamttreffer", db_connection); IssueQueryAndWriteOutput("format:Book" + EXTRA, system_type, "Format", "Buch", db_connection); IssueQueryAndWriteOutput("format:Article" + EXTRA, system_type, "Format", "Artikel", db_connection); IssueQueryAndWriteOutput("mediatype:Electronic" + EXTRA, system_type, "Medientyp", "elektronisch", db_connection); IssueQueryAndWriteOutput("mediatype:Non-Electronic" + EXTRA, system_type, "Medientyp", "non-elektronisch", db_connection); } void CollectKrimDokSpecificStats(DbConnection * const db_connection) { IssueQueryAndWriteOutput("language:German", "krimdok", "Sprache", "Deutsch", db_connection); IssueQueryAndWriteOutput("language:English", "krimdok", "Sprache", "Englisch", db_connection); } void EmitNotationStats(const char notation_group, const std::string &system_type, const std::string &label, DbConnection * const db_connection) { const std::string EXTRA(system_type == "relbib" ? RELBIB_EXTRA : ""); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[1975 TO 2000]" + EXTRA, system_type, "IxTheo Notationen", label + "(Alle Medienarten, 1975-2000)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[2001 TO *]" + EXTRA, system_type, "IxTheo Notationen", label + "(Alle Medienarten, 2001-heute)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[1975 TO 2000] AND format:Book" + EXTRA, system_type, "IxTheo Notationen", label + "(Bücher, 1975-2000)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[2001 TO *] AND format:Book" + EXTRA, system_type, "IxTheo Notationen", label + "(Bücher, 2001-heute)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[1975 TO 2000] AND format:Article" + EXTRA, system_type, "IxTheo Notationen", label + "(Bücher, 1975-2000)", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:" + std::string(1, notation_group) + "* AND publishDate:[2001 TO *] AND format:Article" + EXTRA, system_type, "IxTheo Notationen", label + "(Aufsätze, 2001-heute)", db_connection); } void CollectIxTheoOrRelBibSpecificStats(const std::string &system_type, DbConnection * const db_connection) { const std::string EXTRA(system_type == "relbib" ? RELBIB_EXTRA : ""); IssueQueryAndWriteOutput("dewey-raw:*" + EXTRA, system_type, "DDC", "Anzahl der Datensätze", db_connection); IssueQueryAndWriteOutput("rvk:*" + EXTRA, system_type, "RVK", "Anzahl der Datensätze", db_connection); IssueQueryAndWriteOutput("is_open_access:open-access" + EXTRA, system_type, "Open Access", "ja", db_connection); IssueQueryAndWriteOutput("is_open_access:non-open-access" + EXTRA, system_type, "Open Access", "nein", db_connection); IssueQueryAndWriteOutput("language:German" + EXTRA, system_type, "Sprache", "Deutsch", db_connection); IssueQueryAndWriteOutput("language:English" + EXTRA, system_type, "Sprache", "Englisch", db_connection); IssueQueryAndWriteOutput("language:French" + EXTRA, system_type, "Sprache", "Französisch", db_connection); IssueQueryAndWriteOutput("language:Italian" + EXTRA, system_type, "Sprache", "Italienisch", db_connection); IssueQueryAndWriteOutput("language:Latin" + EXTRA, system_type, "Sprache", "Latein", db_connection); IssueQueryAndWriteOutput("language:Spanish" + EXTRA, system_type, "Sprache", "Spanisch", db_connection); IssueQueryAndWriteOutput("language:Dutch" + EXTRA, system_type, "Sprache", "Holländisch", db_connection); IssueQueryAndWriteOutput("language:\"Ancient Greek\"" + EXTRA, system_type, "Sprache", "Altgriechisch", db_connection); IssueQueryAndWriteOutput("language:Hebrew" + EXTRA, system_type, "Sprache", "Hebräisch", db_connection); IssueQueryAndWriteOutput("language:Portugese" + EXTRA, system_type, "Sprache", "Portugiesisch", db_connection); IssueQueryAndWriteOutput("ixtheo_notation:*" + EXTRA, system_type, "IxTheo Notationen", "Mit Notation", db_connection); IssueQueryAndWriteOutput("-ixtheo_notation:*" + EXTRA, system_type, "IxTheo Notationen", "Ohne Notation", db_connection); EmitNotationStats('A', system_type, "Religionswissenschaft allgemein", db_connection); EmitNotationStats('B', system_type, "Einzelne Religionen", db_connection); EmitNotationStats('C', system_type, "Christentum", db_connection); EmitNotationStats('F', system_type, "Christliche Theologie", db_connection); EmitNotationStats('H', system_type, "Bibel; Bibelwissenschaft", db_connection); EmitNotationStats('K', system_type, "Kirchen- und Theologiegeschichte; Konfessionskunde", db_connection); EmitNotationStats('N', system_type, "Systematische Theologie", db_connection); EmitNotationStats('R', system_type, "Praktische Theologie", db_connection); EmitNotationStats('S', system_type, "Kirchenrecht", db_connection); EmitNotationStats('T', system_type, "(Profan-) Geschichte", db_connection); EmitNotationStats('V', system_type, "Philosophie", db_connection); EmitNotationStats('X', system_type, "Recht allgemein", db_connection); EmitNotationStats('Z', system_type, "Sozialwissenschaften", db_connection); } } // unnamed namespace int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 3) Usage(); const std::string system_type(argv[1]); if (system_type != "ixtheo" and system_type != "relbib" and system_type != "krimdok") LOG_ERROR("system type must be one of {ixtheo, relbib, krimdok}!"); std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[2])); try { const IniFile ini_file("/usr/local/var/lib/tuelib/collect_solr_stats_data.ini"); DbConnection db_connection(ini_file); CollectGeneralStats(system_type, &db_connection); if (system_type == "krimdok") CollectKrimDokSpecificStats(&db_connection); else CollectIxTheoOrRelBibSpecificStats(system_type, &db_connection); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/io/compressed.h" #include <algorithm> #include <cstring> #include <memory> #include <mutex> #include <string> #include <utility> #include "arrow/buffer.h" #include "arrow/memory_pool.h" #include "arrow/status.h" #include "arrow/util/compression.h" #include "arrow/util/logging.h" namespace arrow { using util::Codec; using util::Compressor; using util::Decompressor; namespace io { // ---------------------------------------------------------------------- // CompressedOutputStream implementation class CompressedOutputStream::Impl { public: Impl(MemoryPool* pool, Codec* codec, const std::shared_ptr<OutputStream>& raw) : pool_(pool), raw_(raw), codec_(codec), is_open_(true) {} ~Impl() { DCHECK(Close().ok()); } Status Init() { RETURN_NOT_OK(codec_->MakeCompressor(&compressor_)); RETURN_NOT_OK(AllocateResizableBuffer(pool_, kChunkSize, &compressed_)); compressed_pos_ = 0; return Status::OK(); } Status Tell(int64_t* position) const { return Status::NotImplemented("Cannot tell() a compressed stream"); } std::shared_ptr<OutputStream> raw() const { return raw_; } Status FlushCompressed() { if (compressed_pos_ > 0) { RETURN_NOT_OK(raw_->Write(compressed_->data(), compressed_pos_)); compressed_pos_ = 0; } return Status::OK(); } Status Write(const void* data, int64_t nbytes) { std::lock_guard<std::mutex> guard(lock_); auto input = reinterpret_cast<const uint8_t*>(data); while (nbytes > 0) { int64_t bytes_read, bytes_written; int64_t input_len = nbytes; int64_t output_len = compressed_->size() - compressed_pos_; uint8_t* output = compressed_->mutable_data() + compressed_pos_; RETURN_NOT_OK(compressor_->Compress(input_len, input, output_len, output, &bytes_read, &bytes_written)); compressed_pos_ += bytes_written; if (bytes_read == 0) { // Not enough output, try to flush it and retry if (compressed_pos_ > 0) { RETURN_NOT_OK(FlushCompressed()); output_len = compressed_->size() - compressed_pos_; output = compressed_->mutable_data() + compressed_pos_; RETURN_NOT_OK(compressor_->Compress(input_len, input, output_len, output, &bytes_read, &bytes_written)); compressed_pos_ += bytes_written; } } input += bytes_read; nbytes -= bytes_read; if (compressed_pos_ == compressed_->size()) { // Output buffer full, flush it RETURN_NOT_OK(FlushCompressed()); } if (bytes_read == 0) { // Need to enlarge output buffer RETURN_NOT_OK(compressed_->Resize(compressed_->size() * 2)); } } return Status::OK(); } Status Flush() { std::lock_guard<std::mutex> guard(lock_); while (true) { // Flush compressor int64_t bytes_written; bool should_retry; int64_t output_len = compressed_->size() - compressed_pos_; uint8_t* output = compressed_->mutable_data() + compressed_pos_; RETURN_NOT_OK( compressor_->Flush(output_len, output, &bytes_written, &should_retry)); compressed_pos_ += bytes_written; // Flush compressed output RETURN_NOT_OK(FlushCompressed()); if (should_retry) { // Need to enlarge output buffer RETURN_NOT_OK(compressed_->Resize(compressed_->size() * 2)); } else { break; } } return Status::OK(); } Status FinalizeCompression() { while (true) { // Try to end compressor int64_t bytes_written; bool should_retry; int64_t output_len = compressed_->size() - compressed_pos_; uint8_t* output = compressed_->mutable_data() + compressed_pos_; RETURN_NOT_OK(compressor_->End(output_len, output, &bytes_written, &should_retry)); compressed_pos_ += bytes_written; // Flush compressed output RETURN_NOT_OK(FlushCompressed()); if (should_retry) { // Need to enlarge output buffer RETURN_NOT_OK(compressed_->Resize(compressed_->size() * 2)); } else { // Done break; } } return Status::OK(); } Status Close() { std::lock_guard<std::mutex> guard(lock_); if (is_open_) { is_open_ = false; RETURN_NOT_OK(FinalizeCompression()); return raw_->Close(); } else { return Status::OK(); } } bool closed() { std::lock_guard<std::mutex> guard(lock_); return !is_open_; } private: // Write 64 KB compressed data at a time static const int64_t kChunkSize = 64 * 1024; MemoryPool* pool_; std::shared_ptr<OutputStream> raw_; Codec* codec_; bool is_open_; std::shared_ptr<Compressor> compressor_; std::shared_ptr<ResizableBuffer> compressed_; int64_t compressed_pos_; mutable std::mutex lock_; }; Status CompressedOutputStream::Make(util::Codec* codec, const std::shared_ptr<OutputStream>& raw, std::shared_ptr<CompressedOutputStream>* out) { return Make(default_memory_pool(), codec, raw, out); } Status CompressedOutputStream::Make(MemoryPool* pool, util::Codec* codec, const std::shared_ptr<OutputStream>& raw, std::shared_ptr<CompressedOutputStream>* out) { std::shared_ptr<CompressedOutputStream> res(new CompressedOutputStream); res->impl_ = std::unique_ptr<Impl>(new Impl(pool, codec, std::move(raw))); RETURN_NOT_OK(res->impl_->Init()); *out = res; return Status::OK(); } CompressedOutputStream::~CompressedOutputStream() {} Status CompressedOutputStream::Close() { return impl_->Close(); } bool CompressedOutputStream::closed() const { return impl_->closed(); } Status CompressedOutputStream::Tell(int64_t* position) const { return impl_->Tell(position); } Status CompressedOutputStream::Write(const void* data, int64_t nbytes) { return impl_->Write(data, nbytes); } Status CompressedOutputStream::Flush() { return impl_->Flush(); } // ---------------------------------------------------------------------- // CompressedInputStream implementation class CompressedInputStream::Impl { public: Impl(MemoryPool* pool, Codec* codec, const std::shared_ptr<InputStream>& raw) : pool_(pool), raw_(raw), codec_(codec), is_open_(true) {} Status Init() { RETURN_NOT_OK(codec_->MakeDecompressor(&decompressor_)); return Status::OK(); } ~Impl() { DCHECK(Close().ok()); } Status Close() { std::lock_guard<std::mutex> guard(lock_); if (is_open_) { is_open_ = false; return raw_->Close(); } else { return Status::OK(); } } bool closed() { std::lock_guard<std::mutex> guard(lock_); return !is_open_; } Status Tell(int64_t* position) const { return Status::NotImplemented("Cannot tell() a compressed stream"); } // Read compressed data if necessary Status EnsureCompressedData() { int64_t compressed_avail = compressed_ ? compressed_->size() - compressed_pos_ : 0; if (compressed_avail == 0) { // No compressed data available, read a full chunk RETURN_NOT_OK(raw_->Read(kChunkSize, &compressed_)); compressed_pos_ = 0; } return Status::OK(); } Status DecompressData() { int64_t decompress_size = kDecompressSize; while (true) { RETURN_NOT_OK(AllocateResizableBuffer(pool_, decompress_size, &decompressed_)); decompressed_pos_ = 0; bool need_more_output; int64_t bytes_read, bytes_written; int64_t input_len = compressed_->size() - compressed_pos_; const uint8_t* input = compressed_->data() + compressed_pos_; int64_t output_len = decompressed_->size(); uint8_t* output = decompressed_->mutable_data(); RETURN_NOT_OK(decompressor_->Decompress(input_len, input, output_len, output, &bytes_read, &bytes_written, &need_more_output)); compressed_pos_ += bytes_read; if (bytes_written > 0 || !need_more_output || input_len == 0) { RETURN_NOT_OK(decompressed_->Resize(bytes_written)); break; } DCHECK_EQ(bytes_written, 0); // Need to enlarge output buffer decompress_size *= 2; } return Status::OK(); } Status Read(int64_t nbytes, int64_t* bytes_read, void* out) { std::lock_guard<std::mutex> guard(lock_); *bytes_read = 0; auto out_data = reinterpret_cast<uint8_t*>(out); while (nbytes > 0) { int64_t avail = decompressed_ ? (decompressed_->size() - decompressed_pos_) : 0; if (avail > 0) { // Pending decompressed data is available, use it avail = std::min(avail, nbytes); memcpy(out_data, decompressed_->data() + decompressed_pos_, avail); decompressed_pos_ += avail; out_data += avail; *bytes_read += avail; nbytes -= avail; if (decompressed_pos_ == decompressed_->size()) { // Decompressed data is exhausted, release buffer decompressed_.reset(); } if (nbytes == 0) { // We're done break; } } // At this point, no more decompressed data remains, // so we need to decompress more if (decompressor_->IsFinished()) { break; } // First try to read data from the decompressor if (compressed_) { RETURN_NOT_OK(DecompressData()); } if (!decompressed_ || decompressed_->size() == 0) { // Got nothing, need to read more compressed data RETURN_NOT_OK(EnsureCompressedData()); if (compressed_pos_ == compressed_->size()) { // Compressed stream unexpectedly exhausted return Status::IOError("Truncated compressed stream"); } RETURN_NOT_OK(DecompressData()); } } return Status::OK(); } Status Read(int64_t nbytes, std::shared_ptr<Buffer>* out) { std::shared_ptr<ResizableBuffer> buf; RETURN_NOT_OK(AllocateResizableBuffer(pool_, nbytes, &buf)); int64_t bytes_read; RETURN_NOT_OK(Read(nbytes, &bytes_read, buf->mutable_data())); RETURN_NOT_OK(buf->Resize(bytes_read)); *out = buf; return Status::OK(); } std::shared_ptr<InputStream> raw() const { return raw_; } private: // Read 64 KB compressed data at a time static const int64_t kChunkSize = 64 * 1024; // Decompress 1 MB at a time static const int64_t kDecompressSize = 1024 * 1024; MemoryPool* pool_; std::shared_ptr<InputStream> raw_; Codec* codec_; bool is_open_; std::shared_ptr<Decompressor> decompressor_; std::shared_ptr<Buffer> compressed_; int64_t compressed_pos_; std::shared_ptr<ResizableBuffer> decompressed_; int64_t decompressed_pos_; mutable std::mutex lock_; }; Status CompressedInputStream::Make(Codec* codec, const std::shared_ptr<InputStream>& raw, std::shared_ptr<CompressedInputStream>* out) { return Make(default_memory_pool(), codec, raw, out); } Status CompressedInputStream::Make(MemoryPool* pool, Codec* codec, const std::shared_ptr<InputStream>& raw, std::shared_ptr<CompressedInputStream>* out) { std::shared_ptr<CompressedInputStream> res(new CompressedInputStream); res->impl_ = std::unique_ptr<Impl>(new Impl(pool, codec, std::move(raw))); RETURN_NOT_OK(res->impl_->Init()); *out = res; return Status::OK(); } CompressedInputStream::~CompressedInputStream() {} Status CompressedInputStream::Close() { return impl_->Close(); } bool CompressedInputStream::closed() const { return impl_->closed(); } Status CompressedInputStream::Tell(int64_t* position) const { return impl_->Tell(position); } Status CompressedInputStream::Read(int64_t nbytes, int64_t* bytes_read, void* out) { return impl_->Read(nbytes, bytes_read, out); } Status CompressedInputStream::Read(int64_t nbytes, std::shared_ptr<Buffer>* out) { return impl_->Read(nbytes, out); } std::shared_ptr<InputStream> CompressedInputStream::raw() const { return impl_->raw(); } } // namespace io } // namespace arrow <commit_msg>ARROW-3835: [C++] Add missing arrow::io::CompressedOutputStream::raw() implementation<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/io/compressed.h" #include <algorithm> #include <cstring> #include <memory> #include <mutex> #include <string> #include <utility> #include "arrow/buffer.h" #include "arrow/memory_pool.h" #include "arrow/status.h" #include "arrow/util/compression.h" #include "arrow/util/logging.h" namespace arrow { using util::Codec; using util::Compressor; using util::Decompressor; namespace io { // ---------------------------------------------------------------------- // CompressedOutputStream implementation class CompressedOutputStream::Impl { public: Impl(MemoryPool* pool, Codec* codec, const std::shared_ptr<OutputStream>& raw) : pool_(pool), raw_(raw), codec_(codec), is_open_(true) {} ~Impl() { DCHECK(Close().ok()); } Status Init() { RETURN_NOT_OK(codec_->MakeCompressor(&compressor_)); RETURN_NOT_OK(AllocateResizableBuffer(pool_, kChunkSize, &compressed_)); compressed_pos_ = 0; return Status::OK(); } Status Tell(int64_t* position) const { return Status::NotImplemented("Cannot tell() a compressed stream"); } std::shared_ptr<OutputStream> raw() const { return raw_; } Status FlushCompressed() { if (compressed_pos_ > 0) { RETURN_NOT_OK(raw_->Write(compressed_->data(), compressed_pos_)); compressed_pos_ = 0; } return Status::OK(); } Status Write(const void* data, int64_t nbytes) { std::lock_guard<std::mutex> guard(lock_); auto input = reinterpret_cast<const uint8_t*>(data); while (nbytes > 0) { int64_t bytes_read, bytes_written; int64_t input_len = nbytes; int64_t output_len = compressed_->size() - compressed_pos_; uint8_t* output = compressed_->mutable_data() + compressed_pos_; RETURN_NOT_OK(compressor_->Compress(input_len, input, output_len, output, &bytes_read, &bytes_written)); compressed_pos_ += bytes_written; if (bytes_read == 0) { // Not enough output, try to flush it and retry if (compressed_pos_ > 0) { RETURN_NOT_OK(FlushCompressed()); output_len = compressed_->size() - compressed_pos_; output = compressed_->mutable_data() + compressed_pos_; RETURN_NOT_OK(compressor_->Compress(input_len, input, output_len, output, &bytes_read, &bytes_written)); compressed_pos_ += bytes_written; } } input += bytes_read; nbytes -= bytes_read; if (compressed_pos_ == compressed_->size()) { // Output buffer full, flush it RETURN_NOT_OK(FlushCompressed()); } if (bytes_read == 0) { // Need to enlarge output buffer RETURN_NOT_OK(compressed_->Resize(compressed_->size() * 2)); } } return Status::OK(); } Status Flush() { std::lock_guard<std::mutex> guard(lock_); while (true) { // Flush compressor int64_t bytes_written; bool should_retry; int64_t output_len = compressed_->size() - compressed_pos_; uint8_t* output = compressed_->mutable_data() + compressed_pos_; RETURN_NOT_OK( compressor_->Flush(output_len, output, &bytes_written, &should_retry)); compressed_pos_ += bytes_written; // Flush compressed output RETURN_NOT_OK(FlushCompressed()); if (should_retry) { // Need to enlarge output buffer RETURN_NOT_OK(compressed_->Resize(compressed_->size() * 2)); } else { break; } } return Status::OK(); } Status FinalizeCompression() { while (true) { // Try to end compressor int64_t bytes_written; bool should_retry; int64_t output_len = compressed_->size() - compressed_pos_; uint8_t* output = compressed_->mutable_data() + compressed_pos_; RETURN_NOT_OK(compressor_->End(output_len, output, &bytes_written, &should_retry)); compressed_pos_ += bytes_written; // Flush compressed output RETURN_NOT_OK(FlushCompressed()); if (should_retry) { // Need to enlarge output buffer RETURN_NOT_OK(compressed_->Resize(compressed_->size() * 2)); } else { // Done break; } } return Status::OK(); } Status Close() { std::lock_guard<std::mutex> guard(lock_); if (is_open_) { is_open_ = false; RETURN_NOT_OK(FinalizeCompression()); return raw_->Close(); } else { return Status::OK(); } } bool closed() { std::lock_guard<std::mutex> guard(lock_); return !is_open_; } private: // Write 64 KB compressed data at a time static const int64_t kChunkSize = 64 * 1024; MemoryPool* pool_; std::shared_ptr<OutputStream> raw_; Codec* codec_; bool is_open_; std::shared_ptr<Compressor> compressor_; std::shared_ptr<ResizableBuffer> compressed_; int64_t compressed_pos_; mutable std::mutex lock_; }; Status CompressedOutputStream::Make(util::Codec* codec, const std::shared_ptr<OutputStream>& raw, std::shared_ptr<CompressedOutputStream>* out) { return Make(default_memory_pool(), codec, raw, out); } Status CompressedOutputStream::Make(MemoryPool* pool, util::Codec* codec, const std::shared_ptr<OutputStream>& raw, std::shared_ptr<CompressedOutputStream>* out) { std::shared_ptr<CompressedOutputStream> res(new CompressedOutputStream); res->impl_ = std::unique_ptr<Impl>(new Impl(pool, codec, std::move(raw))); RETURN_NOT_OK(res->impl_->Init()); *out = res; return Status::OK(); } CompressedOutputStream::~CompressedOutputStream() {} Status CompressedOutputStream::Close() { return impl_->Close(); } bool CompressedOutputStream::closed() const { return impl_->closed(); } Status CompressedOutputStream::Tell(int64_t* position) const { return impl_->Tell(position); } Status CompressedOutputStream::Write(const void* data, int64_t nbytes) { return impl_->Write(data, nbytes); } Status CompressedOutputStream::Flush() { return impl_->Flush(); } std::shared_ptr<OutputStream> CompressedOutputStream::raw() const { return impl_->raw(); } // ---------------------------------------------------------------------- // CompressedInputStream implementation class CompressedInputStream::Impl { public: Impl(MemoryPool* pool, Codec* codec, const std::shared_ptr<InputStream>& raw) : pool_(pool), raw_(raw), codec_(codec), is_open_(true) {} Status Init() { RETURN_NOT_OK(codec_->MakeDecompressor(&decompressor_)); return Status::OK(); } ~Impl() { DCHECK(Close().ok()); } Status Close() { std::lock_guard<std::mutex> guard(lock_); if (is_open_) { is_open_ = false; return raw_->Close(); } else { return Status::OK(); } } bool closed() { std::lock_guard<std::mutex> guard(lock_); return !is_open_; } Status Tell(int64_t* position) const { return Status::NotImplemented("Cannot tell() a compressed stream"); } // Read compressed data if necessary Status EnsureCompressedData() { int64_t compressed_avail = compressed_ ? compressed_->size() - compressed_pos_ : 0; if (compressed_avail == 0) { // No compressed data available, read a full chunk RETURN_NOT_OK(raw_->Read(kChunkSize, &compressed_)); compressed_pos_ = 0; } return Status::OK(); } Status DecompressData() { int64_t decompress_size = kDecompressSize; while (true) { RETURN_NOT_OK(AllocateResizableBuffer(pool_, decompress_size, &decompressed_)); decompressed_pos_ = 0; bool need_more_output; int64_t bytes_read, bytes_written; int64_t input_len = compressed_->size() - compressed_pos_; const uint8_t* input = compressed_->data() + compressed_pos_; int64_t output_len = decompressed_->size(); uint8_t* output = decompressed_->mutable_data(); RETURN_NOT_OK(decompressor_->Decompress(input_len, input, output_len, output, &bytes_read, &bytes_written, &need_more_output)); compressed_pos_ += bytes_read; if (bytes_written > 0 || !need_more_output || input_len == 0) { RETURN_NOT_OK(decompressed_->Resize(bytes_written)); break; } DCHECK_EQ(bytes_written, 0); // Need to enlarge output buffer decompress_size *= 2; } return Status::OK(); } Status Read(int64_t nbytes, int64_t* bytes_read, void* out) { std::lock_guard<std::mutex> guard(lock_); *bytes_read = 0; auto out_data = reinterpret_cast<uint8_t*>(out); while (nbytes > 0) { int64_t avail = decompressed_ ? (decompressed_->size() - decompressed_pos_) : 0; if (avail > 0) { // Pending decompressed data is available, use it avail = std::min(avail, nbytes); memcpy(out_data, decompressed_->data() + decompressed_pos_, avail); decompressed_pos_ += avail; out_data += avail; *bytes_read += avail; nbytes -= avail; if (decompressed_pos_ == decompressed_->size()) { // Decompressed data is exhausted, release buffer decompressed_.reset(); } if (nbytes == 0) { // We're done break; } } // At this point, no more decompressed data remains, // so we need to decompress more if (decompressor_->IsFinished()) { break; } // First try to read data from the decompressor if (compressed_) { RETURN_NOT_OK(DecompressData()); } if (!decompressed_ || decompressed_->size() == 0) { // Got nothing, need to read more compressed data RETURN_NOT_OK(EnsureCompressedData()); if (compressed_pos_ == compressed_->size()) { // Compressed stream unexpectedly exhausted return Status::IOError("Truncated compressed stream"); } RETURN_NOT_OK(DecompressData()); } } return Status::OK(); } Status Read(int64_t nbytes, std::shared_ptr<Buffer>* out) { std::shared_ptr<ResizableBuffer> buf; RETURN_NOT_OK(AllocateResizableBuffer(pool_, nbytes, &buf)); int64_t bytes_read; RETURN_NOT_OK(Read(nbytes, &bytes_read, buf->mutable_data())); RETURN_NOT_OK(buf->Resize(bytes_read)); *out = buf; return Status::OK(); } std::shared_ptr<InputStream> raw() const { return raw_; } private: // Read 64 KB compressed data at a time static const int64_t kChunkSize = 64 * 1024; // Decompress 1 MB at a time static const int64_t kDecompressSize = 1024 * 1024; MemoryPool* pool_; std::shared_ptr<InputStream> raw_; Codec* codec_; bool is_open_; std::shared_ptr<Decompressor> decompressor_; std::shared_ptr<Buffer> compressed_; int64_t compressed_pos_; std::shared_ptr<ResizableBuffer> decompressed_; int64_t decompressed_pos_; mutable std::mutex lock_; }; Status CompressedInputStream::Make(Codec* codec, const std::shared_ptr<InputStream>& raw, std::shared_ptr<CompressedInputStream>* out) { return Make(default_memory_pool(), codec, raw, out); } Status CompressedInputStream::Make(MemoryPool* pool, Codec* codec, const std::shared_ptr<InputStream>& raw, std::shared_ptr<CompressedInputStream>* out) { std::shared_ptr<CompressedInputStream> res(new CompressedInputStream); res->impl_ = std::unique_ptr<Impl>(new Impl(pool, codec, std::move(raw))); RETURN_NOT_OK(res->impl_->Init()); *out = res; return Status::OK(); } CompressedInputStream::~CompressedInputStream() {} Status CompressedInputStream::Close() { return impl_->Close(); } bool CompressedInputStream::closed() const { return impl_->closed(); } Status CompressedInputStream::Tell(int64_t* position) const { return impl_->Tell(position); } Status CompressedInputStream::Read(int64_t nbytes, int64_t* bytes_read, void* out) { return impl_->Read(nbytes, bytes_read, out); } Status CompressedInputStream::Read(int64_t nbytes, std::shared_ptr<Buffer>* out) { return impl_->Read(nbytes, out); } std::shared_ptr<InputStream> CompressedInputStream::raw() const { return impl_->raw(); } } // namespace io } // namespace arrow <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginCommandLineArgs // INPUTS: {amst.png} // OUTPUTS: {EdgeDensityOutput.png}, {PrettyEdgeDensityOutput.png} // 3 30 10 1.0 0.01 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example illustrates the use of the // \doxygen{otb}{EdgeDensityImageFilter}. // This filter computes a local density of edges on an image and can // be useful to detect man made objects or urban areas, for // instance. The filter has been implemented in a generic way, so that // the way the edges are detected and the way their density is // computed can be chosen by the user. // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbEdgeDensityImageFilter.h" // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We will also include the header files for the edge detector (a // Canny filter) and the density estimation (a simple count on a // binary image). // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkCannyEdgeDetectionImageFilter.h" #include "otbBinaryImageDensityFunction.h" // Software Guide : EndCodeSnippet int main(int argc, char* argv[] ) { const char * infname = argv[1]; const char * outfname = argv[2]; const char * prettyfilename = argv[3]; const unsigned int radius = atoi(argv[4]); /*--*/ const unsigned int Dimension = 2; typedef float PixelType; /** Variables for the canny detector*/ const PixelType upperThreshold = static_cast<PixelType>(atof(argv[5])); const PixelType lowerThreshold = static_cast<PixelType>(atof(argv[6])); const double variance = atof(argv[7]); const double maximumError = atof(argv[8]); // Software Guide : BeginLatex // // As usual, we start by defining the types for the images, the reader // and the writer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::Image< PixelType, Dimension > ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; // Software Guide : BeginCodeSnippet // Software Guide : BeginLatex // // We define now the type for the function which will be used by the // edge density filter to estimate this density. Here we choose a // function which counts the number of non null pixels per area. The // fucntion takes as template the type of the image to be processed. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::BinaryImageDensityFunction<ImageType> CountFunctionType; // Software Guide : BeginCodeSnippet // Software Guide : BeginLatex // // These {\em non null pixels} will be the result of an edge // detector. We use here the classical Canny edge detector, which is // templated over the input and output image types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::CannyEdgeDetectionImageFilter<ImageType, ImageType> CannyDetectorType; // Software Guide : BeginCodeSnippet // Software Guide : BeginLatex // // Finally, we can define the type for the edge density filter which // takes as template the input image type, the edge detector type, // the count fucntion type and the output image type. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::EdgeDensityImageFilter<ImageType, ImageType, CannyDetectorType, CountFunctionType> EdgeDensityFilterType; /**Instancitation of an object*/ EdgeDensityFilterType::Pointer filter = EdgeDensityFilterType::New(); ReaderType::Pointer reader = ReaderType::New(); CannyDetectorType::Pointer CannyFilter = CannyDetectorType::New(); /** Set The input*/ reader->SetFileName(infname); filter->SetInput(reader->GetOutput()); /** Update the Canny Filter Information*/ CannyFilter->SetUpperThreshold(upperThreshold); CannyFilter->SetLowerThreshold(lowerThreshold); CannyFilter->SetVariance(variance); CannyFilter->SetMaximumError(maximumError); filter->SetDetector(CannyFilter); /** Write the output*/ WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(filter->GetOutput()); writer->Update(); /************* Image for printing **************/ typedef otb::Image< unsigned char, 2 > OutputImageType; typedef itk::RescaleIntensityImageFilter< ImageType, OutputImageType > RescalerType; RescalerType::Pointer rescaler = RescalerType::New(); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); rescaler->SetInput( filter->GetOutput() ); typedef otb::ImageFileWriter< OutputImageType > OutputWriterType; OutputWriterType::Pointer outwriter = OutputWriterType::New(); outwriter->SetFileName( prettyfilename ); outwriter->SetInput( rescaler->GetOutput() ); outwriter->Update(); return EXIT_SUCCESS; } <commit_msg>DOC: Latex added to EdgeDensityExample<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginCommandLineArgs // INPUTS: {suburb2.jpeg} // OUTPUTS: {EdgeDensityOutput.png}, {PrettyEdgeDensityOutput.png} // 3 30 10 1.0 0.01 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example illustrates the use of the // \doxygen{otb}{EdgeDensityImageFilter}. // This filter computes a local density of edges on an image and can // be useful to detect man made objects or urban areas, for // instance. The filter has been implemented in a generic way, so that // the way the edges are detected and the way their density is // computed can be chosen by the user. // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbEdgeDensityImageFilter.h" // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We will also include the header files for the edge detector (a // Canny filter) and the density estimation (a simple count on a // binary image). // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkCannyEdgeDetectionImageFilter.h" #include "otbBinaryImageDensityFunction.h" // Software Guide : EndCodeSnippet int main(int argc, char* argv[] ) { const char * infname = argv[1]; const char * outfname = argv[2]; const char * prettyfilename = argv[3]; const unsigned int radius = atoi(argv[4]); /*--*/ const unsigned int Dimension = 2; typedef float PixelType; /** Variables for the canny detector*/ const PixelType upperThreshold = static_cast<PixelType>(atof(argv[5])); const PixelType lowerThreshold = static_cast<PixelType>(atof(argv[6])); const double variance = atof(argv[7]); const double maximumError = atof(argv[8]); // Software Guide : BeginLatex // // As usual, we start by defining the types for the images, the reader // and the writer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::Image< PixelType, Dimension > ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; // Software Guide : BeginCodeSnippet // Software Guide : BeginLatex // // We define now the type for the function which will be used by the // edge density filter to estimate this density. Here we choose a // function which counts the number of non null pixels per area. The // fucntion takes as template the type of the image to be processed. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::BinaryImageDensityFunction<ImageType> CountFunctionType; // Software Guide : BeginCodeSnippet // Software Guide : BeginLatex // // These {\em non null pixels} will be the result of an edge // detector. We use here the classical Canny edge detector, which is // templated over the input and output image types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::CannyEdgeDetectionImageFilter<ImageType, ImageType> CannyDetectorType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally, we can define the type for the edge density filter which // takes as template the input and output image types, the edge // detector type, and the count fucntion type.. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::EdgeDensityImageFilter<ImageType, ImageType, CannyDetectorType, CountFunctionType> EdgeDensityFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can now instantiate the different processing objects of the // pipeline using the \code{New()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer reader = ReaderType::New(); EdgeDensityFilterType::Pointer filter = EdgeDensityFilterType::New(); CannyDetectorType::Pointer cannyFilter = CannyDetectorType::New(); WriterType::Pointer writer = WriterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The edge detection filter needs to be instantiated because we // need to set its parameters. This is what we do here for the Canny // filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet cannyFilter->SetUpperThreshold(upperThreshold); cannyFilter->SetLowerThreshold(lowerThreshold); cannyFilter->SetVariance(variance); cannyFilter->SetMaximumError(maximumError); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // After that, we can pass the edge detector to the filter which // will use it internally. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetDetector(cannyFilter); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally, we set the file names for the input and the output // images and we plug the pipeline. The \code{Update()} method of // the writer will trigger the processing. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet reader->SetFileName(infname); writer->SetFileName(outfname); filter->SetInput(reader->GetOutput()); writer->SetInput(filter->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Figure~\ref{fig:EDGEDENSITY_FILTER} shows the result of applying // the edge density filter to an image. // \begin{figure} // \center // \includegraphics[width=0.25\textwidth]{suburb2.eps} // \includegraphics[width=0.25\textwidth]{PrettyEdgeDensityOutput.eps} // \itkcaption[Edge Density Filter]{Result of applying the // \doxygen{otb}{EdgeDensityImageFilter} to an image. From left to right : // original image, edge density.} // \label{fig:EDGEDENSITY_FILTER} // \end{figure} // // Software Guide : EndLatex /************* Image for printing **************/ typedef otb::Image< unsigned char, 2 > OutputImageType; typedef itk::RescaleIntensityImageFilter< ImageType, OutputImageType > RescalerType; RescalerType::Pointer rescaler = RescalerType::New(); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); rescaler->SetInput( filter->GetOutput() ); typedef otb::ImageFileWriter< OutputImageType > OutputWriterType; OutputWriterType::Pointer outwriter = OutputWriterType::New(); outwriter->SetFileName( prettyfilename ); outwriter->SetInput( rescaler->GetOutput() ); outwriter->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id: plugin-test.cpp 23401 2015-06-25 15:00:31Z okramer $ #include "../src/ossimCsm3Loader.h" #include <ossim/base/ossimPreferences.h> #define TEST_READER false int main(int argc, char** argv) { ossimPreferences::instance()->loadPreferences(); ossimCsm3Loader ocl; return 0; } <commit_msg>Added a print out ot actually see the plugins that were loaded<commit_after>//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id: plugin-test.cpp 23401 2015-06-25 15:00:31Z okramer $ #include "../src/ossimCsm3Loader.h" #include <ossim/base/ossimPreferences.h> #define TEST_READER false int main(int argc, char** argv) { ossimPreferences::instance()->loadPreferences(); ossimCsm3Loader ocl; std::vector<std::string> plugins = ocl.getAvailablePluginNames(); for(std::vector<std::string>::const_iterator iter = plugins.begin(); iter!=plugins.end(); ++iter) { std::cout << "Plugin: "<< *iter << "\n"; } return 0; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, 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 Willow Garage, 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. * * Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com) */ #ifndef _PCL_TEST_GPU_OCTREE_DATAGEN_ #define _PCL_TEST_GPU_OCTREE_DATAGEN_ #include <vector> #include <algorithm> #include <iostream> #include <opencv2/core/core.hpp> #include <Eigen/StdVector> EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(pcl::PointXYZ) struct DataGenerator { typedef pcl::gpu::Octree::PointType PointType; size_t data_size; size_t tests_num; float cube_size; float max_radius; float shared_radius; std::vector<PointType> points; std::vector<PointType> queries; std::vector<float> radiuses; std::vector< std::vector<int> > bfresutls; DataGenerator() : data_size(871000), tests_num(10000), cube_size(1024.f) { max_radius = cube_size/15.f; shared_radius = cube_size/20.f; } void operator()() { cv::RNG& rng = cv::theRNG(); points.resize(data_size); for(size_t i = 0; i < data_size; ++i) { points[i].x = (float)rng * cube_size; points[i].y = (float)rng * cube_size; points[i].z = (float)rng * cube_size; } queries.resize(tests_num); radiuses.resize(tests_num); for (size_t i = 0; i < tests_num; ++i) { queries[i].x = (float)rng * cube_size; queries[i].y = (float)rng * cube_size; queries[i].z = (float)rng * cube_size; radiuses[i] = (float)rng * max_radius; }; } void bruteForceSearch(bool log = false, float radius = -1.f) { if (log) std::cout << "BruteForceSearch"; int value100 = std::min<int>(tests_num, 50); int step = tests_num/value100; bfresutls.resize(tests_num); for(size_t i = 0; i < tests_num; ++i) { if (log && i % step == 0) std::cout << "."; std::vector<int>& curr_res = bfresutls[i]; curr_res.clear(); float query_radius = radius > 0 ? radius : radiuses[i]; const PointType& query = queries[i]; for(size_t ind = 0; ind < points.size(); ++ind) { const PointType& point = points[ind]; float dx = query.x - point.x; float dy = query.y - point.y; float dz = query.z - point.z; if (dx*dx + dy*dy + dz*dz < query_radius * query_radius) curr_res.push_back(ind); } std::sort(curr_res.begin(), curr_res.end()); } if (log) std::cout << "Done" << std::endl; } void printParams() const { std::cout << "Points number = " << data_size << std::endl; std::cout << "Queries number = " << tests_num << std::endl; std::cout << "Cube size = " << cube_size << std::endl; std::cout << "Max radius = " << max_radius << std::endl; std::cout << "Shared radius = " << shared_radius << std::endl; } template<typename Dst> struct ConvPoint { Dst operator()(const PointType& src) const { Dst dst; dst.x = src.x; dst.y = src.y; dst.z = src.z; return dst; } }; }; #endif /* _PCL_TEST_GPU_OCTREE_DATAGEN_ */ <commit_msg>broken ?<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, 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 Willow Garage, 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. * * Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com) */ #ifndef _PCL_TEST_GPU_OCTREE_DATAGEN_ #define _PCL_TEST_GPU_OCTREE_DATAGEN_ #include <vector> #include <algorithm> #include <iostream> #include <opencv2/core/core.hpp> #include <Eigen/StdVector> /** BROKEN EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(pcl::PointXYZ)*/ struct DataGenerator { typedef pcl::gpu::Octree::PointType PointType; size_t data_size; size_t tests_num; float cube_size; float max_radius; float shared_radius; std::vector<PointType> points; std::vector<PointType> queries; std::vector<float> radiuses; std::vector< std::vector<int> > bfresutls; DataGenerator() : data_size(871000), tests_num(10000), cube_size(1024.f) { max_radius = cube_size/15.f; shared_radius = cube_size/20.f; } void operator()() { cv::RNG& rng = cv::theRNG(); points.resize(data_size); for(size_t i = 0; i < data_size; ++i) { points[i].x = (float)rng * cube_size; points[i].y = (float)rng * cube_size; points[i].z = (float)rng * cube_size; } queries.resize(tests_num); radiuses.resize(tests_num); for (size_t i = 0; i < tests_num; ++i) { queries[i].x = (float)rng * cube_size; queries[i].y = (float)rng * cube_size; queries[i].z = (float)rng * cube_size; radiuses[i] = (float)rng * max_radius; }; } void bruteForceSearch(bool log = false, float radius = -1.f) { if (log) std::cout << "BruteForceSearch"; int value100 = std::min<int>(tests_num, 50); int step = tests_num/value100; bfresutls.resize(tests_num); for(size_t i = 0; i < tests_num; ++i) { if (log && i % step == 0) std::cout << "."; std::vector<int>& curr_res = bfresutls[i]; curr_res.clear(); float query_radius = radius > 0 ? radius : radiuses[i]; const PointType& query = queries[i]; for(size_t ind = 0; ind < points.size(); ++ind) { const PointType& point = points[ind]; float dx = query.x - point.x; float dy = query.y - point.y; float dz = query.z - point.z; if (dx*dx + dy*dy + dz*dz < query_radius * query_radius) curr_res.push_back(ind); } std::sort(curr_res.begin(), curr_res.end()); } if (log) std::cout << "Done" << std::endl; } void printParams() const { std::cout << "Points number = " << data_size << std::endl; std::cout << "Queries number = " << tests_num << std::endl; std::cout << "Cube size = " << cube_size << std::endl; std::cout << "Max radius = " << max_radius << std::endl; std::cout << "Shared radius = " << shared_radius << std::endl; } template<typename Dst> struct ConvPoint { Dst operator()(const PointType& src) const { Dst dst; dst.x = src.x; dst.y = src.y; dst.z = src.z; return dst; } }; }; #endif /* _PCL_TEST_GPU_OCTREE_DATAGEN_ */ <|endoftext|>
<commit_before><commit_msg>fdo#48110 disable the "Automatically" currency unless already used<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <map> #include <mutex> #include <string> #include <vector> #include <openssl/ssl.h> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/property_tree/ini_parser.hpp> #include <boost/signals2.hpp> #include "config/config.h" #include "logging/logging.h" #include "primary/aktualizr.h" #include "uptane/secondaryfactory.h" #include "utilities/utils.h" namespace bpo = boost::program_options; std::map<std::string, unsigned int> progress; std::mutex pending_ecus_mutex; unsigned int pending_ecus; void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) { if (vm.count("help") != 0) { std::cout << description << '\n'; std::cout << "Available commands: Shutdown, SendDeviceData, CheckUpdates, Download, Install, CampaignCheck\n"; exit(EXIT_SUCCESS); } if (vm.count("version") != 0) { std::cout << "Current hmi_stub version is: " << AKTUALIZR_VERSION << "\n"; exit(EXIT_SUCCESS); } } bpo::variables_map parse_options(int argc, char *argv[]) { bpo::options_description description("HMI stub interface for libaktualizr"); // clang-format off // Try to keep these options in the same order as Config::updateFromCommandLine(). // The first three are commandline only. description.add_options() ("help,h", "print usage") ("version,v", "Current aktualizr version") ("config,c", bpo::value<std::vector<boost::filesystem::path> >()->composing(), "configuration file or directory") ("secondary-configs-dir", bpo::value<boost::filesystem::path>(), "directory containing seconday ECU configuration files") ("loglevel", bpo::value<int>(), "set log level 0-5 (trace, debug, info, warning, error, fatal)"); // clang-format on bpo::variables_map vm; std::vector<std::string> unregistered_options; try { bpo::basic_parsed_options<char> parsed_options = bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run(); bpo::store(parsed_options, vm); check_info_options(description, vm); bpo::notify(vm); unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional); if (vm.count("help") == 0 && !unregistered_options.empty()) { std::cout << description << "\n"; exit(EXIT_FAILURE); } } catch (const bpo::required_option &ex) { // print the error and append the default commandline option description std::cout << ex.what() << std::endl << description; exit(EXIT_FAILURE); } catch (const bpo::error &ex) { check_info_options(description, vm); // log boost error LOG_ERROR << "boost command line option error: " << ex.what(); // print the error message to the standard output too, as the user provided // a non-supported commandline option std::cout << ex.what() << '\n'; // set the returnValue, thereby ctest will recognize // that something went wrong exit(EXIT_FAILURE); } return vm; } void process_event(const std::shared_ptr<event::BaseEvent> &event) { if (event->variant == "DownloadProgressReport") { const auto download_progress = dynamic_cast<event::DownloadProgressReport *>(event.get()); if (progress.find(download_progress->target.sha256Hash()) == progress.end()) { progress[download_progress->target.sha256Hash()] = 0; } const unsigned int prev_progress = progress[download_progress->target.sha256Hash()]; const unsigned int new_progress = download_progress->progress; if (new_progress > prev_progress) { progress[download_progress->target.sha256Hash()] = new_progress; std::cout << "Download progress for file " << download_progress->target.filename() << ": " << new_progress << "%\n"; } } else if (event->variant == "DownloadTargetComplete") { const auto download_complete = dynamic_cast<event::DownloadTargetComplete *>(event.get()); std::cout << "Download complete for file " << download_complete->update.filename() << ": " << (download_complete->success ? "success" : "failure") << "\n"; progress.erase(download_complete->update.sha256Hash()); } else if (event->variant == "InstallStarted") { const auto install_started = dynamic_cast<event::InstallStarted *>(event.get()); std::cout << "Installation started for device " << install_started->serial.ToString() << "\n"; } else if (event->variant == "InstallTargetComplete") { const auto install_complete = dynamic_cast<event::InstallTargetComplete *>(event.get()); std::cout << "Installation complete for device " << install_complete->serial.ToString() << ": " << (install_complete->success ? "success" : "failure") << "\n"; } else if (event->variant == "DownloadPaused" || event->variant == "DownloadResumed") { // Do nothing. } else { std::cout << "Received " << event->variant << " event\n"; } } int main(int argc, char *argv[]) { logger_init(); logger_set_threshold(boost::log::trivial::info); LOG_INFO << "hmi_stub version " AKTUALIZR_VERSION " starting"; bpo::variables_map commandline_map = parse_options(argc, argv); int r = -1; boost::signals2::connection conn; try { Config config(commandline_map); if (config.logger.loglevel <= boost::log::trivial::debug) { SSL_load_error_strings(); } LOG_DEBUG << "Current directory: " << boost::filesystem::current_path().string(); Aktualizr aktualizr(config); std::function<void(const std::shared_ptr<event::BaseEvent> event)> f_cb = [](const std::shared_ptr<event::BaseEvent> event) { process_event(event); }; conn = aktualizr.SetSignalHandler(f_cb); aktualizr.Initialize(); std::vector<Uptane::Target> updates; std::string buffer; while (std::getline(std::cin, buffer)) { boost::algorithm::to_lower(buffer); if (buffer == "shutdown") { aktualizr.Shutdown(); break; } else if (buffer == "senddevicedata") { aktualizr.SendDeviceData(); } else if (buffer == "fetchmetadata" || buffer == "fetchmeta" || buffer == "checkupdates" || buffer == "check") { UpdateCheckResult result = aktualizr.CheckUpdates().get(); updates = result.updates; std::cout << updates.size() << " updates available\n"; } else if (buffer == "download" || buffer == "startdownload") { aktualizr.Download(updates); } else if (buffer == "install" || buffer == "uptaneinstall") { aktualizr.Install(updates); updates.clear(); } else if (buffer == "campaigncheck") { aktualizr.CampaignCheck(); } else if (buffer == "pause") { PauseResult pause_result = aktualizr.Pause(); switch (pause_result) { case PauseResult::kPaused: std::cout << "Download paused.\n"; break; case PauseResult::kAlreadyPaused: std::cout << "Download already paused.\n"; break; case PauseResult::kNotDownloading: std::cout << "Download is not in progress.\n"; break; default: std::cout << "Unrecognized pause result.\n"; break; } } else if (buffer == "resume") { PauseResult resume_result = aktualizr.Resume(); switch (resume_result) { case PauseResult::kResumed: std::cout << "Download resumed.\n"; break; case PauseResult::kNotPaused: std::cout << "Download not paused.\n"; break; default: std::cout << "Unrecognized resume result.\n"; break; } } else if (!buffer.empty()) { std::cout << "Unknown command.\n"; } } r = 0; } catch (const std::exception &ex) { LOG_ERROR << "Fatal error in hmi_stub: " << ex.what(); } conn.disconnect(); return r; } <commit_msg>hmi-stub: Fix deadlock caused by checking for updates while paused.<commit_after>#include <iostream> #include <map> #include <mutex> #include <string> #include <vector> #include <openssl/ssl.h> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/property_tree/ini_parser.hpp> #include <boost/signals2.hpp> #include "config/config.h" #include "logging/logging.h" #include "primary/aktualizr.h" #include "uptane/secondaryfactory.h" #include "utilities/utils.h" namespace bpo = boost::program_options; std::map<std::string, unsigned int> progress; std::mutex pending_ecus_mutex; unsigned int pending_ecus; void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) { if (vm.count("help") != 0) { std::cout << description << '\n'; std::cout << "Available commands: Shutdown, SendDeviceData, CheckUpdates, Download, Install, CampaignCheck\n"; exit(EXIT_SUCCESS); } if (vm.count("version") != 0) { std::cout << "Current hmi_stub version is: " << AKTUALIZR_VERSION << "\n"; exit(EXIT_SUCCESS); } } bpo::variables_map parse_options(int argc, char *argv[]) { bpo::options_description description("HMI stub interface for libaktualizr"); // clang-format off // Try to keep these options in the same order as Config::updateFromCommandLine(). // The first three are commandline only. description.add_options() ("help,h", "print usage") ("version,v", "Current aktualizr version") ("config,c", bpo::value<std::vector<boost::filesystem::path> >()->composing(), "configuration file or directory") ("secondary-configs-dir", bpo::value<boost::filesystem::path>(), "directory containing seconday ECU configuration files") ("loglevel", bpo::value<int>(), "set log level 0-5 (trace, debug, info, warning, error, fatal)"); // clang-format on bpo::variables_map vm; std::vector<std::string> unregistered_options; try { bpo::basic_parsed_options<char> parsed_options = bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run(); bpo::store(parsed_options, vm); check_info_options(description, vm); bpo::notify(vm); unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional); if (vm.count("help") == 0 && !unregistered_options.empty()) { std::cout << description << "\n"; exit(EXIT_FAILURE); } } catch (const bpo::required_option &ex) { // print the error and append the default commandline option description std::cout << ex.what() << std::endl << description; exit(EXIT_FAILURE); } catch (const bpo::error &ex) { check_info_options(description, vm); // log boost error LOG_ERROR << "boost command line option error: " << ex.what(); // print the error message to the standard output too, as the user provided // a non-supported commandline option std::cout << ex.what() << '\n'; // set the returnValue, thereby ctest will recognize // that something went wrong exit(EXIT_FAILURE); } return vm; } void process_event(const std::shared_ptr<event::BaseEvent> &event) { if (event->variant == "DownloadProgressReport") { const auto download_progress = dynamic_cast<event::DownloadProgressReport *>(event.get()); if (progress.find(download_progress->target.sha256Hash()) == progress.end()) { progress[download_progress->target.sha256Hash()] = 0; } const unsigned int prev_progress = progress[download_progress->target.sha256Hash()]; const unsigned int new_progress = download_progress->progress; if (new_progress > prev_progress) { progress[download_progress->target.sha256Hash()] = new_progress; std::cout << "Download progress for file " << download_progress->target.filename() << ": " << new_progress << "%\n"; } } else if (event->variant == "DownloadTargetComplete") { const auto download_complete = dynamic_cast<event::DownloadTargetComplete *>(event.get()); std::cout << "Download complete for file " << download_complete->update.filename() << ": " << (download_complete->success ? "success" : "failure") << "\n"; progress.erase(download_complete->update.sha256Hash()); } else if (event->variant == "InstallStarted") { const auto install_started = dynamic_cast<event::InstallStarted *>(event.get()); std::cout << "Installation started for device " << install_started->serial.ToString() << "\n"; } else if (event->variant == "InstallTargetComplete") { const auto install_complete = dynamic_cast<event::InstallTargetComplete *>(event.get()); std::cout << "Installation complete for device " << install_complete->serial.ToString() << ": " << (install_complete->success ? "success" : "failure") << "\n"; } else if (event->variant == "DownloadPaused" || event->variant == "DownloadResumed") { // Do nothing. } else { std::cout << "Received " << event->variant << " event\n"; } } int main(int argc, char *argv[]) { logger_init(); logger_set_threshold(boost::log::trivial::info); LOG_INFO << "hmi_stub version " AKTUALIZR_VERSION " starting"; bpo::variables_map commandline_map = parse_options(argc, argv); int r = -1; boost::signals2::connection conn; try { Config config(commandline_map); if (config.logger.loglevel <= boost::log::trivial::debug) { SSL_load_error_strings(); } LOG_DEBUG << "Current directory: " << boost::filesystem::current_path().string(); Aktualizr aktualizr(config); std::function<void(const std::shared_ptr<event::BaseEvent> event)> f_cb = [](const std::shared_ptr<event::BaseEvent> event) { process_event(event); }; conn = aktualizr.SetSignalHandler(f_cb); aktualizr.Initialize(); std::vector<Uptane::Target> updates; PauseResult pause_result = PauseResult::kNotDownloading; std::string buffer; while (std::getline(std::cin, buffer)) { boost::algorithm::to_lower(buffer); if (buffer == "shutdown") { aktualizr.Shutdown(); break; } else if (buffer == "senddevicedata") { aktualizr.SendDeviceData(); } else if (buffer == "fetchmetadata" || buffer == "fetchmeta" || buffer == "checkupdates" || buffer == "check") { auto fut_result = aktualizr.CheckUpdates(); if (pause_result != PauseResult::kPaused && pause_result != PauseResult::kAlreadyPaused) { UpdateCheckResult result = fut_result.get(); updates = result.updates; std::cout << updates.size() << " updates available\n"; } } else if (buffer == "download" || buffer == "startdownload") { aktualizr.Download(updates); } else if (buffer == "install" || buffer == "uptaneinstall") { aktualizr.Install(updates); updates.clear(); } else if (buffer == "campaigncheck") { aktualizr.CampaignCheck(); } else if (buffer == "pause") { pause_result = aktualizr.Pause(); switch (pause_result) { case PauseResult::kPaused: std::cout << "Download paused.\n"; break; case PauseResult::kAlreadyPaused: std::cout << "Download already paused.\n"; break; case PauseResult::kNotDownloading: std::cout << "Download is not in progress.\n"; break; default: std::cout << "Unrecognized pause result: " << static_cast<int>(pause_result) << "\n"; break; } } else if (buffer == "resume") { pause_result = aktualizr.Resume(); switch (pause_result) { case PauseResult::kResumed: std::cout << "Download resumed.\n"; break; case PauseResult::kNotPaused: std::cout << "Download not paused.\n"; break; default: std::cout << "Unrecognized resume result: " << static_cast<int>(pause_result) << "\n"; break; } } else if (!buffer.empty()) { std::cout << "Unknown command.\n"; } } r = 0; } catch (const std::exception &ex) { LOG_ERROR << "Fatal error in hmi_stub: " << ex.what(); } conn.disconnect(); return r; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, Inc * * 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include "libforestdb/forestdb.h" #include "hbtrie.h" #include "docio.h" #include "btreeblock.h" #include "common.h" #include "wal.h" #include "avltree.h" #include "list.h" #include "internal_types.h" #include "memleak.h" #ifdef __DEBUG #ifndef __DEBUG_FDB #undef DBG #undef DBGCMD #undef DBGSW #define DBG(...) #define DBGCMD(...) #define DBGSW(n, ...) #endif #endif struct iterator_wal_entry{ void *key; wal_item_action action; uint16_t keylen; uint64_t offset; struct avl_node avl; }; // lexicographically compares two variable-length binary streams int _fdb_keycmp(void *key1, size_t keylen1, void *key2, size_t keylen2) { if (keylen1 == keylen2) { return memcmp(key1, key2, keylen1); }else { size_t len = MIN(keylen1, keylen2); int cmp = memcmp(key1, key2, len); if (cmp != 0) return cmp; else { return (int)((int)keylen1 - (int)keylen2); } } } int _fdb_wal_cmp(struct avl_node *a, struct avl_node *b, void *aux) { struct iterator_wal_entry *aa, *bb; aa = _get_entry(a, struct iterator_wal_entry, avl); bb = _get_entry(b, struct iterator_wal_entry, avl); if (aux) { // custom compare function fdb_custom_cmp func = (fdb_custom_cmp)aux; return func(aa->key, bb->key); } else { return _fdb_keycmp(aa->key, aa->keylen, bb->key, bb->keylen); } } fdb_status fdb_iterator_init(fdb_handle *handle, fdb_iterator *iterator, const void *start_key, size_t start_keylen, const void *end_key, size_t end_keylen, fdb_iterator_opt_t opt) { int cmp; hbtrie_result hr; struct list_elem *e; struct wal_item *wal_item; struct iterator_wal_entry *snap_item; if (handle == NULL || iterator == NULL) { return FDB_RESULT_INVALID_ARGS; } iterator->handle = *handle; iterator->hbtrie_iterator = (struct hbtrie_iterator *)malloc(sizeof(struct hbtrie_iterator)); iterator->opt = opt; iterator->_key = (void*)malloc(FDB_MAX_KEYLEN); iterator->_keylen = 0; iterator->_offset = BLK_NOT_FOUND; if (start_key == NULL) start_keylen = 0; if (end_key == NULL) { iterator->end_key = NULL; end_keylen = 0; }else{ iterator->end_key = (void*)malloc(end_keylen); memcpy(iterator->end_key, end_key, end_keylen); } iterator->end_keylen = end_keylen; // create an iterator handle for hb-trie hr = hbtrie_iterator_init(handle->trie, iterator->hbtrie_iterator, (void *)start_key, start_keylen); if (hr == HBTRIE_RESULT_FAIL) { return FDB_RESULT_ITERATOR_FAIL; } // create a snapshot for WAL (avl-tree) // (from the beginning to the last committed element) // init tree iterator->wal_tree = (struct avl_tree*)malloc(sizeof(struct avl_tree)); avl_init(iterator->wal_tree, (void*)(handle->cmp_func)); spin_lock(&handle->file->wal->lock); e = list_begin(&handle->file->wal->list); while(e) { wal_item = _get_entry(e, struct wal_item, list_elem); if (start_key) { if (handle->cmp_func) { // custom compare function cmp = handle->cmp_func((void *)start_key, wal_item->key); } else { cmp = _fdb_keycmp((void *)start_key, start_keylen, wal_item->key, wal_item->keylen); } }else{ cmp = 0; } if (cmp <= 0) { // copy from WAL_ITEM snap_item = (struct iterator_wal_entry*)malloc(sizeof(struct iterator_wal_entry)); snap_item->keylen = wal_item->keylen; snap_item->key = (void*)malloc(snap_item->keylen); memcpy(snap_item->key, wal_item->key, snap_item->keylen); snap_item->action = wal_item->action; snap_item->offset = wal_item->offset; // insert into tree avl_insert(iterator->wal_tree, &snap_item->avl, _fdb_wal_cmp); } if (e == handle->file->wal->last_commit) break; e = list_next(e); } iterator->tree_cursor = avl_first(iterator->wal_tree); spin_unlock(&handle->file->wal->lock); return FDB_RESULT_SUCCESS; } // DOC returned by this function must be freed using 'fdb_doc_free' static fdb_status _fdb_iterator_next(fdb_iterator *iterator, fdb_doc **doc, uint64_t *doc_offset_out) { int cmp; void *key; size_t keylen; uint64_t offset; hbtrie_result hr = HBTRIE_RESULT_SUCCESS; fdb_status fs; struct docio_object _doc; struct iterator_wal_entry *snap_item = NULL; start: key = iterator->_key; // retrieve from hb-trie if (iterator->_offset == BLK_NOT_FOUND) { // no key waiting for being returned // get next key from hb-trie hr = hbtrie_next( iterator->hbtrie_iterator, key, &iterator->_keylen, (void*)&iterator->_offset); btreeblk_end(iterator->handle.bhandle); iterator->_offset = _endian_decode(iterator->_offset); } keylen = iterator->_keylen; offset = iterator->_offset; if (hr == HBTRIE_RESULT_FAIL && iterator->tree_cursor == NULL) { return FDB_RESULT_ITERATOR_FAIL; } while (iterator->tree_cursor) { // get the current item of rb-tree snap_item = _get_entry(iterator->tree_cursor, struct iterator_wal_entry, avl); if (hr != HBTRIE_RESULT_FAIL) { if (iterator->handle.cmp_func) { // custom compare function cmp = iterator->handle.cmp_func(snap_item->key, key); } else { cmp = _fdb_keycmp(snap_item->key, snap_item->keylen, key, keylen); } }else{ // no more docs in hb-trie cmp = -1; } if (cmp <= 0) { // key[WAL] <= key[hb-trie] .. take key[WAL] first iterator->tree_cursor = avl_next(iterator->tree_cursor); uint8_t drop_logical_deletes = (snap_item->action == WAL_ACT_LOGICAL_REMOVE) && (iterator->opt & FDB_ITR_NO_DELETES); if (cmp < 0) { if (snap_item->action == WAL_ACT_REMOVE || drop_logical_deletes) { if (hr == HBTRIE_RESULT_FAIL && iterator->tree_cursor == NULL) { return FDB_RESULT_ITERATOR_FAIL; } // this key is removed .. get next key[WAL] continue; } }else{ iterator->_offset = BLK_NOT_FOUND; if (snap_item->action == WAL_ACT_REMOVE || drop_logical_deletes) { // the key is removed .. start over again goto start; } } key = snap_item->key; keylen = snap_item->keylen; offset = snap_item->offset; } break; } if (offset == iterator->_offset) { // take key[hb-trie] & and fetch the next key[hb-trie] at next turn iterator->_offset = BLK_NOT_FOUND; } if (iterator->end_key) { if (iterator->handle.cmp_func) { // custom compare function cmp = iterator->handle.cmp_func(iterator->end_key, key); } else { cmp = _fdb_keycmp(iterator->end_key, iterator->end_keylen, key, keylen); } if (cmp < 0) { // current key (KEY) is lexicographically greater than END_KEY // terminate the iteration return FDB_RESULT_ITERATOR_FAIL; } } _doc.key = key; _doc.length.keylen = keylen; _doc.meta = NULL; _doc.body = NULL; if (iterator->opt & FDB_ITR_METAONLY) { offset = docio_read_doc_key_meta(iterator->handle.dhandle, offset, &_doc); if (_doc.length.bodylen == 0 && (iterator->opt & FDB_ITR_NO_DELETES)) { free(_doc.meta); return FDB_RESULT_KEY_NOT_FOUND; } if (doc_offset_out && _doc.length.bodylen > 0) { *doc_offset_out = offset; } } else { docio_read_doc(iterator->handle.dhandle, offset, &_doc); if (_doc.length.bodylen == 0 && (iterator->opt & FDB_ITR_NO_DELETES)) { free(_doc.meta); free(_doc.body); return FDB_RESULT_KEY_NOT_FOUND; } } fs = fdb_doc_create(doc, key, keylen, NULL, 0, NULL, 0); if (fs != FDB_RESULT_SUCCESS) { free(_doc.meta); free(_doc.body); return fs; } (*doc)->meta = _doc.meta; (*doc)->metalen = _doc.length.metalen; if (!(iterator->opt & FDB_ITR_METAONLY)) { (*doc)->body = _doc.body; (*doc)->bodylen = _doc.length.bodylen; } #ifdef __FDB_SEQTREE (*doc)->seqnum = _doc.seqnum; #endif (*doc)->deleted = (_doc.length.bodylen == 0) ? 1 : 0; return FDB_RESULT_SUCCESS; } fdb_status fdb_iterator_next_offset(fdb_iterator *iterator, fdb_doc **doc, uint64_t *doc_offset_out) { fdb_iterator_opt_t opt = iterator->opt; iterator->opt |= FDB_ITR_METAONLY; fdb_status result = FDB_RESULT_SUCCESS; while ((result = _fdb_iterator_next(iterator, doc, doc_offset_out)) == FDB_RESULT_KEY_NOT_FOUND); iterator->opt = opt; return result; } fdb_status fdb_iterator_next(fdb_iterator *iterator, fdb_doc **doc) { fdb_status result = FDB_RESULT_SUCCESS; while ((result = _fdb_iterator_next(iterator, doc, NULL)) == FDB_RESULT_KEY_NOT_FOUND); return result; } fdb_status fdb_iterator_close(fdb_iterator *iterator) { hbtrie_result hr; struct avl_node *a; struct iterator_wal_entry *snap_item; hr = hbtrie_iterator_free(iterator->hbtrie_iterator); free(iterator->hbtrie_iterator); if (iterator->end_key) free(iterator->end_key); a = avl_first(iterator->wal_tree); while(a) { snap_item = _get_entry(a, struct iterator_wal_entry, avl); a = avl_next(a); avl_remove(iterator->wal_tree, &snap_item->avl); free(snap_item->key); free(snap_item); } free(iterator->wal_tree); free(iterator->_key); return FDB_RESULT_SUCCESS; } <commit_msg>MB-10783 iterator_next_offset should return a doc body length.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, Inc * * 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include "libforestdb/forestdb.h" #include "hbtrie.h" #include "docio.h" #include "btreeblock.h" #include "common.h" #include "wal.h" #include "avltree.h" #include "list.h" #include "internal_types.h" #include "memleak.h" #ifdef __DEBUG #ifndef __DEBUG_FDB #undef DBG #undef DBGCMD #undef DBGSW #define DBG(...) #define DBGCMD(...) #define DBGSW(n, ...) #endif #endif struct iterator_wal_entry{ void *key; wal_item_action action; uint16_t keylen; uint64_t offset; struct avl_node avl; }; // lexicographically compares two variable-length binary streams int _fdb_keycmp(void *key1, size_t keylen1, void *key2, size_t keylen2) { if (keylen1 == keylen2) { return memcmp(key1, key2, keylen1); }else { size_t len = MIN(keylen1, keylen2); int cmp = memcmp(key1, key2, len); if (cmp != 0) return cmp; else { return (int)((int)keylen1 - (int)keylen2); } } } int _fdb_wal_cmp(struct avl_node *a, struct avl_node *b, void *aux) { struct iterator_wal_entry *aa, *bb; aa = _get_entry(a, struct iterator_wal_entry, avl); bb = _get_entry(b, struct iterator_wal_entry, avl); if (aux) { // custom compare function fdb_custom_cmp func = (fdb_custom_cmp)aux; return func(aa->key, bb->key); } else { return _fdb_keycmp(aa->key, aa->keylen, bb->key, bb->keylen); } } fdb_status fdb_iterator_init(fdb_handle *handle, fdb_iterator *iterator, const void *start_key, size_t start_keylen, const void *end_key, size_t end_keylen, fdb_iterator_opt_t opt) { int cmp; hbtrie_result hr; struct list_elem *e; struct wal_item *wal_item; struct iterator_wal_entry *snap_item; if (handle == NULL || iterator == NULL) { return FDB_RESULT_INVALID_ARGS; } iterator->handle = *handle; iterator->hbtrie_iterator = (struct hbtrie_iterator *)malloc(sizeof(struct hbtrie_iterator)); iterator->opt = opt; iterator->_key = (void*)malloc(FDB_MAX_KEYLEN); iterator->_keylen = 0; iterator->_offset = BLK_NOT_FOUND; if (start_key == NULL) start_keylen = 0; if (end_key == NULL) { iterator->end_key = NULL; end_keylen = 0; }else{ iterator->end_key = (void*)malloc(end_keylen); memcpy(iterator->end_key, end_key, end_keylen); } iterator->end_keylen = end_keylen; // create an iterator handle for hb-trie hr = hbtrie_iterator_init(handle->trie, iterator->hbtrie_iterator, (void *)start_key, start_keylen); if (hr == HBTRIE_RESULT_FAIL) { return FDB_RESULT_ITERATOR_FAIL; } // create a snapshot for WAL (avl-tree) // (from the beginning to the last committed element) // init tree iterator->wal_tree = (struct avl_tree*)malloc(sizeof(struct avl_tree)); avl_init(iterator->wal_tree, (void*)(handle->cmp_func)); spin_lock(&handle->file->wal->lock); e = list_begin(&handle->file->wal->list); while(e) { wal_item = _get_entry(e, struct wal_item, list_elem); if (start_key) { if (handle->cmp_func) { // custom compare function cmp = handle->cmp_func((void *)start_key, wal_item->key); } else { cmp = _fdb_keycmp((void *)start_key, start_keylen, wal_item->key, wal_item->keylen); } }else{ cmp = 0; } if (cmp <= 0) { // copy from WAL_ITEM snap_item = (struct iterator_wal_entry*)malloc(sizeof(struct iterator_wal_entry)); snap_item->keylen = wal_item->keylen; snap_item->key = (void*)malloc(snap_item->keylen); memcpy(snap_item->key, wal_item->key, snap_item->keylen); snap_item->action = wal_item->action; snap_item->offset = wal_item->offset; // insert into tree avl_insert(iterator->wal_tree, &snap_item->avl, _fdb_wal_cmp); } if (e == handle->file->wal->last_commit) break; e = list_next(e); } iterator->tree_cursor = avl_first(iterator->wal_tree); spin_unlock(&handle->file->wal->lock); return FDB_RESULT_SUCCESS; } // DOC returned by this function must be freed using 'fdb_doc_free' static fdb_status _fdb_iterator_next(fdb_iterator *iterator, fdb_doc **doc, uint64_t *doc_offset_out) { int cmp; void *key; size_t keylen; uint64_t offset; hbtrie_result hr = HBTRIE_RESULT_SUCCESS; fdb_status fs; struct docio_object _doc; struct iterator_wal_entry *snap_item = NULL; start: key = iterator->_key; // retrieve from hb-trie if (iterator->_offset == BLK_NOT_FOUND) { // no key waiting for being returned // get next key from hb-trie hr = hbtrie_next( iterator->hbtrie_iterator, key, &iterator->_keylen, (void*)&iterator->_offset); btreeblk_end(iterator->handle.bhandle); iterator->_offset = _endian_decode(iterator->_offset); } keylen = iterator->_keylen; offset = iterator->_offset; if (hr == HBTRIE_RESULT_FAIL && iterator->tree_cursor == NULL) { return FDB_RESULT_ITERATOR_FAIL; } while (iterator->tree_cursor) { // get the current item of rb-tree snap_item = _get_entry(iterator->tree_cursor, struct iterator_wal_entry, avl); if (hr != HBTRIE_RESULT_FAIL) { if (iterator->handle.cmp_func) { // custom compare function cmp = iterator->handle.cmp_func(snap_item->key, key); } else { cmp = _fdb_keycmp(snap_item->key, snap_item->keylen, key, keylen); } }else{ // no more docs in hb-trie cmp = -1; } if (cmp <= 0) { // key[WAL] <= key[hb-trie] .. take key[WAL] first iterator->tree_cursor = avl_next(iterator->tree_cursor); uint8_t drop_logical_deletes = (snap_item->action == WAL_ACT_LOGICAL_REMOVE) && (iterator->opt & FDB_ITR_NO_DELETES); if (cmp < 0) { if (snap_item->action == WAL_ACT_REMOVE || drop_logical_deletes) { if (hr == HBTRIE_RESULT_FAIL && iterator->tree_cursor == NULL) { return FDB_RESULT_ITERATOR_FAIL; } // this key is removed .. get next key[WAL] continue; } }else{ iterator->_offset = BLK_NOT_FOUND; if (snap_item->action == WAL_ACT_REMOVE || drop_logical_deletes) { // the key is removed .. start over again goto start; } } key = snap_item->key; keylen = snap_item->keylen; offset = snap_item->offset; } break; } if (offset == iterator->_offset) { // take key[hb-trie] & and fetch the next key[hb-trie] at next turn iterator->_offset = BLK_NOT_FOUND; } if (iterator->end_key) { if (iterator->handle.cmp_func) { // custom compare function cmp = iterator->handle.cmp_func(iterator->end_key, key); } else { cmp = _fdb_keycmp(iterator->end_key, iterator->end_keylen, key, keylen); } if (cmp < 0) { // current key (KEY) is lexicographically greater than END_KEY // terminate the iteration return FDB_RESULT_ITERATOR_FAIL; } } _doc.key = key; _doc.length.keylen = keylen; _doc.meta = NULL; _doc.body = NULL; if (iterator->opt & FDB_ITR_METAONLY) { offset = docio_read_doc_key_meta(iterator->handle.dhandle, offset, &_doc); if (_doc.length.bodylen == 0 && (iterator->opt & FDB_ITR_NO_DELETES)) { free(_doc.meta); return FDB_RESULT_KEY_NOT_FOUND; } if (doc_offset_out && _doc.length.bodylen > 0) { *doc_offset_out = offset; } } else { docio_read_doc(iterator->handle.dhandle, offset, &_doc); if (_doc.length.bodylen == 0 && (iterator->opt & FDB_ITR_NO_DELETES)) { free(_doc.meta); free(_doc.body); return FDB_RESULT_KEY_NOT_FOUND; } } fs = fdb_doc_create(doc, key, keylen, NULL, 0, NULL, 0); if (fs != FDB_RESULT_SUCCESS) { free(_doc.meta); free(_doc.body); return fs; } (*doc)->meta = _doc.meta; (*doc)->metalen = _doc.length.metalen; (*doc)->body = _doc.body; (*doc)->bodylen = _doc.length.bodylen; #ifdef __FDB_SEQTREE (*doc)->seqnum = _doc.seqnum; #endif (*doc)->deleted = (_doc.length.bodylen == 0) ? 1 : 0; return FDB_RESULT_SUCCESS; } fdb_status fdb_iterator_next_offset(fdb_iterator *iterator, fdb_doc **doc, uint64_t *doc_offset_out) { fdb_iterator_opt_t opt = iterator->opt; iterator->opt |= FDB_ITR_METAONLY; fdb_status result = FDB_RESULT_SUCCESS; while ((result = _fdb_iterator_next(iterator, doc, doc_offset_out)) == FDB_RESULT_KEY_NOT_FOUND); iterator->opt = opt; return result; } fdb_status fdb_iterator_next(fdb_iterator *iterator, fdb_doc **doc) { fdb_status result = FDB_RESULT_SUCCESS; while ((result = _fdb_iterator_next(iterator, doc, NULL)) == FDB_RESULT_KEY_NOT_FOUND); return result; } fdb_status fdb_iterator_close(fdb_iterator *iterator) { hbtrie_result hr; struct avl_node *a; struct iterator_wal_entry *snap_item; hr = hbtrie_iterator_free(iterator->hbtrie_iterator); free(iterator->hbtrie_iterator); if (iterator->end_key) free(iterator->end_key); a = avl_first(iterator->wal_tree); while(a) { snap_item = _get_entry(a, struct iterator_wal_entry, avl); a = avl_next(a); avl_remove(iterator->wal_tree, &snap_item->avl); free(snap_item->key); free(snap_item); } free(iterator->wal_tree); free(iterator->_key); return FDB_RESULT_SUCCESS; } <|endoftext|>
<commit_before>/* Research carried out within the scope of the Associated International Laboratory: Joint Japanese-French Robotics Laboratory (JRL) Developed by Florent Lamiraux (LAAS-CNRS) */ #include <iostream> #include "hppCorbaServer/hppciServer.h" #include "hppCorbaServer/hppciProblem.h" #include "flicSteeringMethod.h" #include "reedsSheppSteeringMethod.h" #include "hppVisRdmBuilder.h" #include "kwsPlusPCARdmBuilder.h" #define ODEBUG(x) std::cerr << "hppciProblem.cpp: " << x << std::endl //#define ODEBUG(x) ChppciProblem_impl::ChppciProblem_impl(ChppciServer* inHppciServer) : attHppciServer(inHppciServer), attHppPlanner(inHppciServer->getHppPlanner()) { } CORBA::Short ChppciProblem_impl::setSteeringMethod(CORBA::Short inProblemId, const char* inSteeringMethod, CORBA::Boolean inOriented) { std::string steeringMethodName(inSteeringMethod); unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than number of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); /* Check that name correspond to a steering method factory */ if (!attHppciServer->steeringMethodFactoryAlreadySet(steeringMethodName)) { ODEBUG("unknown steering method."); } // Create steering method CkwsSteeringMethodShPtr steeringMethod = attHppciServer->createSteeringMethod(steeringMethodName, inOriented); hppRobot->steeringMethod(steeringMethod); } else { ODEBUG("setSteeringMethod: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::setRoadmapbuilder(CORBA::Short inProblemId, const char* inRoadmapBuilderName) { std::string roadmapBuilderName(inRoadmapBuilderName); unsigned int hppProblemId = (unsigned int)inProblemId; ktStatus status; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than number of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); // Create an empty roadmap for the robot. CkwsRoadmapShPtr roadmap = CkwsRoadmap::create(hppRobot->kwsDevice()); // Set arbitrary penetration. double penetration = 0.05; // Create roadmapBuilder if (roadmapBuilderName == "basic") { CkwsBasicRdmBuilderShPtr roadmapBuilder = CkwsBasicRdmBuilder::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); return status; } else if (roadmapBuilderName == "diffusing") { CkwsDiffusingRdmBuilderShPtr roadmapBuilder = CkwsDiffusingRdmBuilder::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); return status; } else if (roadmapBuilderName == "bi-diffusing") { CkwsDiffusingRdmBuilderShPtr roadmapBuilder = CkwsDiffusingRdmBuilder::create(roadmap, penetration); roadmapBuilder->diffuseFromProblemGoal(true); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); return status; } else if (roadmapBuilderName == "IPP") { CkwsIPPRdmBuilderShPtr roadmapBuilder = CkwsIPPRdmBuilder::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); } else if (roadmapBuilderName == "visibility") { ChppVisRdmBuilderShPtr roadmapBuilder = ChppVisRdmBuilder::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); } else if (roadmapBuilderName == "PCA<diffusing>") { KIT_SHARED_PTR(CkwsPlusPCARdmBuilder<CkwsDiffusingRdmBuilder>) roadmapBuilder = CkwsPlusPCARdmBuilder<CkwsDiffusingRdmBuilder>::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); } else { ODEBUG("unknown roadmap builder"); return -1; } } else { ODEBUG("setRoadmapbuilder: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::setPathOptimizer(CORBA::Short inProblemId, const char* inPathOptimizerName) { std::string pathOptimizerName(inPathOptimizerName); ktStatus status; unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); #ifdef VERBOSE std::cout << "hppciProblem.cpp: setPathOptimizer: nbProblems " << nbProblems <<"problem id " << inProblemId << ", pathOptimizerName " <<pathOptimizerName << std::endl; #endif // Test that rank is less than number of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); if (pathOptimizerName == "clear") { CkwsClearOptimizerShPtr pathOptimizer = CkwsClearOptimizer::create(); status = attHppPlanner->pathOptimizerIthProblem(hppProblemId, pathOptimizer); #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: clear path optimizer set."<<endl; #endif return (CORBA::Short)status; } else if (pathOptimizerName == "adaptiveShortcut") { CkwsAdaptiveShortcutOptimizerShPtr pathOptimizer = CkwsAdaptiveShortcutOptimizer::create(); status = attHppPlanner->pathOptimizerIthProblem(hppProblemId, pathOptimizer); #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: adaptive shortcut path optimizer set."<<endl; #endif return (CORBA::Short)status; } else if (pathOptimizerName == "random") { CkwsRandomOptimizerShPtr pathOptimizer = CkwsRandomOptimizer::create(); status = attHppPlanner->pathOptimizerIthProblem(hppProblemId, pathOptimizer); #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: random path optimizer set."<<endl; #endif return (CORBA::Short)status; } else if (pathOptimizerName == "none") { CkwsPathOptimizerShPtr pathOptimizer; status = attHppPlanner->pathOptimizerIthProblem(hppProblemId, pathOptimizer); #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: no path optimizer set."<<endl; #endif return (CORBA::Short)status; } else { #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: unknown path optimizer" << endl; #endif return -1; } } else { ODEBUG("setPathOptimizer: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::setInitialConfig(CORBA::Short inProblemId, const dofSeq& dofArray) { unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int configDim = (unsigned int)dofArray.length(); std::vector<double> dofVector; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than nulber of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); // Fill dof vector with dof array. for (unsigned int iDof=0; iDof<configDim; iDof++) { dofVector.push_back(dofArray[iDof]); } // Create a config for robot initialized with dof vector. CkwsConfigShPtr config = CkwsConfig::create(hppRobot, dofVector); if (!config) { ODEBUG("setInitialConfig: cannot create config. Check that robot nb dof is equal to config size"); return -1; } return (short)attHppPlanner->initConfIthProblem(hppProblemId, config); } else { ODEBUG("setInitialConfig: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::setGoalConfig(CORBA::Short inProblemId, const dofSeq& dofArray) { unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int configDim = (unsigned int)dofArray.length(); std::vector<double> dofVector; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than nulber of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); // Fill dof vector with dof array. for (unsigned int iDof=0; iDof<configDim; iDof++) { dofVector.push_back(dofArray[iDof]); } // Create a config for robot initialized with dof vector. CkwsConfigShPtr config = CkwsConfig::create(hppRobot, dofVector); if (!config) { ODEBUG("setGoalConfig: cannot create config. Check that robot nb dof is equal to config size"); return -1; } return (short)attHppPlanner->goalConfIthProblem(hppProblemId, config); } else { ODEBUG("setGoalConfig: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::initializeProblem() { ktStatus status = attHppPlanner->initializeProblem(); return (CORBA::Short)status; } CORBA::Short ChppciProblem_impl::solveOneProblem(CORBA::Short inProblemId, CORBA::Short& inLastPathId, CORBA::Double& pathLength) { ktStatus status = KD_ERROR; inLastPathId = 0 ; pathLength = 0; unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than nulber of robots in vector. if (hppProblemId < nbProblems) { status = attHppPlanner->solveOneProblem(hppProblemId); } inLastPathId = attHppPlanner->getNbPaths(hppProblemId) - 1; if (inLastPathId > -1) { pathLength = attHppPlanner->getPath(hppProblemId, inLastPathId)->length(); } else { ODEBUG("solveOneProblem: no path in hppProblem " << hppProblemId); } return (CORBA::Short)status; } CORBA::Short ChppciProblem_impl::solve() { ktStatus status = attHppPlanner->solve(); return (CORBA::Short)status; } CORBA::Short ChppciProblem_impl::optimizePath(CORBA::Short inProblemId, CORBA::Short inPathId) { ktStatus status = attHppPlanner->optimizePath((unsigned int) inProblemId, (unsigned int) inPathId); return (CORBA::Short)status; } dofSeq* ChppciProblem_impl::configAtDistance(CORBA::Short inProblemId, CORBA::Short pathId, CORBA::Double pathLength, CORBA::Double atDistance) { dofSeq* inDofSeq ; // get the planner unsigned int hppProblemId = (unsigned int)inProblemId; //get the nb of dof of the robot in the problem unsigned int nbDofRobot = attHppPlanner->robotIthProblem(inProblemId)->countDofs(); //init the seqdof // Allocate result now that the size is known. CORBA::ULong size = (CORBA::ULong)nbDofRobot; double* DofList = dofSeq::allocbuf(size); inDofSeq = new dofSeq(size, size, DofList, true); //get the config of the robot on the path if (atDistance > pathLength) { ODEBUG("configAtParam: param out of range (longer than path Length) " << "Param : "<< atDistance << " length : " << pathLength); } else { CkwsConfigShPtr inConfig ; inConfig = attHppPlanner->getPath(hppProblemId, pathId)->configAtDistance(atDistance) ; //convert the config in dofseq for ( unsigned int i = 0 ; i < inConfig->size() ; i++){ DofList[i] = inConfig->dofValue(i) ; } } return inDofSeq; } /// \brief set tolerance to the objects in the planner CORBA::Short ChppciProblem_impl::setObstacleTolerance(CORBA::Short inProblemId, CORBA::Double tolerance) throw(CORBA::SystemException) { // get the planner unsigned int hppProblemId = (unsigned int)inProblemId; // get object hppPlanner of Corba server. if(!attHppPlanner){ ODEBUG("problem " << hppProblemId << " not found"); return -1; } std::vector<CkcdObjectShPtr> oList = attHppPlanner->obstacleList(); if(oList.size() == 0) cerr << " there are no obstacle in problem " << hppProblemId << endl; for(unsigned int i =0; i<oList.size(); i++){ oList[i]->tolerance(tolerance); ODEBUG("tolerance " << tolerance << " set to obstacle " << i); } return 0; } <commit_msg>Return -1 if steering method is not implemented.<commit_after>/* Research carried out within the scope of the Associated International Laboratory: Joint Japanese-French Robotics Laboratory (JRL) Developed by Florent Lamiraux (LAAS-CNRS) */ #include <iostream> #include "hppCorbaServer/hppciServer.h" #include "hppCorbaServer/hppciProblem.h" #include "flicSteeringMethod.h" #include "reedsSheppSteeringMethod.h" #include "hppVisRdmBuilder.h" #include "kwsPlusPCARdmBuilder.h" #define ODEBUG(x) std::cerr << "hppciProblem.cpp: " << x << std::endl //#define ODEBUG(x) ChppciProblem_impl::ChppciProblem_impl(ChppciServer* inHppciServer) : attHppciServer(inHppciServer), attHppPlanner(inHppciServer->getHppPlanner()) { } CORBA::Short ChppciProblem_impl::setSteeringMethod(CORBA::Short inProblemId, const char* inSteeringMethod, CORBA::Boolean inOriented) { std::string steeringMethodName(inSteeringMethod); unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than number of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); /* Check that name correspond to a steering method factory */ if (!attHppciServer->steeringMethodFactoryAlreadySet(steeringMethodName)) { ODEBUG("unknown steering method."); return -1; } // Create steering method CkwsSteeringMethodShPtr steeringMethod = attHppciServer->createSteeringMethod(steeringMethodName, inOriented); hppRobot->steeringMethod(steeringMethod); } else { ODEBUG("setSteeringMethod: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::setRoadmapbuilder(CORBA::Short inProblemId, const char* inRoadmapBuilderName) { std::string roadmapBuilderName(inRoadmapBuilderName); unsigned int hppProblemId = (unsigned int)inProblemId; ktStatus status; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than number of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); // Create an empty roadmap for the robot. CkwsRoadmapShPtr roadmap = CkwsRoadmap::create(hppRobot->kwsDevice()); // Set arbitrary penetration. double penetration = 0.05; // Create roadmapBuilder if (roadmapBuilderName == "basic") { CkwsBasicRdmBuilderShPtr roadmapBuilder = CkwsBasicRdmBuilder::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); return status; } else if (roadmapBuilderName == "diffusing") { CkwsDiffusingRdmBuilderShPtr roadmapBuilder = CkwsDiffusingRdmBuilder::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); return status; } else if (roadmapBuilderName == "bi-diffusing") { CkwsDiffusingRdmBuilderShPtr roadmapBuilder = CkwsDiffusingRdmBuilder::create(roadmap, penetration); roadmapBuilder->diffuseFromProblemGoal(true); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); return status; } else if (roadmapBuilderName == "IPP") { CkwsIPPRdmBuilderShPtr roadmapBuilder = CkwsIPPRdmBuilder::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); } else if (roadmapBuilderName == "visibility") { ChppVisRdmBuilderShPtr roadmapBuilder = ChppVisRdmBuilder::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); } else if (roadmapBuilderName == "PCA<diffusing>") { KIT_SHARED_PTR(CkwsPlusPCARdmBuilder<CkwsDiffusingRdmBuilder>) roadmapBuilder = CkwsPlusPCARdmBuilder<CkwsDiffusingRdmBuilder>::create(roadmap, penetration); status = attHppPlanner->roadmapBuilderIthProblem(hppProblemId, roadmapBuilder); } else { ODEBUG("unknown roadmap builder"); return -1; } } else { ODEBUG("setRoadmapbuilder: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::setPathOptimizer(CORBA::Short inProblemId, const char* inPathOptimizerName) { std::string pathOptimizerName(inPathOptimizerName); ktStatus status; unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); #ifdef VERBOSE std::cout << "hppciProblem.cpp: setPathOptimizer: nbProblems " << nbProblems <<"problem id " << inProblemId << ", pathOptimizerName " <<pathOptimizerName << std::endl; #endif // Test that rank is less than number of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); if (pathOptimizerName == "clear") { CkwsClearOptimizerShPtr pathOptimizer = CkwsClearOptimizer::create(); status = attHppPlanner->pathOptimizerIthProblem(hppProblemId, pathOptimizer); #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: clear path optimizer set."<<endl; #endif return (CORBA::Short)status; } else if (pathOptimizerName == "adaptiveShortcut") { CkwsAdaptiveShortcutOptimizerShPtr pathOptimizer = CkwsAdaptiveShortcutOptimizer::create(); status = attHppPlanner->pathOptimizerIthProblem(hppProblemId, pathOptimizer); #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: adaptive shortcut path optimizer set."<<endl; #endif return (CORBA::Short)status; } else if (pathOptimizerName == "random") { CkwsRandomOptimizerShPtr pathOptimizer = CkwsRandomOptimizer::create(); status = attHppPlanner->pathOptimizerIthProblem(hppProblemId, pathOptimizer); #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: random path optimizer set."<<endl; #endif return (CORBA::Short)status; } else if (pathOptimizerName == "none") { CkwsPathOptimizerShPtr pathOptimizer; status = attHppPlanner->pathOptimizerIthProblem(hppProblemId, pathOptimizer); #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: no path optimizer set."<<endl; #endif return (CORBA::Short)status; } else { #ifdef VERBOSE std::cout << "ChppciProblem_impl::setPathOptimizer: unknown path optimizer" << endl; #endif return -1; } } else { ODEBUG("setPathOptimizer: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::setInitialConfig(CORBA::Short inProblemId, const dofSeq& dofArray) { unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int configDim = (unsigned int)dofArray.length(); std::vector<double> dofVector; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than nulber of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); // Fill dof vector with dof array. for (unsigned int iDof=0; iDof<configDim; iDof++) { dofVector.push_back(dofArray[iDof]); } // Create a config for robot initialized with dof vector. CkwsConfigShPtr config = CkwsConfig::create(hppRobot, dofVector); if (!config) { ODEBUG("setInitialConfig: cannot create config. Check that robot nb dof is equal to config size"); return -1; } return (short)attHppPlanner->initConfIthProblem(hppProblemId, config); } else { ODEBUG("setInitialConfig: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::setGoalConfig(CORBA::Short inProblemId, const dofSeq& dofArray) { unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int configDim = (unsigned int)dofArray.length(); std::vector<double> dofVector; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than nulber of robots in vector. if (hppProblemId < nbProblems) { // Get robot in hppPlanner object. CkppDeviceComponentShPtr hppRobot = attHppPlanner->robotIthProblem(hppProblemId); // Fill dof vector with dof array. for (unsigned int iDof=0; iDof<configDim; iDof++) { dofVector.push_back(dofArray[iDof]); } // Create a config for robot initialized with dof vector. CkwsConfigShPtr config = CkwsConfig::create(hppRobot, dofVector); if (!config) { ODEBUG("setGoalConfig: cannot create config. Check that robot nb dof is equal to config size"); return -1; } return (short)attHppPlanner->goalConfIthProblem(hppProblemId, config); } else { ODEBUG("setGoalConfig: wrong robot Id"); return -1; } return 0; } CORBA::Short ChppciProblem_impl::initializeProblem() { ktStatus status = attHppPlanner->initializeProblem(); return (CORBA::Short)status; } CORBA::Short ChppciProblem_impl::solveOneProblem(CORBA::Short inProblemId, CORBA::Short& inLastPathId, CORBA::Double& pathLength) { ktStatus status = KD_ERROR; inLastPathId = 0 ; pathLength = 0; unsigned int hppProblemId = (unsigned int)inProblemId; unsigned int nbProblems = attHppPlanner->getNbHppProblems(); // Test that rank is less than nulber of robots in vector. if (hppProblemId < nbProblems) { status = attHppPlanner->solveOneProblem(hppProblemId); } inLastPathId = attHppPlanner->getNbPaths(hppProblemId) - 1; if (inLastPathId > -1) { pathLength = attHppPlanner->getPath(hppProblemId, inLastPathId)->length(); } else { ODEBUG("solveOneProblem: no path in hppProblem " << hppProblemId); } return (CORBA::Short)status; } CORBA::Short ChppciProblem_impl::solve() { ktStatus status = attHppPlanner->solve(); return (CORBA::Short)status; } CORBA::Short ChppciProblem_impl::optimizePath(CORBA::Short inProblemId, CORBA::Short inPathId) { ktStatus status = attHppPlanner->optimizePath((unsigned int) inProblemId, (unsigned int) inPathId); return (CORBA::Short)status; } dofSeq* ChppciProblem_impl::configAtDistance(CORBA::Short inProblemId, CORBA::Short pathId, CORBA::Double pathLength, CORBA::Double atDistance) { dofSeq* inDofSeq ; // get the planner unsigned int hppProblemId = (unsigned int)inProblemId; //get the nb of dof of the robot in the problem unsigned int nbDofRobot = attHppPlanner->robotIthProblem(inProblemId)->countDofs(); //init the seqdof // Allocate result now that the size is known. CORBA::ULong size = (CORBA::ULong)nbDofRobot; double* DofList = dofSeq::allocbuf(size); inDofSeq = new dofSeq(size, size, DofList, true); //get the config of the robot on the path if (atDistance > pathLength) { ODEBUG("configAtParam: param out of range (longer than path Length) " << "Param : "<< atDistance << " length : " << pathLength); } else { CkwsConfigShPtr inConfig ; inConfig = attHppPlanner->getPath(hppProblemId, pathId)->configAtDistance(atDistance) ; //convert the config in dofseq for ( unsigned int i = 0 ; i < inConfig->size() ; i++){ DofList[i] = inConfig->dofValue(i) ; } } return inDofSeq; } /// \brief set tolerance to the objects in the planner CORBA::Short ChppciProblem_impl::setObstacleTolerance(CORBA::Short inProblemId, CORBA::Double tolerance) throw(CORBA::SystemException) { // get the planner unsigned int hppProblemId = (unsigned int)inProblemId; // get object hppPlanner of Corba server. if(!attHppPlanner){ ODEBUG("problem " << hppProblemId << " not found"); return -1; } std::vector<CkcdObjectShPtr> oList = attHppPlanner->obstacleList(); if(oList.size() == 0) cerr << " there are no obstacle in problem " << hppProblemId << endl; for(unsigned int i =0; i<oList.size(); i++){ oList[i]->tolerance(tolerance); ODEBUG("tolerance " << tolerance << " set to obstacle " << i); } return 0; } <|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. * */ #include <cstdlib> #include <string> #include "ignition/transport/Node.hh" #include "gtest/gtest.h" #include "msg/int.pb.h" #include "ignition/transport/test_config.h" using namespace ignition; std::string partition = "testPartition"; std::string ns = ""; std::string topic = "/foo"; ////////////////////////////////////////////////// /// \brief Provide a service. void srvEcho(const std::string &_topic, const transport::msgs::Int &_req, transport::msgs::Int &_rep, bool &_result) { EXPECT_EQ(_topic, topic); _rep.set_data(_req.data()); _result = true; } ////////////////////////////////////////////////// TEST(twoProcSrvCall, ThousandCalls) { std::string responser_path = testing::portablePathUnion( PROJECT_BINARY_PATH, "test/integration/INTEGRATION_twoProcessesSrvCallReplierIncreasing_aux"); testing::forkHandlerType pi = testing::forkAndRun(responser_path.c_str()); transport::msgs::Int req; transport::msgs::Int response; bool result; unsigned int timeout = 1000; transport::Node node(partition, ns); for (int i = 0; i < 15000; i++) { req.set_data(i); ASSERT_TRUE(node.Request(topic, req, timeout, response, result)); // Check the service response. ASSERT_TRUE(result); EXPECT_EQ(i, response.data()); } // Need to kill the transport node testing::killFork(pi); } <commit_msg>Removing unused code.<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. * */ #include <cstdlib> #include <string> #include "ignition/transport/Node.hh" #include "gtest/gtest.h" #include "msg/int.pb.h" #include "ignition/transport/test_config.h" using namespace ignition; std::string partition = "testPartition"; std::string ns = ""; std::string topic = "/foo"; ////////////////////////////////////////////////// TEST(twoProcSrvCall, ThousandCalls) { std::string responser_path = testing::portablePathUnion( PROJECT_BINARY_PATH, "test/integration/INTEGRATION_twoProcessesSrvCallReplierIncreasing_aux"); testing::forkHandlerType pi = testing::forkAndRun(responser_path.c_str()); transport::msgs::Int req; transport::msgs::Int response; bool result; unsigned int timeout = 1000; transport::Node node(partition, ns); for (int i = 0; i < 15000; i++) { req.set_data(i); ASSERT_TRUE(node.Request(topic, req, timeout, response, result)); // Check the service response. ASSERT_TRUE(result); EXPECT_EQ(i, response.data()); } // Need to kill the transport node testing::killFork(pi); } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2017 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. // // ======================================================================== // #undef NDEBUG // sg #include "SceneGraph.h" #include "sg/common/Texture2D.h" #include "sg/geometry/TriangleMesh.h" #define TINYOBJLOADER_IMPLEMENTATION // define this in only *one* .cc #include "../3rdParty/tiny_obj_loader.h" #include <cstring> #include <sstream> namespace ospray { namespace sg { std::shared_ptr<Texture2D> loadTexture(const FileName &fullPath, const bool preferLinear = false) { std::shared_ptr<Texture2D> tex = Texture2D::load(fullPath, preferLinear); if (!tex) std::cout << "could not load texture " << fullPath.str() << " !\n"; return tex; } void addTextureIfNeeded(Material &node, const std::string &type, const FileName &texName, const FileName &containingPath, bool preferLinear = false) { if (!texName.str().empty()) { auto tex = loadTexture(containingPath + texName, preferLinear); if (tex) { tex->setName(type); node.setChild(type, tex); } } } static inline float parseFloatString(std::string valueString) { std::stringstream valueStream(valueString); float value; valueStream >> value; return value; } static inline vec3f parseVec3fString(std::string valueString) { std::stringstream valueStream(valueString); vec3f value; valueStream >> value.x >> value.y >> value.z; return value; } static inline void parseParameterString(std::string typeAndValueString, std::string & paramType, ospcommon::utility::Any & paramValue) { std::stringstream typeAndValueStream(typeAndValueString); typeAndValueStream >> paramType; std::string paramValueString; getline(typeAndValueStream,paramValueString); if (paramType == "float") { paramValue = parseFloatString(paramValueString); } else if (paramType == "vec3f") { paramValue = parseVec3fString(paramValueString); } else { // Unknown type. paramValue = typeAndValueString; } } static inline std::vector<std::shared_ptr<Material>> createSgMaterials(std::vector<tinyobj::material_t> &mats, const FileName &containingPath) { std::vector<std::shared_ptr<Material>> sgMaterials; for (auto &mat : mats) { auto matNodePtr = createNode(mat.name, "Material")->nodeAs<Material>(); auto &matNode = *matNodePtr; for (auto &param : mat.unknown_parameter) { if (param.first == "type") { matNode["type"].setValue(param.second); std::cout << "Creating material node of type " << param.second << std::endl; } else { std::string paramType; ospcommon::utility::Any paramValue; parseParameterString(param.second, paramType, paramValue); matNode.createChildWithValue(param.first, paramType, paramValue); std::cout << "Parsed parameter " << param.first << " of type " << paramType << std::endl; } } matNode["d"].setValue(mat.dissolve); matNode["Ka"].setValue(vec3f(mat.ambient[0], mat.ambient[1], mat.ambient[2])); matNode["Kd"].setValue(vec3f(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2])); matNode["Ks"].setValue(vec3f(mat.specular[0], mat.specular[1], mat.specular[2])); addTextureIfNeeded(matNode, "map_Ka", mat.ambient_texname, containingPath); addTextureIfNeeded(matNode, "map_Kd", mat.diffuse_texname, containingPath); addTextureIfNeeded(matNode, "map_Ks", mat.specular_texname, containingPath); addTextureIfNeeded(matNode, "map_Ns", mat.specular_highlight_texname, containingPath, true); addTextureIfNeeded(matNode, "map_bump", mat.bump_texname, containingPath); addTextureIfNeeded(matNode, "map_d", mat.alpha_texname, containingPath, true); sgMaterials.push_back(matNodePtr); } return sgMaterials; } void importOBJ(const std::shared_ptr<Node> &world, const FileName &fileName) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; auto containingPath = fileName.path().str() + '/'; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, fileName.c_str(), containingPath.c_str()); if (!err.empty()) std::cerr << "#ospsg: obj parsing warning(s)...\n" << err << std::endl; if (!ret) { std::cerr << "#ospsg: FATAL error parsing obj file, no geometry added" << " to the scene!" << std::endl; return; } auto sgMaterials = createSgMaterials(materials, containingPath); std::string base_name = fileName.name() + '_'; int shapeId = 0; for (auto &shape : shapes) { for (int numVertsInFace : shape.mesh.num_face_vertices) { if (numVertsInFace != 3) { std::cerr << "Warning: more thant 3 verts in face!"; PRINT(numVertsInFace); } } auto name = base_name + std::to_string(shapeId++) + '_' + shape.name; auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>(); auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>(); auto numSrcIndices = shape.mesh.indices.size(); v->v.reserve(numSrcIndices); auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>(); vi->v.reserve(numSrcIndices / 3); auto vn = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>(); vn->v.reserve(numSrcIndices); auto vt = createNode("texcoord","DataVector2f")->nodeAs<DataVector2f>(); vt->v.reserve(numSrcIndices); for (int i = 0; i < shape.mesh.indices.size(); i += 3) { auto idx0 = shape.mesh.indices[i+0]; auto idx1 = shape.mesh.indices[i+1]; auto idx2 = shape.mesh.indices[i+2]; auto prim = vec3i(i+0, i+1, i+2); vi->push_back(prim); v->push_back(vec3f(attrib.vertices[idx0.vertex_index*3+0], attrib.vertices[idx0.vertex_index*3+1], attrib.vertices[idx0.vertex_index*3+2])); v->push_back(vec3f(attrib.vertices[idx1.vertex_index*3+0], attrib.vertices[idx1.vertex_index*3+1], attrib.vertices[idx1.vertex_index*3+2])); v->push_back(vec3f(attrib.vertices[idx2.vertex_index*3+0], attrib.vertices[idx2.vertex_index*3+1], attrib.vertices[idx2.vertex_index*3+2])); if (!attrib.normals.empty()) { vn->push_back(vec3f(attrib.normals[idx0.normal_index*3+0], attrib.normals[idx0.normal_index*3+1], attrib.normals[idx0.normal_index*3+2])); vn->push_back(vec3f(attrib.normals[idx1.normal_index*3+0], attrib.normals[idx1.normal_index*3+1], attrib.normals[idx1.normal_index*3+2])); vn->push_back(vec3f(attrib.normals[idx2.normal_index*3+0], attrib.normals[idx2.normal_index*3+1], attrib.normals[idx2.normal_index*3+2])); } if (!attrib.texcoords.empty()) { vt->push_back(vec2f(attrib.texcoords[idx0.texcoord_index*2+0], attrib.texcoords[idx0.texcoord_index*2+1])); vt->push_back(vec2f(attrib.texcoords[idx1.texcoord_index*2+0], attrib.texcoords[idx1.texcoord_index*2+1])); vt->push_back(vec2f(attrib.texcoords[idx2.texcoord_index*2+0], attrib.texcoords[idx2.texcoord_index*2+1])); } } mesh->add(v); mesh->add(vi); if(!vn->empty()) mesh->add(vn); if(!vt->empty()) mesh->add(vt); auto matIdx = shape.mesh.material_ids[0]; if (!sgMaterials.empty()) { if (matIdx >= 0) mesh->setChild("material", sgMaterials[matIdx]); else mesh->setChild("material", sgMaterials[0]); } auto model = createNode(name + "_model", "Model"); model->add(mesh); auto instance = createNode(name + "_instance", "Instance"); instance->setChild("model", model); model->setParent(instance); world->add(instance); } } } // ::ospray::sg } // ::ospray <commit_msg>format importOBJ.cpp<commit_after>// ======================================================================== // // Copyright 2009-2017 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. // // ======================================================================== // #undef NDEBUG // sg #include "SceneGraph.h" #include "sg/common/Texture2D.h" #include "sg/geometry/TriangleMesh.h" #define TINYOBJLOADER_IMPLEMENTATION // define this in only *one* .cc #include "../3rdParty/tiny_obj_loader.h" #include <cstring> #include <sstream> namespace ospray { namespace sg { std::shared_ptr<Texture2D> loadTexture(const FileName &fullPath, const bool preferLinear = false) { std::shared_ptr<Texture2D> tex = Texture2D::load(fullPath, preferLinear); if (!tex) std::cout << "could not load texture " << fullPath.str() << " !\n"; return tex; } void addTextureIfNeeded(Material &node, const std::string &type, const FileName &texName, const FileName &containingPath, bool preferLinear = false) { if (!texName.str().empty()) { auto tex = loadTexture(containingPath + texName, preferLinear); if (tex) { tex->setName(type); node.setChild(type, tex); } } } static inline float parseFloatString(std::string valueString) { std::stringstream valueStream(valueString); float value; valueStream >> value; return value; } static inline vec3f parseVec3fString(std::string valueString) { std::stringstream valueStream(valueString); vec3f value; valueStream >> value.x >> value.y >> value.z; return value; } static inline void parseParameterString(std::string typeAndValueString, std::string &paramType, ospcommon::utility::Any &paramValue) { std::stringstream typeAndValueStream(typeAndValueString); typeAndValueStream >> paramType; std::string paramValueString; getline(typeAndValueStream, paramValueString); if (paramType == "float") { paramValue = parseFloatString(paramValueString); } else if (paramType == "vec3f") { paramValue = parseVec3fString(paramValueString); } else { // Unknown type. paramValue = typeAndValueString; } } static inline std::vector<std::shared_ptr<Material>> createSgMaterials( std::vector<tinyobj::material_t> &mats, const FileName &containingPath) { std::vector<std::shared_ptr<Material>> sgMaterials; for (auto &mat : mats) { auto matNodePtr = createNode(mat.name, "Material")->nodeAs<Material>(); auto &matNode = *matNodePtr; for (auto &param : mat.unknown_parameter) { if (param.first == "type") { matNode["type"].setValue(param.second); std::cout << "Creating material node of type " << param.second << std::endl; } else { std::string paramType; ospcommon::utility::Any paramValue; parseParameterString(param.second, paramType, paramValue); matNode.createChildWithValue(param.first, paramType, paramValue); std::cout << "Parsed parameter " << param.first << " of type " << paramType << std::endl; } } matNode["d"].setValue(mat.dissolve); matNode["Ka"].setValue( vec3f(mat.ambient[0], mat.ambient[1], mat.ambient[2])); matNode["Kd"].setValue( vec3f(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2])); matNode["Ks"].setValue( vec3f(mat.specular[0], mat.specular[1], mat.specular[2])); addTextureIfNeeded( matNode, "map_Ka", mat.ambient_texname, containingPath); addTextureIfNeeded( matNode, "map_Kd", mat.diffuse_texname, containingPath); addTextureIfNeeded( matNode, "map_Ks", mat.specular_texname, containingPath); addTextureIfNeeded(matNode, "map_Ns", mat.specular_highlight_texname, containingPath, true); addTextureIfNeeded( matNode, "map_bump", mat.bump_texname, containingPath); addTextureIfNeeded( matNode, "map_d", mat.alpha_texname, containingPath, true); sgMaterials.push_back(matNodePtr); } return sgMaterials; } void importOBJ(const std::shared_ptr<Node> &world, const FileName &fileName) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; auto containingPath = fileName.path().str() + '/'; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, fileName.c_str(), containingPath.c_str()); if (!err.empty()) std::cerr << "#ospsg: obj parsing warning(s)...\n" << err << std::endl; if (!ret) { std::cerr << "#ospsg: FATAL error parsing obj file, no geometry added" << " to the scene!" << std::endl; return; } auto sgMaterials = createSgMaterials(materials, containingPath); std::string base_name = fileName.name() + '_'; int shapeId = 0; for (auto &shape : shapes) { for (int numVertsInFace : shape.mesh.num_face_vertices) { if (numVertsInFace != 3) { std::cerr << "Warning: more thant 3 verts in face!"; PRINT(numVertsInFace); } } auto name = base_name + std::to_string(shapeId++) + '_' + shape.name; auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>(); auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>(); auto numSrcIndices = shape.mesh.indices.size(); v->v.reserve(numSrcIndices); auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>(); vi->v.reserve(numSrcIndices / 3); auto vn = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>(); vn->v.reserve(numSrcIndices); auto vt = createNode("texcoord", "DataVector2f")->nodeAs<DataVector2f>(); vt->v.reserve(numSrcIndices); for (int i = 0; i < shape.mesh.indices.size(); i += 3) { auto idx0 = shape.mesh.indices[i + 0]; auto idx1 = shape.mesh.indices[i + 1]; auto idx2 = shape.mesh.indices[i + 2]; auto prim = vec3i(i + 0, i + 1, i + 2); vi->push_back(prim); v->push_back(vec3f(attrib.vertices[idx0.vertex_index * 3 + 0], attrib.vertices[idx0.vertex_index * 3 + 1], attrib.vertices[idx0.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx1.vertex_index * 3 + 0], attrib.vertices[idx1.vertex_index * 3 + 1], attrib.vertices[idx1.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx2.vertex_index * 3 + 0], attrib.vertices[idx2.vertex_index * 3 + 1], attrib.vertices[idx2.vertex_index * 3 + 2])); if (!attrib.normals.empty()) { vn->push_back(vec3f(attrib.normals[idx0.normal_index * 3 + 0], attrib.normals[idx0.normal_index * 3 + 1], attrib.normals[idx0.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx1.normal_index * 3 + 0], attrib.normals[idx1.normal_index * 3 + 1], attrib.normals[idx1.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx2.normal_index * 3 + 0], attrib.normals[idx2.normal_index * 3 + 1], attrib.normals[idx2.normal_index * 3 + 2])); } if (!attrib.texcoords.empty()) { vt->push_back(vec2f(attrib.texcoords[idx0.texcoord_index * 2 + 0], attrib.texcoords[idx0.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx1.texcoord_index * 2 + 0], attrib.texcoords[idx1.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx2.texcoord_index * 2 + 0], attrib.texcoords[idx2.texcoord_index * 2 + 1])); } } mesh->add(v); mesh->add(vi); if (!vn->empty()) mesh->add(vn); if (!vt->empty()) mesh->add(vt); auto matIdx = shape.mesh.material_ids[0]; if (!sgMaterials.empty()) { if (matIdx >= 0) mesh->setChild("material", sgMaterials[matIdx]); else mesh->setChild("material", sgMaterials[0]); } auto model = createNode(name + "_model", "Model"); model->add(mesh); auto instance = createNode(name + "_instance", "Instance"); instance->setChild("model", model); model->setParent(instance); world->add(instance); } } } // ::ospray::sg } // ::ospray <|endoftext|>
<commit_before>#pragma once /// @file /// /// @brief Digital IO for the LPC1100 series microcontrollers. /// /// @remarks Because the I2C pins (PIO0_4/SCL and PIO0_5/SDA) have built-in non-programmable open-drain circuitry, it /// is not possible to use these physical pins as digital outputs without an external pull-up resistor. They /// however remain configurable as digital inputs. #include <rtl/mmio.hpp> #include <rtl/intrinsics.hpp> #include <hal/digital_io.hpp> #include <hal/lpc1100/physical_io.hpp> namespace hal::lpc1100 { template <pin pin> class digital_input; template <pin pin> class digital_output; namespace digital_io_detail { inline auto SYSAHBCLKCTRL() { return rtl::mmio<rtl::u32>{0x40048080}; } // move this general resource management stuff to a separate class // which can monitor exactly which resources are used and turn the clocks on and off accordingly? // this would have to be an internal object somehow static inline int gpio_refcount = 0; inline auto acquire_gpio() { rtl::intrinsics::non_preemptible([](){ if (gpio_refcount++ == 0) { SYSAHBCLKCTRL().set_bit<6>(); } }); } inline auto release_gpio() { rtl::intrinsics::non_preemptible([](){ if (--gpio_refcount == 0) { SYSAHBCLKCTRL().clear_bit<6>(); } }); } template <pin pin, rtl::uptr gpio_ptr, std::size_t port_no> class basic_digital_input : public hal::digital_input<basic_digital_input<pin, gpio_ptr, port_no>> { private: using physical_io_t = typename hal::lpc1100::physical_io<pin>; physical_io_t physical_io; public: using termination = typename physical_io_t::termination; using options = typename physical_io_t::digital_input_options; basic_digital_input(termination termination, options options = options::none) : physical_io(termination, options) { acquire_gpio(); DIR().template clear<port_mask>(); } ~basic_digital_input() { release_gpio(); } auto state() { return DATA().read() ? hal::logic_level::high : hal::logic_level::low; } private: static constexpr auto port_mask = 1 << port_no; static auto DATA() { return rtl::mmio<rtl::u32>{gpio_ptr + 4 * port_mask}; } static auto DIR() { return rtl::mmio<rtl::u32>{gpio_ptr + 0x8000}; } }; template <pin pin, rtl::uptr gpio_ptr, std::size_t port_no> class basic_digital_output : public hal::digital_output<basic_digital_output<pin, gpio_ptr, port_no>> { private: using physical_io_t = typename hal::lpc1100::physical_io<pin>; physical_io_t physical_io; public: using options = typename physical_io_t::digital_output_options; basic_digital_output(hal::logic_level initial_level, options options = options::none) : physical_io(options) { acquire_gpio(); DIR().template set<port_mask>(); this->drive(initial_level); } ~basic_digital_output() { release_gpio(); } auto drive_low() { DATA().clear(); } auto drive_high() { DATA().set(); } private: static constexpr auto port_mask = 1 << port_no; static auto DATA() { return rtl::mmio<rtl::u32>{gpio_ptr + 4 * port_mask}; } static auto DIR() { return rtl::mmio<rtl::u32>{gpio_ptr + 0x8000}; } }; } #define DIGITAL_INPUT(PIN, GPIO, PORT_NO) \ template <> class digital_input<PIN> : public digital_io_detail::basic_digital_input<PIN, GPIO, PORT_NO> {\ using digital_io_detail::basic_digital_input<PIN, GPIO, PORT_NO>::basic_digital_input;\ }; #define DIGITAL_OUTPUT(PIN, GPIO, PORT_NO) \ template <> class digital_output<PIN> : public digital_io_detail::basic_digital_output<PIN, GPIO, PORT_NO> {\ using digital_io_detail::basic_digital_output<PIN, GPIO, PORT_NO>::basic_digital_output;\ }; #define DIGITAL_IO(PIN, GPIO, PORT_NO) \ DIGITAL_INPUT(PIN, GPIO, PORT_NO) \ DIGITAL_OUTPUT(PIN, GPIO, PORT_NO) DIGITAL_IO(pin::PIO0_0, 0x50000000, 0) DIGITAL_IO(pin::PIO0_1, 0x50000000, 1) DIGITAL_IO(pin::PIO0_2, 0x50000000, 2) DIGITAL_IO(pin::PIO0_3, 0x50000000, 3) DIGITAL_INPUT(pin::PIO0_4, 0x50000000, 4) DIGITAL_INPUT(pin::PIO0_5, 0x50000000, 5) DIGITAL_IO(pin::PIO0_6, 0x50000000, 6) DIGITAL_IO(pin::PIO0_7, 0x50000000, 7) DIGITAL_IO(pin::PIO0_8, 0x50000000, 8) DIGITAL_IO(pin::PIO0_9, 0x50000000, 9) DIGITAL_IO(pin::PIO0_10, 0x50000000, 10) DIGITAL_IO(pin::PIO0_11, 0x50000000, 11) DIGITAL_IO(pin::PIO1_0, 0x50010000, 0) DIGITAL_IO(pin::PIO1_1, 0x50010000, 1) DIGITAL_IO(pin::PIO1_2, 0x50010000, 2) DIGITAL_IO(pin::PIO1_3, 0x50010000, 3) DIGITAL_IO(pin::PIO1_4, 0x50010000, 4) DIGITAL_IO(pin::PIO1_5, 0x50010000, 5) DIGITAL_IO(pin::PIO1_6, 0x50010000, 6) DIGITAL_IO(pin::PIO1_7, 0x50010000, 7) DIGITAL_IO(pin::PIO1_8, 0x50010000, 8) DIGITAL_IO(pin::PIO1_9, 0x50010000, 9) DIGITAL_IO(pin::PIO1_10, 0x50010000, 10) DIGITAL_IO(pin::PIO1_11, 0x50010000, 11) DIGITAL_IO(pin::PIO2_0, 0x50020000, 0) DIGITAL_IO(pin::PIO2_1, 0x50020000, 1) DIGITAL_IO(pin::PIO2_2, 0x50020000, 2) DIGITAL_IO(pin::PIO2_3, 0x50020000, 3) DIGITAL_IO(pin::PIO2_4, 0x50020000, 4) DIGITAL_IO(pin::PIO2_5, 0x50020000, 5) DIGITAL_IO(pin::PIO2_6, 0x50020000, 6) DIGITAL_IO(pin::PIO2_7, 0x50020000, 7) DIGITAL_IO(pin::PIO2_8, 0x50020000, 8) DIGITAL_IO(pin::PIO2_9, 0x50020000, 9) DIGITAL_IO(pin::PIO2_10, 0x50020000, 10) DIGITAL_IO(pin::PIO2_11, 0x50020000, 11) DIGITAL_IO(pin::PIO3_0, 0x50030000, 0) DIGITAL_IO(pin::PIO3_1, 0x50030000, 1) DIGITAL_IO(pin::PIO3_2, 0x50030000, 2) DIGITAL_IO(pin::PIO3_3, 0x50030000, 3) DIGITAL_IO(pin::PIO3_4, 0x50030000, 4) DIGITAL_IO(pin::PIO3_5, 0x50030000, 5) #undef DIGITAL_IO #undef DIGITAL_OUTPUT #undef DIGITAL_INPUT } <commit_msg>Simplify some template code<commit_after>#pragma once /// @file /// /// @brief Digital IO for the LPC1100 series microcontrollers. /// /// @remarks Because the I2C pins (PIO0_4/SCL and PIO0_5/SDA) have built-in non-programmable open-drain circuitry, it /// is not possible to use these physical pins as digital outputs without an external pull-up resistor. They /// however remain configurable as digital inputs. #include <rtl/mmio.hpp> #include <rtl/intrinsics.hpp> #include <hal/digital_io.hpp> #include <hal/lpc1100/physical_io.hpp> namespace hal::lpc1100 { template <pin pin> class digital_input; template <pin pin> class digital_output; namespace digital_io_detail { inline auto SYSAHBCLKCTRL() { return rtl::mmio<rtl::u32>{0x40048080}; } // move this general resource management stuff to a separate class // which can monitor exactly which resources are used and turn the clocks on and off accordingly? // this would have to be an internal object somehow static inline int gpio_refcount = 0; inline auto acquire_gpio() { rtl::intrinsics::non_preemptible([](){ if (gpio_refcount++ == 0) { SYSAHBCLKCTRL().set_bit<6>(); } }); } inline auto release_gpio() { rtl::intrinsics::non_preemptible([](){ if (--gpio_refcount == 0) { SYSAHBCLKCTRL().clear_bit<6>(); } }); } template <pin pin, rtl::uptr gpio_ptr, std::size_t port_no> class basic_digital_input : public hal::digital_input<basic_digital_input<pin, gpio_ptr, port_no>> { private: hal::lpc1100::physical_io<pin> physical_io; public: using termination = typename decltype(physical_io)::termination; using options = typename decltype(physical_io)::digital_input_options; basic_digital_input(termination termination, options options = options::none) : physical_io(termination, options) { acquire_gpio(); DIR().template clear<port_mask>(); } ~basic_digital_input() { release_gpio(); } auto state() { return DATA().read() ? hal::logic_level::high : hal::logic_level::low; } private: static constexpr auto port_mask = 1 << port_no; static auto DATA() { return rtl::mmio<rtl::u32>{gpio_ptr + 4 * port_mask}; } static auto DIR() { return rtl::mmio<rtl::u32>{gpio_ptr + 0x8000}; } }; template <pin pin, rtl::uptr gpio_ptr, std::size_t port_no> class basic_digital_output : public hal::digital_output<basic_digital_output<pin, gpio_ptr, port_no>> { private: hal::lpc1100::physical_io<pin> physical_io; public: using options = typename decltype(physical_io)::digital_output_options; basic_digital_output(hal::logic_level initial_level, options options = options::none) : physical_io(options) { acquire_gpio(); DIR().template set<port_mask>(); this->drive(initial_level); } ~basic_digital_output() { release_gpio(); } auto drive_low() { DATA().clear(); } auto drive_high() { DATA().set(); } private: static constexpr auto port_mask = 1 << port_no; static auto DATA() { return rtl::mmio<rtl::u32>{gpio_ptr + 4 * port_mask}; } static auto DIR() { return rtl::mmio<rtl::u32>{gpio_ptr + 0x8000}; } }; } #define DIGITAL_INPUT(PIN, GPIO, PORT_NO) \ template <> class digital_input<PIN> : public digital_io_detail::basic_digital_input<PIN, GPIO, PORT_NO> {\ using digital_io_detail::basic_digital_input<PIN, GPIO, PORT_NO>::basic_digital_input;\ }; #define DIGITAL_OUTPUT(PIN, GPIO, PORT_NO) \ template <> class digital_output<PIN> : public digital_io_detail::basic_digital_output<PIN, GPIO, PORT_NO> {\ using digital_io_detail::basic_digital_output<PIN, GPIO, PORT_NO>::basic_digital_output;\ }; #define DIGITAL_IO(PIN, GPIO, PORT_NO) \ DIGITAL_INPUT(PIN, GPIO, PORT_NO) \ DIGITAL_OUTPUT(PIN, GPIO, PORT_NO) DIGITAL_IO(pin::PIO0_0, 0x50000000, 0) DIGITAL_IO(pin::PIO0_1, 0x50000000, 1) DIGITAL_IO(pin::PIO0_2, 0x50000000, 2) DIGITAL_IO(pin::PIO0_3, 0x50000000, 3) DIGITAL_INPUT(pin::PIO0_4, 0x50000000, 4) DIGITAL_INPUT(pin::PIO0_5, 0x50000000, 5) DIGITAL_IO(pin::PIO0_6, 0x50000000, 6) DIGITAL_IO(pin::PIO0_7, 0x50000000, 7) DIGITAL_IO(pin::PIO0_8, 0x50000000, 8) DIGITAL_IO(pin::PIO0_9, 0x50000000, 9) DIGITAL_IO(pin::PIO0_10, 0x50000000, 10) DIGITAL_IO(pin::PIO0_11, 0x50000000, 11) DIGITAL_IO(pin::PIO1_0, 0x50010000, 0) DIGITAL_IO(pin::PIO1_1, 0x50010000, 1) DIGITAL_IO(pin::PIO1_2, 0x50010000, 2) DIGITAL_IO(pin::PIO1_3, 0x50010000, 3) DIGITAL_IO(pin::PIO1_4, 0x50010000, 4) DIGITAL_IO(pin::PIO1_5, 0x50010000, 5) DIGITAL_IO(pin::PIO1_6, 0x50010000, 6) DIGITAL_IO(pin::PIO1_7, 0x50010000, 7) DIGITAL_IO(pin::PIO1_8, 0x50010000, 8) DIGITAL_IO(pin::PIO1_9, 0x50010000, 9) DIGITAL_IO(pin::PIO1_10, 0x50010000, 10) DIGITAL_IO(pin::PIO1_11, 0x50010000, 11) DIGITAL_IO(pin::PIO2_0, 0x50020000, 0) DIGITAL_IO(pin::PIO2_1, 0x50020000, 1) DIGITAL_IO(pin::PIO2_2, 0x50020000, 2) DIGITAL_IO(pin::PIO2_3, 0x50020000, 3) DIGITAL_IO(pin::PIO2_4, 0x50020000, 4) DIGITAL_IO(pin::PIO2_5, 0x50020000, 5) DIGITAL_IO(pin::PIO2_6, 0x50020000, 6) DIGITAL_IO(pin::PIO2_7, 0x50020000, 7) DIGITAL_IO(pin::PIO2_8, 0x50020000, 8) DIGITAL_IO(pin::PIO2_9, 0x50020000, 9) DIGITAL_IO(pin::PIO2_10, 0x50020000, 10) DIGITAL_IO(pin::PIO2_11, 0x50020000, 11) DIGITAL_IO(pin::PIO3_0, 0x50030000, 0) DIGITAL_IO(pin::PIO3_1, 0x50030000, 1) DIGITAL_IO(pin::PIO3_2, 0x50030000, 2) DIGITAL_IO(pin::PIO3_3, 0x50030000, 3) DIGITAL_IO(pin::PIO3_4, 0x50030000, 4) DIGITAL_IO(pin::PIO3_5, 0x50030000, 5) #undef DIGITAL_IO #undef DIGITAL_OUTPUT #undef DIGITAL_INPUT } <|endoftext|>
<commit_before>#pragma once /// @file /// /// @brief Digital IO for the LPC1100 series microcontrollers. /// /// @remarks Because the I2C pins (PIO0_4/SCL and PIO0_5/SDA) have built-in non-programmable open-drain circuitry, it /// is not possible to use these physical pins as digital outputs without an external pull-up resistor. They /// however remain configurable as digital inputs. #include <rtl/mmio.hpp> #include <rtl/intrinsics.hpp> #include <hal/digital_io.hpp> #include <hal/lpc1100/physical_io.hpp> namespace hal::lpc1100 { template <pin pin> class digital_input; template <pin pin> class digital_output; namespace digital_io_detail { inline auto SYSAHBCLKCTRL() { return rtl::mmio<rtl::u32>{0x40048080}; } // move this general resource management stuff to a separate class // which can monitor exactly which resources are used and turn the clocks on and off accordingly? // this would have to be an internal object somehow static inline int gpio_refcount = 0; inline auto acquire_gpio() { rtl::intrinsics::non_preemptible([](){ if (gpio_refcount++ == 0) { SYSAHBCLKCTRL().set_bit<6>(); } }); } inline auto release_gpio() { rtl::intrinsics::non_preemptible([](){ if (--gpio_refcount == 0) { SYSAHBCLKCTRL().clear_bit<6>(); } }); } template <pin pin, rtl::uptr gpio_ptr, std::size_t port_no> class basic_digital_input : public hal::digital_input<basic_digital_input<pin, gpio_ptr, port_no>> { private: hal::lpc1100::physical_io<pin> physical_io; public: using termination = typename decltype(physical_io)::termination; using options = typename decltype(physical_io)::digital_input_options; basic_digital_input(termination termination, options options = options::none) : physical_io(termination, options) { acquire_gpio(); DIR().template clear<port_mask>(); } ~basic_digital_input() { release_gpio(); } auto state() { return DATA().read() ? hal::logic_level::high : hal::logic_level::low; } private: static constexpr auto port_mask = 1 << port_no; static auto DATA() { return rtl::mmio<rtl::u32>{gpio_ptr + 4 * port_mask}; } static auto DIR() { return rtl::mmio<rtl::u32>{gpio_ptr + 0x8000}; } }; template <pin pin, rtl::uptr gpio_ptr, std::size_t port_no> class basic_digital_output : public hal::digital_output<basic_digital_output<pin, gpio_ptr, port_no>> { private: hal::lpc1100::physical_io<pin> physical_io; public: using options = typename decltype(physical_io)::digital_output_options; basic_digital_output(hal::logic_level initial_level, options options = options::none) : physical_io(options) { acquire_gpio(); DIR().template set<port_mask>(); this->drive(initial_level); } ~basic_digital_output() { release_gpio(); } auto drive_low() { DATA().clear(); } auto drive_high() { DATA().set(); } private: static constexpr auto port_mask = 1 << port_no; static auto DATA() { return rtl::mmio<rtl::u32>{gpio_ptr + 4 * port_mask}; } static auto DIR() { return rtl::mmio<rtl::u32>{gpio_ptr + 0x8000}; } }; } #define DIGITAL_INPUT(PIN, GPIO, PORT_NO) \ template <> class digital_input<PIN> : public digital_io_detail::basic_digital_input<PIN, GPIO, PORT_NO> {\ using digital_io_detail::basic_digital_input<PIN, GPIO, PORT_NO>::basic_digital_input;\ }; #define DIGITAL_OUTPUT(PIN, GPIO, PORT_NO) \ template <> class digital_output<PIN> : public digital_io_detail::basic_digital_output<PIN, GPIO, PORT_NO> {\ using digital_io_detail::basic_digital_output<PIN, GPIO, PORT_NO>::basic_digital_output;\ }; #define DIGITAL_IO(PIN, GPIO, PORT_NO) \ DIGITAL_INPUT(PIN, GPIO, PORT_NO) \ DIGITAL_OUTPUT(PIN, GPIO, PORT_NO) DIGITAL_IO(pin::PIO0_0, 0x50000000, 0) DIGITAL_IO(pin::PIO0_1, 0x50000000, 1) DIGITAL_IO(pin::PIO0_2, 0x50000000, 2) DIGITAL_IO(pin::PIO0_3, 0x50000000, 3) DIGITAL_INPUT(pin::PIO0_4, 0x50000000, 4) DIGITAL_INPUT(pin::PIO0_5, 0x50000000, 5) DIGITAL_IO(pin::PIO0_6, 0x50000000, 6) DIGITAL_IO(pin::PIO0_7, 0x50000000, 7) DIGITAL_IO(pin::PIO0_8, 0x50000000, 8) DIGITAL_IO(pin::PIO0_9, 0x50000000, 9) DIGITAL_IO(pin::PIO0_10, 0x50000000, 10) DIGITAL_IO(pin::PIO0_11, 0x50000000, 11) DIGITAL_IO(pin::PIO1_0, 0x50010000, 0) DIGITAL_IO(pin::PIO1_1, 0x50010000, 1) DIGITAL_IO(pin::PIO1_2, 0x50010000, 2) DIGITAL_IO(pin::PIO1_3, 0x50010000, 3) DIGITAL_IO(pin::PIO1_4, 0x50010000, 4) DIGITAL_IO(pin::PIO1_5, 0x50010000, 5) DIGITAL_IO(pin::PIO1_6, 0x50010000, 6) DIGITAL_IO(pin::PIO1_7, 0x50010000, 7) DIGITAL_IO(pin::PIO1_8, 0x50010000, 8) DIGITAL_IO(pin::PIO1_9, 0x50010000, 9) DIGITAL_IO(pin::PIO1_10, 0x50010000, 10) DIGITAL_IO(pin::PIO1_11, 0x50010000, 11) DIGITAL_IO(pin::PIO2_0, 0x50020000, 0) DIGITAL_IO(pin::PIO2_1, 0x50020000, 1) DIGITAL_IO(pin::PIO2_2, 0x50020000, 2) DIGITAL_IO(pin::PIO2_3, 0x50020000, 3) DIGITAL_IO(pin::PIO2_4, 0x50020000, 4) DIGITAL_IO(pin::PIO2_5, 0x50020000, 5) DIGITAL_IO(pin::PIO2_6, 0x50020000, 6) DIGITAL_IO(pin::PIO2_7, 0x50020000, 7) DIGITAL_IO(pin::PIO2_8, 0x50020000, 8) DIGITAL_IO(pin::PIO2_9, 0x50020000, 9) DIGITAL_IO(pin::PIO2_10, 0x50020000, 10) DIGITAL_IO(pin::PIO2_11, 0x50020000, 11) DIGITAL_IO(pin::PIO3_0, 0x50030000, 0) DIGITAL_IO(pin::PIO3_1, 0x50030000, 1) DIGITAL_IO(pin::PIO3_2, 0x50030000, 2) DIGITAL_IO(pin::PIO3_3, 0x50030000, 3) DIGITAL_IO(pin::PIO3_4, 0x50030000, 4) DIGITAL_IO(pin::PIO3_5, 0x50030000, 5) #undef DIGITAL_IO #undef DIGITAL_OUTPUT #undef DIGITAL_INPUT } <commit_msg>Test base class instead of member to benefit from empty base class optimization<commit_after>#pragma once /// @file /// /// @brief Digital IO for the LPC1100 series microcontrollers. /// /// @remarks Because the I2C pins (PIO0_4/SCL and PIO0_5/SDA) have built-in non-programmable open-drain circuitry, it /// is not possible to use these physical pins as digital outputs without an external pull-up resistor. They /// however remain configurable as digital inputs. #include <rtl/mmio.hpp> #include <rtl/intrinsics.hpp> #include <hal/digital_io.hpp> #include <hal/lpc1100/physical_io.hpp> namespace hal::lpc1100 { template <pin pin> class digital_input; template <pin pin> class digital_output; namespace digital_io_detail { inline auto SYSAHBCLKCTRL() { return rtl::mmio<rtl::u32>{0x40048080}; } // move this general resource management stuff to a separate class // which can monitor exactly which resources are used and turn the clocks on and off accordingly? // this would have to be an internal object somehow static inline int gpio_refcount = 0; inline auto acquire_gpio() { rtl::intrinsics::non_preemptible([](){ if (gpio_refcount++ == 0) { SYSAHBCLKCTRL().set_bit<6>(); } }); } inline auto release_gpio() { rtl::intrinsics::non_preemptible([](){ if (--gpio_refcount == 0) { SYSAHBCLKCTRL().clear_bit<6>(); } }); } template <pin pin, rtl::uptr gpio_ptr, std::size_t port_no> class basic_digital_input : public hal::digital_input<basic_digital_input<pin, gpio_ptr, port_no>>, private hal::lpc1100::physical_io<pin> { public: using termination = typename hal::lpc1100::physical_io<pin>::termination; using options = typename hal::lpc1100::physical_io<pin>::digital_input_options; basic_digital_input(termination termination, options options = options::none) : hal::lpc1100::physical_io<pin>(termination, options) { acquire_gpio(); DIR().template clear<port_mask>(); } ~basic_digital_input() { release_gpio(); } auto state() { return DATA().read() ? hal::logic_level::high : hal::logic_level::low; } private: static constexpr auto port_mask = 1 << port_no; static auto DATA() { return rtl::mmio<rtl::u32>{gpio_ptr + 4 * port_mask}; } static auto DIR() { return rtl::mmio<rtl::u32>{gpio_ptr + 0x8000}; } }; template <pin pin, rtl::uptr gpio_ptr, std::size_t port_no> class basic_digital_output : public hal::digital_output<basic_digital_output<pin, gpio_ptr, port_no>>, private hal::lpc1100::physical_io<pin> { public: using options = typename hal::lpc1100::physical_io<pin>::digital_output_options; basic_digital_output(hal::logic_level initial_level, options options = options::none) : hal::lpc1100::physical_io<pin>(options) { acquire_gpio(); DIR().template set<port_mask>(); this->drive(initial_level); } ~basic_digital_output() { release_gpio(); } auto drive_low() { DATA().clear(); } auto drive_high() { DATA().set(); } private: static constexpr auto port_mask = 1 << port_no; static auto DATA() { return rtl::mmio<rtl::u32>{gpio_ptr + 4 * port_mask}; } static auto DIR() { return rtl::mmio<rtl::u32>{gpio_ptr + 0x8000}; } }; } #define DIGITAL_INPUT(PIN, GPIO, PORT_NO) \ template <> class digital_input<PIN> : public digital_io_detail::basic_digital_input<PIN, GPIO, PORT_NO> {\ using digital_io_detail::basic_digital_input<PIN, GPIO, PORT_NO>::basic_digital_input;\ }; #define DIGITAL_OUTPUT(PIN, GPIO, PORT_NO) \ template <> class digital_output<PIN> : public digital_io_detail::basic_digital_output<PIN, GPIO, PORT_NO> {\ using digital_io_detail::basic_digital_output<PIN, GPIO, PORT_NO>::basic_digital_output;\ }; #define DIGITAL_IO(PIN, GPIO, PORT_NO) \ DIGITAL_INPUT(PIN, GPIO, PORT_NO) \ DIGITAL_OUTPUT(PIN, GPIO, PORT_NO) DIGITAL_IO(pin::PIO0_0, 0x50000000, 0) DIGITAL_IO(pin::PIO0_1, 0x50000000, 1) DIGITAL_IO(pin::PIO0_2, 0x50000000, 2) DIGITAL_IO(pin::PIO0_3, 0x50000000, 3) DIGITAL_INPUT(pin::PIO0_4, 0x50000000, 4) DIGITAL_INPUT(pin::PIO0_5, 0x50000000, 5) DIGITAL_IO(pin::PIO0_6, 0x50000000, 6) DIGITAL_IO(pin::PIO0_7, 0x50000000, 7) DIGITAL_IO(pin::PIO0_8, 0x50000000, 8) DIGITAL_IO(pin::PIO0_9, 0x50000000, 9) DIGITAL_IO(pin::PIO0_10, 0x50000000, 10) DIGITAL_IO(pin::PIO0_11, 0x50000000, 11) DIGITAL_IO(pin::PIO1_0, 0x50010000, 0) DIGITAL_IO(pin::PIO1_1, 0x50010000, 1) DIGITAL_IO(pin::PIO1_2, 0x50010000, 2) DIGITAL_IO(pin::PIO1_3, 0x50010000, 3) DIGITAL_IO(pin::PIO1_4, 0x50010000, 4) DIGITAL_IO(pin::PIO1_5, 0x50010000, 5) DIGITAL_IO(pin::PIO1_6, 0x50010000, 6) DIGITAL_IO(pin::PIO1_7, 0x50010000, 7) DIGITAL_IO(pin::PIO1_8, 0x50010000, 8) DIGITAL_IO(pin::PIO1_9, 0x50010000, 9) DIGITAL_IO(pin::PIO1_10, 0x50010000, 10) DIGITAL_IO(pin::PIO1_11, 0x50010000, 11) DIGITAL_IO(pin::PIO2_0, 0x50020000, 0) DIGITAL_IO(pin::PIO2_1, 0x50020000, 1) DIGITAL_IO(pin::PIO2_2, 0x50020000, 2) DIGITAL_IO(pin::PIO2_3, 0x50020000, 3) DIGITAL_IO(pin::PIO2_4, 0x50020000, 4) DIGITAL_IO(pin::PIO2_5, 0x50020000, 5) DIGITAL_IO(pin::PIO2_6, 0x50020000, 6) DIGITAL_IO(pin::PIO2_7, 0x50020000, 7) DIGITAL_IO(pin::PIO2_8, 0x50020000, 8) DIGITAL_IO(pin::PIO2_9, 0x50020000, 9) DIGITAL_IO(pin::PIO2_10, 0x50020000, 10) DIGITAL_IO(pin::PIO2_11, 0x50020000, 11) DIGITAL_IO(pin::PIO3_0, 0x50030000, 0) DIGITAL_IO(pin::PIO3_1, 0x50030000, 1) DIGITAL_IO(pin::PIO3_2, 0x50030000, 2) DIGITAL_IO(pin::PIO3_3, 0x50030000, 3) DIGITAL_IO(pin::PIO3_4, 0x50030000, 4) DIGITAL_IO(pin::PIO3_5, 0x50030000, 5) #undef DIGITAL_IO #undef DIGITAL_OUTPUT #undef DIGITAL_INPUT } <|endoftext|>
<commit_before>#include "filesystem.h" int FileSystem::createFile(const char *title, const char *srcFile) { /* objective: to create a file that can be written in multiple non-continuous sectors input: title: title of file srcFile: source file to read from return: 0: success 1: error effect: a new file is created in disk and directory entry is passed, if success */ TypeCastEntry entry; if (strlen(title) == 0) { std::cout << "File title: "; std::cin >> entry.entry.name; std::cin.ignore(32767, '\n'); } else { strcpy(entry.entry.name, title); } // default parent is root entry.entry.parent = currentDir; // not a directory, is a file entry.entry.type = 'F'; // file contents & size char file_content[MAX_FILE_SIZE]; if (strlen(srcFile) == 0) { std::cout << "Enter content of file:" << std::endl; std::cin.getline(file_content, sizeof(file_content)); entry.entry.size = strlen(file_content); } else { std::ifstream fsrc; fsrc.open(srcFile, std::ios::binary | std::ios::in); fsrc.read(file_content, MAX_FILE_SIZE); fsrc.close(); fsrc.open(srcFile, std::ios::binary | std::ios::in | std::ios::ate); entry.entry.size = fsrc.tellg(); fsrc.close(); } if (entry.entry.size < 0) { return 1; } // find sectors to write in int sectorsNeeded = entry.entry.size / kSectorSize + 1; std::vector<int> sectorsFree(sectorsNeeded); if (findFreeSectors(sectorsNeeded, sectorsFree) == 1) { return 1; }; entry.entry.startsAt = sectorsFree[0]; char buf[kSectorSize]; // find position for file entry bool positionFound = false; int byteforEntry = 0; int sectorForEntry = 0; for (int s = 0; s < sectorsForDir; ++s) { readSector(currentDir + s, buf); for (int b = 0; b < kSectorSize; b += 32) { TypeCastEntry test; for (int k = 0; k < 32; ++k) { test.str[k] = buf[b+k]; } if (strlen(test.entry.name) == 0) { positionFound = true; sectorForEntry = s; byteforEntry = b; break; } else if (strcmp(test.entry.name, entry.entry.name) == 0) { std::cout << "File with same name already exists in directory." << std::endl; return 1; } } if (positionFound) break; } if (!positionFound) { std::cout << "Cannot contain more than " << sectorsForDir*16 << " entries" << std::endl; return 1; } // update buffer for (int i = byteforEntry, j = 0; j < 32; ++i, ++j) { buf[i] = entry.str[j]; } // write the file entry writeSector(currentDir + sectorForEntry, buf); updateStatus(currentDir + sectorForEntry, DIR_ENTRY); // write data and update sector status for (int i = 0; i < sectorsNeeded; ++i) { for (int j = 0; j < kSectorSize; ++j) { buf[j] = file_content[kSectorSize*i + j]; } writeSector(sectorsFree[i], buf); updateStatus(sectorsFree[i], (i != sectorsNeeded-1) ? sectorsFree[i+1] : 1); } std::cout << "CREATED FILE WITH" << std::endl; std::cout << "TITLE = " << entry.entry.name << std::endl; std::cout << "SIZE = " << entry.entry.size << " bytes" << std::endl; std::cout << "STORED IN SECTORS = "; for (int i = 0; i < sectorsNeeded; ++i) std::cout << sectorsFree[i] << " "; std::cout << std::endl; return 0; }<commit_msg>wrong calculation of sectorsNeeded <commit_after>#include "filesystem.h" int FileSystem::createFile(const char *title, const char *srcFile) { /* objective: to create a file that can be written in multiple non-continuous sectors input: title: title of file srcFile: source file to read from return: 0: success 1: error effect: a new file is created in disk and directory entry is passed, if success */ TypeCastEntry entry; if (strlen(title) == 0) { std::cout << "File title: "; std::cin >> entry.entry.name; std::cin.ignore(32767, '\n'); } else { strcpy(entry.entry.name, title); } // default parent is root entry.entry.parent = currentDir; // not a directory, is a file entry.entry.type = 'F'; // file contents & size char file_content[MAX_FILE_SIZE]; if (strlen(srcFile) == 0) { std::cout << "Enter content of file:" << std::endl; std::cin.getline(file_content, sizeof(file_content)); entry.entry.size = strlen(file_content); } else { std::ifstream fsrc; fsrc.open(srcFile, std::ios::binary | std::ios::in); fsrc.read(file_content, MAX_FILE_SIZE); fsrc.close(); fsrc.open(srcFile, std::ios::binary | std::ios::in | std::ios::ate); entry.entry.size = fsrc.tellg(); fsrc.close(); } if (entry.entry.size < 0) { return 1; } // find sectors to write in int sectorsNeeded = (entry.entry.size - 1) / kSectorSize + 1; std::vector<int> sectorsFree(sectorsNeeded); if (findFreeSectors(sectorsNeeded, sectorsFree) == 1) { return 1; }; entry.entry.startsAt = sectorsFree[0]; char buf[kSectorSize]; // find position for file entry bool positionFound = false; int byteforEntry = 0; int sectorForEntry = 0; for (int s = 0; s < sectorsForDir; ++s) { readSector(currentDir + s, buf); for (int b = 0; b < kSectorSize; b += 32) { TypeCastEntry test; for (int k = 0; k < 32; ++k) { test.str[k] = buf[b+k]; } if (strlen(test.entry.name) == 0) { positionFound = true; sectorForEntry = s; byteforEntry = b; break; } else if (strcmp(test.entry.name, entry.entry.name) == 0) { std::cout << "File with same name already exists in directory." << std::endl; return 1; } } if (positionFound) break; } if (!positionFound) { std::cout << "Cannot contain more than " << sectorsForDir*16 << " entries" << std::endl; return 1; } // update buffer for (int i = byteforEntry, j = 0; j < 32; ++i, ++j) { buf[i] = entry.str[j]; } // write the file entry writeSector(currentDir + sectorForEntry, buf); updateStatus(currentDir + sectorForEntry, DIR_ENTRY); // write data and update sector status for (int i = 0; i < sectorsNeeded; ++i) { for (int j = 0; j < kSectorSize; ++j) { buf[j] = file_content[kSectorSize*i + j]; } writeSector(sectorsFree[i], buf); updateStatus(sectorsFree[i], (i != sectorsNeeded-1) ? sectorsFree[i+1] : 1); } std::cout << "CREATED FILE WITH" << std::endl; std::cout << "TITLE = " << entry.entry.name << std::endl; std::cout << "SIZE = " << entry.entry.size << " bytes" << std::endl; std::cout << "STORED IN SECTORS = "; for (int i = 0; i < sectorsNeeded; ++i) std::cout << sectorsFree[i] << " "; std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2011 by Benedict Paten (benedictpaten@gmail.com) * * Released under the MIT license, see LICENSE.txt */ /* * sonLibKVDatabase_KyotoTycoon.cpp * * Created on: 5-1-11 * Author: epaull */ //Database functions #include "sonLibGlobalsInternal.h" #include "sonLibKVDatabasePrivate.h" #ifdef HAVE_KYOTO_TYCOON #include <ktremotedb.h> using namespace std; using namespace kyototycoon; /* * construct in the Tokyo Tyrant case means connect to the remote DB */ static RemoteDB *constructDB(stKVDatabaseConf *conf, bool create) { // we actually do need a local DB dir for Kyoto Tycoon to store the sequences file const char *dbDir = stKVDatabaseConf_getDir(conf); mkdir(dbDir, S_IRWXU); // just let open of database generate error (FIXME: would be better to make this report errors) char *databaseName = stString_print("%s/%s", dbDir, "data"); const char *dbRemote_Host = stKVDatabaseConf_getHost(conf); unsigned dbRemote_Port = stKVDatabaseConf_getPort(conf); int timeout = stKVDatabaseConf_getTimeout(conf); // new tycoon object RemoteDB rdb; // tcrdb open sets the host and port for the rdb object if (!rdb.open(dbRemote_Host, dbRemote_Port, timeout)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Opening connection to host: %s with error: %s", dbRemote_Host, rdb.error().name()); } free(databaseName); return rdb; } #ifdef NEVER_DEFINED not implemented yet -- copied from Tyrant... --test-- /* closes the remote DB connection and deletes the rdb object, but does not destroy the remote database */ static void destructDB(stKVDatabase *database) { if (rdb != NULL) { // close the connection if (!tcrdbclose(rdb)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Closing database error: %s", tcrdberrmsg(tcrdbecode(rdb))); } // delete the local in-memory object tcrdbdel(rdb); database->dbImpl = NULL; } } /* WARNING: destroys the remote database */ static void deleteDB(stKVDatabase *database) { TCRDB *rdb = database->dbImpl; if (rdb != NULL) { tcrdbvanish(rdb); } destructDB(database); // this removes all records from the remove database object } /* check if a record already exists */ static bool recordExists(TCRDB *rdb, int64_t key) { int32_t sp; if (tcrdbget(rdb, &key, sizeof(int64_t), &sp) == NULL) { return false; } else { return true; } } static bool containsRecord(stKVDatabase *database, int64_t key) { return recordExists(database->dbImpl, key); } /* uses tcrdbputkeep : if the record already exists it won't overwrite it */ static void insertRecord(stKVDatabase *database, int64_t key, const void *value, int64_t sizeOfRecord) { TCRDB *dbImpl = database->dbImpl; if (recordExists(dbImpl, key)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Attempt to insert a key in the database that already exists: %lld", (long long)key); } if (!tcrdbputkeep(dbImpl, &key, sizeof(int64_t), value, sizeOfRecord)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Inserting key/value to database error: %s", tcrdberrmsg(tcrdbecode(dbImpl))); } } /* tcrdbput will overwrite the record if it exists */ static void updateRecord(stKVDatabase *database, int64_t key, const void *value, int64_t sizeOfRecord) { TCRDB *dbImpl = database->dbImpl; if (!recordExists(dbImpl, key)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Attempt to update a key in the database that doesn't exists: %lld", (long long)key); } if (!tcrdbput(dbImpl, &key, sizeof(int64_t), value, sizeOfRecord)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Updating key/value to database error: %s", tcrdberrmsg(tcrdbecode(dbImpl))); } } static int64_t numberOfRecords(stKVDatabase *database) { TCRDB *dbImpl = database->dbImpl; return tcrdbrnum(dbImpl); } static void *getRecord2(stKVDatabase *database, int64_t key, int64_t *recordSize) { TCRDB *dbImpl = database->dbImpl; //Return value must be freed. int32_t i; void *record = tcrdbget(dbImpl, &key, sizeof(int64_t), &i); *recordSize = i; return record; } /* get a single non-string record */ static void *getRecord(stKVDatabase *database, int64_t key) { int64_t i; return getRecord2(database, key, &i); } /* get part of a string record */ static void *getPartialRecord(stKVDatabase *database, int64_t key, int64_t zeroBasedByteOffset, int64_t sizeInBytes, int64_t recordSize) { int64_t recordSize2; char *record = getRecord2(database, key, &recordSize2); if(recordSize2 != recordSize) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "The given record size is incorrect: %lld, should be %lld", (long long)recordSize, recordSize2); } if(record == NULL) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "The record does not exist: %lld for partial retrieval", (long long)key); } if(zeroBasedByteOffset < 0 || sizeInBytes < 0 || zeroBasedByteOffset + sizeInBytes > recordSize) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Partial record retrieval to out of bounds memory, record size: %lld, requested start: %lld, requested size: %lld", (long long)recordSize, (long long)zeroBasedByteOffset, (long long)sizeInBytes); } void *partialRecord = memcpy(st_malloc(sizeInBytes), record + zeroBasedByteOffset, sizeInBytes); free(record); return partialRecord; } static void removeRecord(stKVDatabase *database, int64_t key) { TCRDB *dbImpl = database->dbImpl; if (!tcrdbout(dbImpl, &key, sizeof(int64_t))) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Removing key/value to database error: %s", tcrdberrmsg(tcrdbecode(dbImpl))); } } static void startTransaction(stKVDatabase *database) { // transactions not supported in Tokyo Tyrant... return; } static void commitTransaction(stKVDatabase *database) { // transactions not supported in Tokyo Tyrant... return; } static void abortTransaction(stKVDatabase *database) { // transactions not supported in Tokyo Tyrant... return; } //initialisation function void stKVDatabase_initialise_tokyoTyrant(stKVDatabase *database, stKVDatabaseConf *conf, bool create) { database->dbImpl = constructDB(stKVDatabase_getConf(database), create); database->destruct = destructDB; database->delete = deleteDB; database->containsRecord = containsRecord; database->insertRecord = insertRecord; database->updateRecord = updateRecord; database->numberOfRecords = numberOfRecords; database->getRecord = getRecord; database->getRecord2 = getRecord2; database->getPartialRecord = getPartialRecord; database->removeRecord = removeRecord; database->startTransaction = startTransaction; database->commitTransaction = commitTransaction; database->abortTransaction = abortTransaction; } #endif #endif <commit_msg>--using the C (arguments) version of remote methods<commit_after>/* * Copyright (C) 2006-2011 by Benedict Paten (benedictpaten@gmail.com) * * Released under the MIT license, see LICENSE.txt */ /* * sonLibKVDatabase_KyotoTycoon.cpp * * Created on: 5-1-11 * Author: epaull * * Note: all the KT methods seem to have a C and a CPP version (in terms of the arguments) , * and for this implementation we're using the plain C versions as much as we can. */ //Database functions #include "sonLibGlobalsInternal.h" #include "sonLibKVDatabasePrivate.h" #ifdef HAVE_KYOTO_TYCOON #include <ktremotedb.h> using namespace std; using namespace kyototycoon; /* * construct in the Tokyo Tyrant case means connect to the remote DB */ static RemoteDB *constructDB(stKVDatabaseConf *conf, bool create) { // we actually do need a local DB dir for Kyoto Tycoon to store the sequences file const char *dbDir = stKVDatabaseConf_getDir(conf); mkdir(dbDir, S_IRWXU); // just let open of database generate error (FIXME: would be better to make this report errors) char *databaseName = stString_print("%s/%s", dbDir, "data"); const char *dbRemote_Host = stKVDatabaseConf_getHost(conf); unsigned dbRemote_Port = stKVDatabaseConf_getPort(conf); int timeout = stKVDatabaseConf_getTimeout(conf); // new tycoon object RemoteDB rdb; // tcrdb open sets the host and port for the rdb object if (!rdb.open(dbRemote_Host, dbRemote_Port, timeout)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Opening connection to host: %s with error: %s", dbRemote_Host, rdb.error().name()); } free(databaseName); return rdb; } /* closes the remote DB connection and deletes the rdb object, but does not destroy the remote database */ static void destructDB(stKVDatabase *database) { RemoteDB rdb = database->dbImpl; if (rdb != NULL) { // close the connection: first try a graceful close, then a forced close if (!rdb.close(true)) { if (!rdb.close(false)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Closing database error: %s",rdb.error().name()); } } // delete the local in-memory object database->dbImpl = NULL; } } /* WARNING: removes all records from the remote database */ static void deleteDB(stKVDatabase *database) { RemoteDB rdb = database->dbImpl; if (rdb != NULL) { rdb.clear(); } destructDB(database); // this removes all records from the remove database object } /* check if a record already exists */ static bool recordExists(RemoteDB rdb, int64_t key) { size_t sp; if (rdb.get(&key,sizeof(key), &sp) == NULL) return false; } else { return true; } } static bool containsRecord(stKVDatabase *database, int64_t key) { return recordExists(database->dbImpl, key); } static void insertRecord(stKVDatabase *database, int64_t key, const void *value, int64_t sizeOfRecord) { RemoteDB rdb = database->dbImpl; // add method: If the key already exists the record will not be modified and it'll return false if (!rdb.add(&key, sizeof(int64_t), value, sizeOfRecord)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Inserting key/value to database error: %s", rdb.error().name()); } } static void updateRecord(stKVDatabase *database, int64_t key, const void *value, int64_t sizeOfRecord) { RemoteDB rdb = database->dbImpl; // replace method: If the key doesn't already exist it won't be created, and we'll get an error if (!rdb.replace(&key, sizeof(int64_t), value, sizeOfRecord)) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Updating key/value to database error: %s", rdb.error().name()); } } static int64_t numberOfRecords(stKVDatabase *database) { RemoteDB rdb = database->dbImpl; return rdb.count(); } static void *getRecord2(stKVDatabase *database, int64_t key, int64_t *recordSize) { RemoteDB rdb = database->dbImpl; //Return value must be freed. size_t i; void *record = (void *)rdb.get(&key, sizeof(int64_t), &i); *recordSize = (int64_t)i; return record; } /* get a single non-string record */ static void *getRecord(stKVDatabase *database, int64_t key) { size_t i; return getRecord2(database, key, &i); } /* get part of a string record */ static void *getPartialRecord(stKVDatabase *database, int64_t key, int64_t zeroBasedByteOffset, int64_t sizeInBytes, int64_t recordSize) { int64_t recordSize2; char *record = getRecord2(database, key, &recordSize2); if(recordSize2 != recordSize) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "The given record size is incorrect: %lld, should be %lld", (long long)recordSize, recordSize2); } if(record == NULL) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "The record does not exist: %lld for partial retrieval", (long long)key); } if(zeroBasedByteOffset < 0 || sizeInBytes < 0 || zeroBasedByteOffset + sizeInBytes > recordSize) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Partial record retrieval to out of bounds memory, record size: %lld, requested start: %lld, requested size: %lld", (long long)recordSize, (long long)zeroBasedByteOffset, (long long)sizeInBytes); } void *partialRecord = memcpy(st_malloc(sizeInBytes), record + zeroBasedByteOffset, sizeInBytes); free(record); return partialRecord; } static void removeRecord(stKVDatabase *database, int64_t key) { RemoteDB rdb = database->dbImpl; if (!rdb.remove(&key, sizeof(int64_t))) { stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Removing key/value to database error: %s", rdb.error().name()); } } static void startTransaction(stKVDatabase *database) { // transactions supported through bulk_... methods return; } static void commitTransaction(stKVDatabase *database) { // transactions supported through bulk_... methods return; } static void abortTransaction(stKVDatabase *database) { // transactions supported through bulk_... methods return; } void stKVDatabase_initialise_kyotoTycoon(stKVDatabase *database, stKVDatabaseConf *conf, bool create) { database->dbImpl = constructDB(stKVDatabase_getConf(database), create); database->destruct = destructDB; database->delete = deleteDB; database->containsRecord = containsRecord; database->insertRecord = insertRecord; database->updateRecord = updateRecord; database->numberOfRecords = numberOfRecords; database->getRecord = getRecord; database->getRecord2 = getRecord2; database->getPartialRecord = getPartialRecord; database->removeRecord = removeRecord; database->startTransaction = startTransaction; database->commitTransaction = commitTransaction; database->abortTransaction = abortTransaction; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: entityreference.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "entityreference.hxx" #include <string.h> namespace DOM { CEntityReference::CEntityReference(const xmlNodePtr /*aNodePtr*/) { m_aNodeType = NodeType_ENTITY_REFERENCE_NODE; init_node(m_aNodePtr); } OUString SAL_CALL CEntityReference::getNodeName()throw (RuntimeException) { OUString aName; if (m_aNodePtr != NULL) { const xmlChar* xName = m_aNodePtr->name; aName = OUString((sal_Char*)xName, strlen((char*)xName), RTL_TEXTENCODING_UTF8); } return aName; } OUString SAL_CALL CEntityReference::getNodeValue() throw (RuntimeException) { return OUString(); } } <commit_msg>INTEGRATION: CWS xmlfix2 (1.4.30); FILE MERGED 2008/05/15 17:26:33 mst 1.4.30.3: RESYNC: (1.5-1.6); FILE MERGED 2008/03/26 15:10:02 mst 1.4.30.2: RESYNC: (1.4-1.5); FILE MERGED 2007/11/14 14:28:38 lo 1.4.30.1: parser improvements<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: entityreference.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "entityreference.hxx" #include <string.h> namespace DOM { CEntityReference::CEntityReference(const xmlNodePtr aNodePtr) { m_aNodeType = NodeType_ENTITY_REFERENCE_NODE; init_node(aNodePtr); } OUString SAL_CALL CEntityReference::getNodeName()throw (RuntimeException) { OUString aName; if (m_aNodePtr != NULL) { const xmlChar* xName = m_aNodePtr->name; aName = OUString((sal_Char*)xName, strlen((char*)xName), RTL_TEXTENCODING_UTF8); } return aName; } OUString SAL_CALL CEntityReference::getNodeValue() throw (RuntimeException) { return OUString(); } } <|endoftext|>
<commit_before>#include "RademacherRand.h" RademacherRand::RademacherRand() { } std::string RademacherRand::name() { return "Rademacher"; } double RademacherRand::P(int k) const { if (k == -1 || k == 1) return 0.5; return 0; } double RademacherRand::F(double x) const { if (x < -1) return 0; if (x < 1) return 0.5; return 1; } double RademacherRand::variate() const { if ((signed)RandGenerator::variate() < 0) return -1; return 1; } std::complex<double> RademacherRand::CF(double t) const { return std::cos(t); } double RademacherRand::quantile(double p) const { } double RademacherRand::Median() const { return 0.0; } double RademacherRand::Mode() const { /// any from {-1, 1} return variate(); } double RademacherRand::Skewness() const { return 0.0; } double RademacherRand::ExcessKurtosis() const { return -2.0; } <commit_msg>Update RademacherRand.cpp<commit_after>#include "RademacherRand.h" RademacherRand::RademacherRand() { } std::string RademacherRand::name() { return "Rademacher"; } double RademacherRand::P(int k) const { if (k == -1 || k == 1) return 0.5; return 0; } double RademacherRand::F(double x) const { if (x < -1) return 0; if (x < 1) return 0.5; return 1; } double RademacherRand::variate() const { if ((signed)RandGenerator::variate() < 0) return -1; return 1; } std::complex<double> RademacherRand::CF(double t) const { return std::cos(t); } double RademacherRand::quantile(double p) const { if (p == 0) return -INFINITY; if (p == 0.5) return -1; if (p == 1) return 1; return NAN; } double RademacherRand::Median() const { return 0.0; } double RademacherRand::Mode() const { /// any from {-1, 1} return variate(); } double RademacherRand::Skewness() const { return 0.0; } double RademacherRand::ExcessKurtosis() const { return -2.0; } <|endoftext|>
<commit_before>/*********************************************************************** created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/OpenGL/ShaderManager.h" #include "CEGUI/RendererModules/OpenGL/GLES2Renderer.h" #include "CEGUI/RendererModules/OpenGL/GLES2Texture.h" #include "CEGUI/RendererModules/OpenGL/Shader.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/RendererModules/OpenGL/ViewportTarget.h" #include "CEGUI/RendererModules/OpenGL/GLES2GeometryBuffer.h" #include "CEGUI/GUIContext.h" #include "CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h" #include "CEGUI/System.h" #include "CEGUI/DefaultResourceProvider.h" #include "CEGUI/Logger.h" #include "CEGUI/RendererModules/OpenGL/GLES2StateChangeWrapper.h" #include "CEGUI/RenderMaterial.h" #include "CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h" #include <sstream> #include <algorithm> #include <cstring> #ifdef __ANDROID__ #include <android/log.h> #endif // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // The following are some GL extension / version dependant related items. // This is all done totally internally here; no need for external interface // to show any of this. //----------------------------------------------------------------------------// // we only really need this with MSVC / Windows(?) and by now it should already // be defined on that platform, so we just define it as empty macro so the // compile does not break on other systems. #ifndef APIENTRY # define APIENTRY #endif //! Dummy function for if real ones are not present (saves testing each render) static void APIENTRY activeTextureDummy(GLenum) {} //----------------------------------------------------------------------------// // template specialised class that does the real work for us template<typename T> class OGLTemplateTargetFactory : public OGLTextureTargetFactory { TextureTarget* create(OpenGLRendererBase& r) const { return new T(static_cast<GLES2Renderer&>(r)); } }; //----------------------------------------------------------------------------// GLES2Renderer& GLES2Renderer::bootstrapSystem(const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); if (System::getSingletonPtr()) CEGUI_THROW(InvalidRequestException( "CEGUI::System object is already initialised.")); GLES2Renderer& renderer(create()); DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; } //----------------------------------------------------------------------------// GLES2Renderer& GLES2Renderer::bootstrapSystem(const Sizef& display_size, const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); if (System::getSingletonPtr()) CEGUI_THROW(InvalidRequestException( "CEGUI::System object is already initialised.")); GLES2Renderer& renderer(create(display_size)); DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; } //----------------------------------------------------------------------------// void GLES2Renderer::destroySystem() { System* sys; if (!(sys = System::getSingletonPtr())) CEGUI_THROW(InvalidRequestException( "CEGUI::System object is not created or was already destroyed.")); GLES2Renderer* renderer = static_cast<GLES2Renderer*>(sys->getRenderer()); DefaultResourceProvider* rp = static_cast<DefaultResourceProvider*>(sys->getResourceProvider()); System::destroy(); delete rp; destroy(*renderer); } //----------------------------------------------------------------------------// GLES2Renderer& GLES2Renderer::create(const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); return *new GLES2Renderer(); } //----------------------------------------------------------------------------// GLES2Renderer& GLES2Renderer::create(const Sizef& display_size, const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); return *new GLES2Renderer(display_size); } //----------------------------------------------------------------------------// void GLES2Renderer::destroy(GLES2Renderer& renderer) { delete &renderer; } //----------------------------------------------------------------------------// GLES2Renderer::GLES2Renderer() : d_shaderWrapperTextured(0), d_openGLStateChanger(0), d_shaderManager(0) { initialiseRendererIDString(); initialiseGLExtensions(); d_openGLStateChanger = new GLES2StateChangeWrapper(); initialiseTextureTargetFactory(); initialiseOpenGLShaders(); } //----------------------------------------------------------------------------// GLES2Renderer::GLES2Renderer(const Sizef& display_size) : OpenGLRendererBase(display_size), d_shaderWrapperTextured(0), d_openGLStateChanger(0), d_shaderManager(0) { initialiseRendererIDString(); initialiseGLExtensions(); d_openGLStateChanger = new GLES2StateChangeWrapper(); initialiseTextureTargetFactory(); initialiseOpenGLShaders(); } //----------------------------------------------------------------------------// GLES2Renderer::~GLES2Renderer() { delete d_textureTargetFactory; delete d_openGLStateChanger; delete d_shaderManager; delete d_shaderWrapperTextured; delete d_shaderWrapperSolid; } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseRendererIDString() { d_rendererID = #ifdef CEGUI_GLES3_SUPPORT "CEGUI::GLES2Renderer - OpenGL ES 3.0 Renderer" #else "CEGUI::GLES2Renderer - OpenGL ES 2.0 Renderer" #endif "renderer module."; } //----------------------------------------------------------------------------// OpenGLGeometryBufferBase* GLES2Renderer::createGeometryBuffer_impl(CEGUI::RefCounted<RenderMaterial> renderMaterial) { return new GLES2GeometryBuffer(*this, renderMaterial); } //----------------------------------------------------------------------------// TextureTarget* GLES2Renderer::createTextureTarget_impl() { return d_textureTargetFactory->create(*this); } //----------------------------------------------------------------------------// void GLES2Renderer::beginRendering() { // if enabled, restores a subset of the GL state back to default values. if (d_initExtraStates) setupExtraStates(); d_openGLStateChanger->reset(); // Setup initial states d_openGLStateChanger->enable(GL_BLEND); // force set blending ops to get to a known state. setupRenderingBlendMode(BM_NORMAL, true); } //----------------------------------------------------------------------------// void GLES2Renderer::endRendering() { } //----------------------------------------------------------------------------// void GLES2Renderer::setupExtraStates() { glActiveTexture(GL_TEXTURE0); //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glUseProgram(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseTextureTargetFactory() { //Use OGL core implementation for FBOs d_rendererID += " TextureTarget support enabled via FBO OGL 3.2 core implementation."; d_textureTargetFactory = new OGLTemplateTargetFactory<GLES2FBOTextureTarget>; } //----------------------------------------------------------------------------// void GLES2Renderer::setupRenderingBlendMode(const BlendMode mode, const bool force) { // exit if mode is already set up (and update not forced) if ((d_activeBlendMode == mode) && !force) return; d_activeBlendMode = mode; if (d_activeBlendMode == BM_RTT_PREMULTIPLIED) { d_openGLStateChanger->blendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { d_openGLStateChanger->blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE); } } //----------------------------------------------------------------------------// Sizef GLES2Renderer::getAdjustedTextureSize(const Sizef& sz) { Sizef out(sz); const GLubyte* pcExt = glGetString(GL_EXTENSIONS); String extensions = String((const char*)pcExt); // if we can't support non power of two sizes, get appropriate POT values. if (!extensions.find("GL_OES_texture_npot")) { out.d_width = getNextPOTSize(out.d_width); out.d_height = getNextPOTSize(out.d_height); } return out; } //----------------------------------------------------------------------------// OpenGLBaseStateChangeWrapper* GLES2Renderer::getOpenGLStateChanger() { return d_openGLStateChanger; } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseOpenGLShaders() { checkGLErrors(); #ifdef CEGUI_GLES3_SUPPORT d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSLES3); #else d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSLES1); #endif d_shaderManager->initialiseShaders(); initialiseStandardTexturedShaderWrapper(); initialiseStandardColouredShaderWrapper(); } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseGLExtensions() { const GLubyte* pcExt = glGetString(GL_EXTENSIONS); String extensions = String((const char*)pcExt); if (extensions.find("GL_EXT_texture_compression_s3tc")) { d_s3tcSupported = true; } } //----------------------------------------------------------------------------// bool GLES2Renderer::isS3TCSupported() const { return d_s3tcSupported; } //----------------------------------------------------------------------------// RefCounted<RenderMaterial> GLES2Renderer::createRenderMaterial(const DefaultShaderType shaderType) const { if(shaderType == DS_TEXTURED) { RefCounted<RenderMaterial> render_material(new RenderMaterial(d_shaderWrapperTextured)); return render_material; } else if(shaderType == DS_SOLID) { RefCounted<RenderMaterial> render_material(new RenderMaterial(d_shaderWrapperSolid)); return render_material; } else { CEGUI_THROW(RendererException( "A default shader of this type does not exist.")); return RefCounted<RenderMaterial>(); } } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseStandardTexturedShaderWrapper() { OpenGLBaseShader* shader_standard_textured = d_shaderManager->getShader(SHADER_ID_STANDARD_TEXTURED); d_shaderWrapperTextured = new OpenGLBaseShaderWrapper(*shader_standard_textured, d_openGLStateChanger); d_shaderWrapperTextured->addTextureUniformVariable("texture0", 0); d_shaderWrapperTextured->addUniformVariable("modelViewProjMatrix"); d_shaderWrapperTextured->addUniformVariable("alphaPercentage"); d_shaderWrapperTextured->addAttributeVariable("inPosition"); d_shaderWrapperTextured->addAttributeVariable("inTexCoord"); d_shaderWrapperTextured->addAttributeVariable("inColour"); } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseStandardColouredShaderWrapper() { OpenGLBaseShader* shader_standard_solid = d_shaderManager->getShader(SHADER_ID_STANDARD_SOLID); d_shaderWrapperSolid = new OpenGLBaseShaderWrapper(*shader_standard_solid, d_openGLStateChanger); d_shaderWrapperSolid->addUniformVariable("modelViewProjMatrix"); d_shaderWrapperSolid->addUniformVariable("alphaPercentage"); d_shaderWrapperSolid->addAttributeVariable("inPosition"); d_shaderWrapperSolid->addAttributeVariable("inColour"); } //----------------------------------------------------------------------------// OpenGLTexture* GLES2Renderer::createTexture_impl(const String& name) { return new GLES2Texture(*this, name); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>remove android log<commit_after>/*********************************************************************** created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/OpenGL/ShaderManager.h" #include "CEGUI/RendererModules/OpenGL/GLES2Renderer.h" #include "CEGUI/RendererModules/OpenGL/GLES2Texture.h" #include "CEGUI/RendererModules/OpenGL/Shader.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/RendererModules/OpenGL/ViewportTarget.h" #include "CEGUI/RendererModules/OpenGL/GLES2GeometryBuffer.h" #include "CEGUI/GUIContext.h" #include "CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h" #include "CEGUI/System.h" #include "CEGUI/DefaultResourceProvider.h" #include "CEGUI/Logger.h" #include "CEGUI/RendererModules/OpenGL/GLES2StateChangeWrapper.h" #include "CEGUI/RenderMaterial.h" #include "CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h" #include <sstream> #include <algorithm> #include <cstring> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // The following are some GL extension / version dependant related items. // This is all done totally internally here; no need for external interface // to show any of this. //----------------------------------------------------------------------------// // we only really need this with MSVC / Windows(?) and by now it should already // be defined on that platform, so we just define it as empty macro so the // compile does not break on other systems. #ifndef APIENTRY # define APIENTRY #endif //! Dummy function for if real ones are not present (saves testing each render) static void APIENTRY activeTextureDummy(GLenum) {} //----------------------------------------------------------------------------// // template specialised class that does the real work for us template<typename T> class OGLTemplateTargetFactory : public OGLTextureTargetFactory { TextureTarget* create(OpenGLRendererBase& r) const { return new T(static_cast<GLES2Renderer&>(r)); } }; //----------------------------------------------------------------------------// GLES2Renderer& GLES2Renderer::bootstrapSystem(const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); if (System::getSingletonPtr()) CEGUI_THROW(InvalidRequestException( "CEGUI::System object is already initialised.")); GLES2Renderer& renderer(create()); DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; } //----------------------------------------------------------------------------// GLES2Renderer& GLES2Renderer::bootstrapSystem(const Sizef& display_size, const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); if (System::getSingletonPtr()) CEGUI_THROW(InvalidRequestException( "CEGUI::System object is already initialised.")); GLES2Renderer& renderer(create(display_size)); DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; } //----------------------------------------------------------------------------// void GLES2Renderer::destroySystem() { System* sys; if (!(sys = System::getSingletonPtr())) CEGUI_THROW(InvalidRequestException( "CEGUI::System object is not created or was already destroyed.")); GLES2Renderer* renderer = static_cast<GLES2Renderer*>(sys->getRenderer()); DefaultResourceProvider* rp = static_cast<DefaultResourceProvider*>(sys->getResourceProvider()); System::destroy(); delete rp; destroy(*renderer); } //----------------------------------------------------------------------------// GLES2Renderer& GLES2Renderer::create(const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); return *new GLES2Renderer(); } //----------------------------------------------------------------------------// GLES2Renderer& GLES2Renderer::create(const Sizef& display_size, const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); return *new GLES2Renderer(display_size); } //----------------------------------------------------------------------------// void GLES2Renderer::destroy(GLES2Renderer& renderer) { delete &renderer; } //----------------------------------------------------------------------------// GLES2Renderer::GLES2Renderer() : d_shaderWrapperTextured(0), d_openGLStateChanger(0), d_shaderManager(0) { initialiseRendererIDString(); initialiseGLExtensions(); d_openGLStateChanger = new GLES2StateChangeWrapper(); initialiseTextureTargetFactory(); initialiseOpenGLShaders(); } //----------------------------------------------------------------------------// GLES2Renderer::GLES2Renderer(const Sizef& display_size) : OpenGLRendererBase(display_size), d_shaderWrapperTextured(0), d_openGLStateChanger(0), d_shaderManager(0) { initialiseRendererIDString(); initialiseGLExtensions(); d_openGLStateChanger = new GLES2StateChangeWrapper(); initialiseTextureTargetFactory(); initialiseOpenGLShaders(); } //----------------------------------------------------------------------------// GLES2Renderer::~GLES2Renderer() { delete d_textureTargetFactory; delete d_openGLStateChanger; delete d_shaderManager; delete d_shaderWrapperTextured; delete d_shaderWrapperSolid; } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseRendererIDString() { d_rendererID = #ifdef CEGUI_GLES3_SUPPORT "CEGUI::GLES2Renderer - OpenGL ES 3.0 Renderer" #else "CEGUI::GLES2Renderer - OpenGL ES 2.0 Renderer" #endif "renderer module."; } //----------------------------------------------------------------------------// OpenGLGeometryBufferBase* GLES2Renderer::createGeometryBuffer_impl(CEGUI::RefCounted<RenderMaterial> renderMaterial) { return new GLES2GeometryBuffer(*this, renderMaterial); } //----------------------------------------------------------------------------// TextureTarget* GLES2Renderer::createTextureTarget_impl() { return d_textureTargetFactory->create(*this); } //----------------------------------------------------------------------------// void GLES2Renderer::beginRendering() { // if enabled, restores a subset of the GL state back to default values. if (d_initExtraStates) setupExtraStates(); d_openGLStateChanger->reset(); // Setup initial states d_openGLStateChanger->enable(GL_BLEND); // force set blending ops to get to a known state. setupRenderingBlendMode(BM_NORMAL, true); } //----------------------------------------------------------------------------// void GLES2Renderer::endRendering() { } //----------------------------------------------------------------------------// void GLES2Renderer::setupExtraStates() { glActiveTexture(GL_TEXTURE0); //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glUseProgram(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseTextureTargetFactory() { //Use OGL core implementation for FBOs d_rendererID += " TextureTarget support enabled via FBO OGL 3.2 core implementation."; d_textureTargetFactory = new OGLTemplateTargetFactory<GLES2FBOTextureTarget>; } //----------------------------------------------------------------------------// void GLES2Renderer::setupRenderingBlendMode(const BlendMode mode, const bool force) { // exit if mode is already set up (and update not forced) if ((d_activeBlendMode == mode) && !force) return; d_activeBlendMode = mode; if (d_activeBlendMode == BM_RTT_PREMULTIPLIED) { d_openGLStateChanger->blendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { d_openGLStateChanger->blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE); } } //----------------------------------------------------------------------------// Sizef GLES2Renderer::getAdjustedTextureSize(const Sizef& sz) { Sizef out(sz); const GLubyte* pcExt = glGetString(GL_EXTENSIONS); String extensions = String((const char*)pcExt); // if we can't support non power of two sizes, get appropriate POT values. if (!extensions.find("GL_OES_texture_npot")) { out.d_width = getNextPOTSize(out.d_width); out.d_height = getNextPOTSize(out.d_height); } return out; } //----------------------------------------------------------------------------// OpenGLBaseStateChangeWrapper* GLES2Renderer::getOpenGLStateChanger() { return d_openGLStateChanger; } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseOpenGLShaders() { checkGLErrors(); #ifdef CEGUI_GLES3_SUPPORT d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSLES3); #else d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSLES1); #endif d_shaderManager->initialiseShaders(); initialiseStandardTexturedShaderWrapper(); initialiseStandardColouredShaderWrapper(); } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseGLExtensions() { const GLubyte* pcExt = glGetString(GL_EXTENSIONS); String extensions = String((const char*)pcExt); if (extensions.find("GL_EXT_texture_compression_s3tc")) { d_s3tcSupported = true; } } //----------------------------------------------------------------------------// bool GLES2Renderer::isS3TCSupported() const { return d_s3tcSupported; } //----------------------------------------------------------------------------// RefCounted<RenderMaterial> GLES2Renderer::createRenderMaterial(const DefaultShaderType shaderType) const { if(shaderType == DS_TEXTURED) { RefCounted<RenderMaterial> render_material(new RenderMaterial(d_shaderWrapperTextured)); return render_material; } else if(shaderType == DS_SOLID) { RefCounted<RenderMaterial> render_material(new RenderMaterial(d_shaderWrapperSolid)); return render_material; } else { CEGUI_THROW(RendererException( "A default shader of this type does not exist.")); return RefCounted<RenderMaterial>(); } } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseStandardTexturedShaderWrapper() { OpenGLBaseShader* shader_standard_textured = d_shaderManager->getShader(SHADER_ID_STANDARD_TEXTURED); d_shaderWrapperTextured = new OpenGLBaseShaderWrapper(*shader_standard_textured, d_openGLStateChanger); d_shaderWrapperTextured->addTextureUniformVariable("texture0", 0); d_shaderWrapperTextured->addUniformVariable("modelViewProjMatrix"); d_shaderWrapperTextured->addUniformVariable("alphaPercentage"); d_shaderWrapperTextured->addAttributeVariable("inPosition"); d_shaderWrapperTextured->addAttributeVariable("inTexCoord"); d_shaderWrapperTextured->addAttributeVariable("inColour"); } //----------------------------------------------------------------------------// void GLES2Renderer::initialiseStandardColouredShaderWrapper() { OpenGLBaseShader* shader_standard_solid = d_shaderManager->getShader(SHADER_ID_STANDARD_SOLID); d_shaderWrapperSolid = new OpenGLBaseShaderWrapper(*shader_standard_solid, d_openGLStateChanger); d_shaderWrapperSolid->addUniformVariable("modelViewProjMatrix"); d_shaderWrapperSolid->addUniformVariable("alphaPercentage"); d_shaderWrapperSolid->addAttributeVariable("inPosition"); d_shaderWrapperSolid->addAttributeVariable("inColour"); } //----------------------------------------------------------------------------// OpenGLTexture* GLES2Renderer::createTexture_impl(const String& name) { return new GLES2Texture(*this, name); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>#include "starlight_game.h" #include "starlight_input.h" #include "starlight_log.h" #include "starlight_generated.h" #include "starlight_transform.h" #include "starlight_renderer.h" #include "starlight_platform.h" #include <process.h> #include <cstdint> #include <Windows.h> #include <d3d11.h> #include <glm/gtc/matrix_transform.hpp> #include "starlight_glm.h" // shaders (generated) // changed to defines to prevent visual studio hanging #include "SimplePixelShader.h" #define PixelShaderBlob g_SimplePixelShader #include "SimpleVertexShader.h" #define VertexShaderBlob g_SimpleVertexShader static ID3D11Buffer* s_constantBuffers[renderer::NumConstantBuffers]; struct Camera { float m_fieldOfView = glm::radians(60.0f); // Field of view angle (radians) float m_zNear = 0.3f; float m_zFar = 1000.0f; }; static Transform s_player; static Camera s_camera; // Todo: texture static LARGE_INTEGER s_lastTime; static LARGE_INTEGER s_perfFreq; static float s_deltaTime; static ID3D11RasterizerState* s_rasterizerState; static ID3D11PixelShader* s_pixelShader; static ID3D11VertexShader* s_vertexShader; static ID3D11InputLayout* s_inputLayout; static D3D11_VIEWPORT s_viewport; static PerCamera s_perCamera; static PerFrame s_perFrame; static PerObject s_perObject; Mesh s_mesh; Mesh CreateCube() { Vertex vertices[8] = { { { -1.0f, -1.0f, -1.0f },{ 0.0f, 0.0f, 0.0f } }, // 0 { { -1.0f, 1.0f, -1.0f },{ 0.0f, 1.0f, 0.0f } }, // 1 { { 1.0f, 1.0f, -1.0f },{ 1.0f, 1.0f, 0.0f } }, // 2 { { 1.0f, -1.0f, -1.0f },{ 1.0f, 0.0f, 0.0f } }, // 3 { { -1.0f, -1.0f, 1.0f },{ 0.0f, 0.0f, 1.0f } }, // 4 { { -1.0f, 1.0f, 1.0f },{ 0.0f, 1.0f, 1.0f } }, // 5 { { 1.0f, 1.0f, 1.0f },{ 1.0f, 1.0f, 1.0f } }, // 6 { { 1.0f, -1.0f, 1.0f },{ 1.0f, 0.0f, 1.0f } } // 7 }; uint16_t indices[36] = { 0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 4, 5, 1, 4, 1, 0, 3, 2, 6, 3, 6, 7, 1, 5, 6, 1, 6, 2, 4, 0, 3, 4, 3, 7 }; // Create the primitive object. Mesh mesh; // vertex buffer { D3D11_BUFFER_DESC bufferDesc = { 0 }; bufferDesc.ByteWidth = sizeof(vertices); bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.Usage = D3D11_USAGE_DEFAULT; D3D11_SUBRESOURCE_DATA dataDesc = { 0 }; dataDesc.pSysMem = vertices; D3D_TRY(renderer::GetDevice()->CreateBuffer(&bufferDesc, &dataDesc, &mesh.vertexBuffer)); } // index buffer { D3D11_BUFFER_DESC bufferDesc = { 0 }; bufferDesc.ByteWidth = sizeof(indices); bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bufferDesc.Usage = D3D11_USAGE_DEFAULT; D3D11_SUBRESOURCE_DATA dataDesc = { 0 }; dataDesc.pSysMem = indices; D3D_TRY(renderer::GetDevice()->CreateBuffer(&bufferDesc, &dataDesc, &mesh.indexBuffer)); } mesh.numIndices = _countof(indices); return mesh; } void game::Init() { input::Init(); logger::Init(); LogInfo("Сука блять!"); s_player.SetPosition(0, 0, -10); auto windowSize = platform::GetWindowSize(); // Rasterizer State D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(D3D11_RASTERIZER_DESC)); rasterizerDesc.AntialiasedLineEnable = FALSE; rasterizerDesc.CullMode = D3D11_CULL_BACK; rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = TRUE; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.FrontCounterClockwise = FALSE; rasterizerDesc.MultisampleEnable = FALSE; rasterizerDesc.ScissorEnable = FALSE; rasterizerDesc.SlopeScaledDepthBias = 0.0f; D3D_TRY(renderer::GetDevice()->CreateRasterizerState(&rasterizerDesc, &s_rasterizerState)); // Initialize the viewport to occupy the entire client area. s_viewport.Width = static_cast<float>(windowSize.x); s_viewport.Height = static_cast<float>(windowSize.y); s_viewport.TopLeftX = 0.0f; s_viewport.TopLeftY = 0.0f; s_viewport.MinDepth = 0.0f; s_viewport.MaxDepth = 1.0f; // Shaders s_pixelShader = renderer::CreatePixelShader(PixelShaderBlob, sizeof(PixelShaderBlob)); s_vertexShader = renderer::CreateVertexShader(VertexShaderBlob, sizeof(VertexShaderBlob)); // TODO Sampler (for texturing) // Input layout D3D11_INPUT_ELEMENT_DESC inputElementDescs[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; D3D_TRY(renderer::GetDevice()->CreateInputLayout(inputElementDescs, _countof(inputElementDescs), VertexShaderBlob, sizeof(VertexShaderBlob), &s_inputLayout)); // Cube s_mesh = CreateCube(); // Timing s_deltaTime = 0.0f; QueryPerformanceFrequency(&s_perfFreq); QueryPerformanceCounter(&s_lastTime); // Constant buffer descriptor D3D11_BUFFER_DESC constantBufferDesc; ZeroMemory(&constantBufferDesc, sizeof(constantBufferDesc)); constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constantBufferDesc.CPUAccessFlags = 0; constantBufferDesc.Usage = D3D11_USAGE_DEFAULT; // Per frame constant buffer constantBufferDesc.ByteWidth = sizeof(PerFrame); D3D_TRY(renderer::GetDevice()->CreateBuffer(&constantBufferDesc, nullptr, &s_constantBuffers[renderer::Frame])); // Per camera constant buffer constantBufferDesc.ByteWidth = sizeof(PerCamera); D3D_TRY(renderer::GetDevice()->CreateBuffer(&constantBufferDesc, nullptr, &s_constantBuffers[renderer::Camera])); // Per object constant buffer constantBufferDesc.ByteWidth = sizeof(PerObject); D3D_TRY(renderer::GetDevice()->CreateBuffer(&constantBufferDesc, nullptr, &s_constantBuffers[renderer::Object])); } void MoveCamera() { // TODO: probably need to check if i'm typing something in ImGui or not static glm::vec2 lastRotation; static glm::vec2 currentRotation; if (input::GetKeyDown('M')) { input::SetMouseGrabbed(!input::IsMouseGrabbed()); } // Reset if (input::GetKeyDown('R')) { currentRotation = lastRotation = { 0, 0 }; s_player.SetPosition(glm::vec3(0, 0, 0)); s_player.SetRotation(glm::quat(1, 0, 0, 0)); } if (input::IsMouseGrabbed()) { // Rotation const float ROT_SPEED = 0.0025f; currentRotation -= ROT_SPEED * input::GetMouseDelta(); if (currentRotation.y < glm::radians(-89.0f)) { currentRotation.y = glm::radians(-89.0f); } if (currentRotation.y > glm::radians(89.0f)) { currentRotation.y = glm::radians(89.0f); } if (currentRotation.x != lastRotation.x || currentRotation.y != lastRotation.y) { s_player.SetRotation(glm::quat(glm::vec3(currentRotation.y, currentRotation.x, 0.0f))); lastRotation = currentRotation; } } // Translation const float SPEED = 20.0f; glm::vec3 translation(0, 0, 0); if (input::GetKey('W')) translation += s_player.Forward(); if (input::GetKey('A')) translation -= s_player.Right(); if (input::GetKey('S')) translation -= s_player.Forward(); if (input::GetKey('D')) translation += s_player.Right(); if (input::GetKey(VK_LCONTROL) || input::GetKey('C') || input::GetKey(VK_LSHIFT)) translation -= glm::vec3(0, 1, 0); if (input::GetKey(VK_SPACE)) translation += glm::vec3(0, 1, 0); if (translation != glm::vec3(0, 0, 0)) { glm::vec3 pos = s_player.GetPosition(); pos += glm::normalize(translation) * SPEED * s_deltaTime; s_player.SetPosition(pos); //printf("pos: %.1f, %.1f, %.1f\n", m_player.GetPosition().x, m_player.GetPosition().y, m_player.GetPosition().z); } } void game::Update() { // Timing LARGE_INTEGER currentTime; QueryPerformanceCounter(&currentTime); s_deltaTime = float(currentTime.QuadPart - s_lastTime.QuadPart) / float(s_perfFreq.QuadPart); s_lastTime = currentTime; // Begin logic input::BeginFrame(); MoveCamera(); input::EndFrame(); // Does not render, but builds display lists logger::Render(); auto windowSize = platform::GetWindowSize(); if (windowSize.x > 0 && windowSize.y > 0) { glm::mat4 projectionMatrix = glm::perspectiveFovLH(glm::radians(45.0f), (float)windowSize.x, (float)windowSize.y, 0.1f, 100.0f); s_perCamera.view = s_player.GetViewMatrix(); renderer::SetPerCamera(&s_perCamera); s_perFrame.projection = projectionMatrix; renderer::SetPerFrame(&s_perFrame); s_viewport.Width = static_cast<float>(windowSize.x); s_viewport.Height = static_cast<float>(windowSize.y); } //s_perObject.worldMatrix = glm::mat4(); s_perObject.worldMatrix = glm::translate(glm::vec3(0, 0, 10.0f)); } void game::CreateDrawCommands() { renderer::DrawCommand cmd; ZeroMemory(&cmd, sizeof(cmd)); cmd.mesh = &s_mesh; cmd.pipelineState.inputLayout = s_inputLayout; cmd.pipelineState.numViewports = 1; cmd.pipelineState.viewports = &s_viewport; cmd.pipelineState.pixelShader = s_pixelShader; cmd.pipelineState.vertexShader = s_vertexShader; cmd.pipelineState.rasterizerState = s_rasterizerState; cmd.perObject = &s_perObject; renderer::AddDrawCommand(cmd); } void game::Destroy() { SafeRelease(s_rasterizerState); SafeRelease(s_pixelShader); SafeRelease(s_vertexShader); SafeRelease(s_inputLayout); SafeRelease(s_mesh.indexBuffer); SafeRelease(s_mesh.vertexBuffer); } <commit_msg>Removed leftover constant buffers for testing<commit_after>#include "starlight_game.h" #include "starlight_input.h" #include "starlight_log.h" #include "starlight_generated.h" #include "starlight_transform.h" #include "starlight_renderer.h" #include "starlight_platform.h" #include <process.h> #include <cstdint> #include <Windows.h> #include <d3d11.h> #include <glm/gtc/matrix_transform.hpp> #include "starlight_glm.h" // shaders (generated) // changed to defines to prevent visual studio hanging #include "SimplePixelShader.h" #define PixelShaderBlob g_SimplePixelShader #include "SimpleVertexShader.h" #define VertexShaderBlob g_SimpleVertexShader struct Camera { float m_fieldOfView = glm::radians(60.0f); // Field of view angle (radians) float m_zNear = 0.3f; float m_zFar = 1000.0f; }; static Transform s_player; static Camera s_camera; // Todo: texture static LARGE_INTEGER s_lastTime; static LARGE_INTEGER s_perfFreq; static float s_deltaTime; static ID3D11RasterizerState* s_rasterizerState; static ID3D11PixelShader* s_pixelShader; static ID3D11VertexShader* s_vertexShader; static ID3D11InputLayout* s_inputLayout; static D3D11_VIEWPORT s_viewport; static PerCamera s_perCamera; static PerFrame s_perFrame; static PerObject s_perObject; Mesh s_mesh; Mesh CreateCube() { Vertex vertices[8] = { { { -1.0f, -1.0f, -1.0f },{ 0.0f, 0.0f, 0.0f } }, // 0 { { -1.0f, 1.0f, -1.0f },{ 0.0f, 1.0f, 0.0f } }, // 1 { { 1.0f, 1.0f, -1.0f },{ 1.0f, 1.0f, 0.0f } }, // 2 { { 1.0f, -1.0f, -1.0f },{ 1.0f, 0.0f, 0.0f } }, // 3 { { -1.0f, -1.0f, 1.0f },{ 0.0f, 0.0f, 1.0f } }, // 4 { { -1.0f, 1.0f, 1.0f },{ 0.0f, 1.0f, 1.0f } }, // 5 { { 1.0f, 1.0f, 1.0f },{ 1.0f, 1.0f, 1.0f } }, // 6 { { 1.0f, -1.0f, 1.0f },{ 1.0f, 0.0f, 1.0f } } // 7 }; uint16_t indices[36] = { 0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 4, 5, 1, 4, 1, 0, 3, 2, 6, 3, 6, 7, 1, 5, 6, 1, 6, 2, 4, 0, 3, 4, 3, 7 }; // Create the primitive object. Mesh mesh; // vertex buffer { D3D11_BUFFER_DESC bufferDesc = { 0 }; bufferDesc.ByteWidth = sizeof(vertices); bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.Usage = D3D11_USAGE_DEFAULT; D3D11_SUBRESOURCE_DATA dataDesc = { 0 }; dataDesc.pSysMem = vertices; D3D_TRY(renderer::GetDevice()->CreateBuffer(&bufferDesc, &dataDesc, &mesh.vertexBuffer)); } // index buffer { D3D11_BUFFER_DESC bufferDesc = { 0 }; bufferDesc.ByteWidth = sizeof(indices); bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bufferDesc.Usage = D3D11_USAGE_DEFAULT; D3D11_SUBRESOURCE_DATA dataDesc = { 0 }; dataDesc.pSysMem = indices; D3D_TRY(renderer::GetDevice()->CreateBuffer(&bufferDesc, &dataDesc, &mesh.indexBuffer)); } mesh.numIndices = _countof(indices); return mesh; } void game::Init() { input::Init(); logger::Init(); LogInfo("Сука блять!"); s_player.SetPosition(0, 0, -10); auto windowSize = platform::GetWindowSize(); // Rasterizer State D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(D3D11_RASTERIZER_DESC)); rasterizerDesc.AntialiasedLineEnable = FALSE; rasterizerDesc.CullMode = D3D11_CULL_BACK; rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = TRUE; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.FrontCounterClockwise = FALSE; rasterizerDesc.MultisampleEnable = FALSE; rasterizerDesc.ScissorEnable = FALSE; rasterizerDesc.SlopeScaledDepthBias = 0.0f; D3D_TRY(renderer::GetDevice()->CreateRasterizerState(&rasterizerDesc, &s_rasterizerState)); // Initialize the viewport to occupy the entire client area. s_viewport.Width = static_cast<float>(windowSize.x); s_viewport.Height = static_cast<float>(windowSize.y); s_viewport.TopLeftX = 0.0f; s_viewport.TopLeftY = 0.0f; s_viewport.MinDepth = 0.0f; s_viewport.MaxDepth = 1.0f; // Shaders s_pixelShader = renderer::CreatePixelShader(PixelShaderBlob, sizeof(PixelShaderBlob)); s_vertexShader = renderer::CreateVertexShader(VertexShaderBlob, sizeof(VertexShaderBlob)); // TODO Sampler (for texturing) // Input layout D3D11_INPUT_ELEMENT_DESC inputElementDescs[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; D3D_TRY(renderer::GetDevice()->CreateInputLayout(inputElementDescs, _countof(inputElementDescs), VertexShaderBlob, sizeof(VertexShaderBlob), &s_inputLayout)); // Cube s_mesh = CreateCube(); // Timing s_deltaTime = 0.0f; QueryPerformanceFrequency(&s_perfFreq); QueryPerformanceCounter(&s_lastTime); } void MoveCamera() { // TODO: probably need to check if i'm typing something in ImGui or not static glm::vec2 lastRotation; static glm::vec2 currentRotation; if (input::GetKeyDown('M')) { input::SetMouseGrabbed(!input::IsMouseGrabbed()); } // Reset if (input::GetKeyDown('R')) { currentRotation = lastRotation = { 0, 0 }; s_player.SetPosition(glm::vec3(0, 0, 0)); s_player.SetRotation(glm::quat(1, 0, 0, 0)); } if (input::IsMouseGrabbed()) { // Rotation const float ROT_SPEED = 0.0025f; currentRotation -= ROT_SPEED * input::GetMouseDelta(); if (currentRotation.y < glm::radians(-89.0f)) { currentRotation.y = glm::radians(-89.0f); } if (currentRotation.y > glm::radians(89.0f)) { currentRotation.y = glm::radians(89.0f); } if (currentRotation.x != lastRotation.x || currentRotation.y != lastRotation.y) { s_player.SetRotation(glm::quat(glm::vec3(currentRotation.y, currentRotation.x, 0.0f))); lastRotation = currentRotation; } } // Translation const float SPEED = 20.0f; glm::vec3 translation(0, 0, 0); if (input::GetKey('W')) translation += s_player.Forward(); if (input::GetKey('A')) translation -= s_player.Right(); if (input::GetKey('S')) translation -= s_player.Forward(); if (input::GetKey('D')) translation += s_player.Right(); if (input::GetKey(VK_LCONTROL) || input::GetKey('C') || input::GetKey(VK_LSHIFT)) translation -= glm::vec3(0, 1, 0); if (input::GetKey(VK_SPACE)) translation += glm::vec3(0, 1, 0); if (translation != glm::vec3(0, 0, 0)) { glm::vec3 pos = s_player.GetPosition(); pos += glm::normalize(translation) * SPEED * s_deltaTime; s_player.SetPosition(pos); //printf("pos: %.1f, %.1f, %.1f\n", m_player.GetPosition().x, m_player.GetPosition().y, m_player.GetPosition().z); } } void game::Update() { // Timing LARGE_INTEGER currentTime; QueryPerformanceCounter(&currentTime); s_deltaTime = float(currentTime.QuadPart - s_lastTime.QuadPart) / float(s_perfFreq.QuadPart); s_lastTime = currentTime; // Begin logic input::BeginFrame(); MoveCamera(); input::EndFrame(); // Does not render, but builds display lists logger::Render(); auto windowSize = platform::GetWindowSize(); if (windowSize.x > 0 && windowSize.y > 0) { glm::mat4 projectionMatrix = glm::perspectiveFovLH(glm::radians(45.0f), (float)windowSize.x, (float)windowSize.y, 0.1f, 100.0f); s_perCamera.view = s_player.GetViewMatrix(); renderer::SetPerCamera(&s_perCamera); s_perFrame.projection = projectionMatrix; renderer::SetPerFrame(&s_perFrame); s_viewport.Width = static_cast<float>(windowSize.x); s_viewport.Height = static_cast<float>(windowSize.y); } //s_perObject.worldMatrix = glm::mat4(); s_perObject.worldMatrix = glm::translate(glm::vec3(0, 0, 10.0f)); } void game::CreateDrawCommands() { renderer::DrawCommand cmd; ZeroMemory(&cmd, sizeof(cmd)); cmd.mesh = &s_mesh; cmd.pipelineState.inputLayout = s_inputLayout; cmd.pipelineState.numViewports = 1; cmd.pipelineState.viewports = &s_viewport; cmd.pipelineState.pixelShader = s_pixelShader; cmd.pipelineState.vertexShader = s_vertexShader; cmd.pipelineState.rasterizerState = s_rasterizerState; cmd.perObject = &s_perObject; renderer::AddDrawCommand(cmd); } void game::Destroy() { SafeRelease(s_rasterizerState); SafeRelease(s_pixelShader); SafeRelease(s_vertexShader); SafeRelease(s_inputLayout); SafeRelease(s_mesh.indexBuffer); SafeRelease(s_mesh.vertexBuffer); } <|endoftext|>
<commit_before>/* * Program.cpp * * Created on: 08.03.2016 * Author: hartung */ #include "initialization/MainFactory.hpp" #include "initialization/Program.hpp" #include "initialization/XMLConfigurationReader.hpp" #include "simulation/AbstractSimulation.hpp" #ifdef USE_MPI #include <mpi.h> #endif #ifdef USE_NETWORK_OFFLOADER #include "InitialNetworkServer.hpp" #include "NetworkFunctions.hpp" #endif namespace Initialization { Program::Program(const CommandLineArgs & cla) : _isInitialized(false), _usingMPI(false), _usingOMP(false), _commandLineArgs(cla) { } Program::Program(int* argc, char** argv[]) : _isInitialized(false), _usingMPI(false), _usingOMP(false), _commandLineArgs(CommandLineArgs(argc, argv)) { } Program::~Program() { if (_isInitialized) deinitialize(); } void Program::initialize() { if (_isInitialized) return; Util::Logger::initialize(_commandLineArgs.getLogSettings()); //create simulation plan, i.e. multiple simulation plans if mpi should be used (for each mpi process one plan) // read config file: XMLConfigurationReader reader(_commandLineArgs.getConfigFilePath()); _pp = reader.getProgramPlan(); // test for MPI initialization: int rank = 0, numRanks = 1; if (_pp.simPlans.size() > 1) if (!initMPI(rank, numRanks)) throw std::runtime_error("Couldn't initialize simulation. MPI couldn't be initialized."); if(rank == 0) printProgramInfo(_pp); // initialize server if needed if (_commandLineArgs.isSimulationServer()) { if (!initNetworkConnection(rank)) throw std::runtime_error("Simulation server couldn't be initialized"); } // initialize and create simulation: MainFactory mf; _simulations.resize(_pp.simPlans[rank].size()); // not in parallel because FmuSdkFMU::load and FmiLibFmu::load is not save to call in parallel for(size_type i=0;i<_simulations.size();++i) _simulations[i] = mf.createSimulation(_pp.simPlans[rank][i]); _isInitialized = true; } void Program::simulate() { size_type threadNum = 0; // not in parallel, Communicator::addFmu is not safe to call for (auto & sim : _simulations) sim->initialize(); #pragma omp parallel num_threads(_simulations.size()) { #ifdef USE_OPENMP threadNum = omp_get_thread_num(); #endif _simulations[threadNum]->simulate(); } } void Program::deinitialize() { if (_isInitialized) { //_simulation->deinitialize(); deinitMPI(); } } Simulation::AbstractSimulationSPtr Program::getSimulation() { #ifdef USE_OPENMP return _simulations[omp_get_thread_num()]; #else return _simulations[0]; #endif } void Program::printProgramInfo(const ProgramPlan& in) const { LOGGER_WRITE("", Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("--~~~####ParallelFmu Simulation####~~~--", Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("", Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("simulating following FMUs:", Util::LC_LOADER, Util::LL_INFO); for (size_type i = 0; i < in.simPlans.size(); ++i) for (size_type j = 0; j < in.simPlans[i].size(); ++j) for (size_type k = 0; k < in.simPlans[i][j].dataManager.solvers.size(); ++k) { const auto & fmu = *in.simPlans[i][j].dataManager.solvers[k]->fmu; LOGGER_WRITE("name: " + fmu.name, Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("path: " + fmu.path, Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("working directory: " + fmu.workingPath, Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("node/core: " + to_string(i) + "/" + to_string(j), Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("", Util::LC_LOADER, Util::LL_INFO); } LOGGER_WRITE("Program info: ", Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("numNodes: " + to_string(in.simPlans.size()), Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("Node infos: ", Util::LC_LOADER, Util::LL_INFO); for (size_type i = 0; i < in.simPlans.size(); ++i) { LOGGER_WRITE("Node " + to_string(i) + ":", Util::LC_LOADER, Util::LL_INFO); size_type numFmus = 0; for (size_type j = 0; j < in.simPlans[i].size(); ++j) numFmus += in.simPlans[i][j].dataManager.solvers.size(); LOGGER_WRITE("NumFmus: " + to_string(numFmus), Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("NumCores: " + to_string(in.simPlans[i].size()), Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("\n", Util::LC_LOADER, Util::LL_INFO); } } bool Program::initMPI(int & rank, int & numRanks) { #ifdef USE_MPI if (!(_commandLineArgs.getProgramArgs() == make_tuple<const int *, const char ***>(nullptr, nullptr)) && MPI_SUCCESS == MPI_Init(std::get<0>(_commandLineArgs.getProgramArgs()), std::get<1>(_commandLineArgs.getProgramArgs()))) { MPI_Comm_size(MPI_COMM_WORLD, &numRanks); if (numRanks < (long long int) _pp.simPlans.size()) { deinitialize(); throw std::runtime_error("Program: Not enough mpi processes for given schedule."); } else if (numRanks > (long long int) _pp.simPlans.size()) LOGGER_WRITE("Program: More mpi process given than the simulation will use.", Util::LC_LOADER, Util::LL_WARNING); MPI_Comm_rank(MPI_COMM_WORLD, &rank); _usingMPI = true; return true; } else return false; #else //throw std::runtime_error("Program: MPI not supported by this system."); #endif } bool Program::initNetworkConnection(const int & rank) { // Need to tread special cases. In a network server case the socket can only be hold by one process. The additional information need to be send via MPI. #ifdef USE_NETWORK_OFFLOADER Network::NetworkPlan np; if (rank == 0) { // initial network phase. Gather which information need to be collected and send to the client: Network::InitialNetworkServer initServer(_commandLineArgs.getSimulationServerPort(), _pp); initServer.start(); np = initServer.getNetworkPlan(); #ifdef USE_MPI if (_usingMPI) { int num = np.fmuNet.size(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); for (const auto & addFmu : np.fmuNet) { // sim num MPI_Bcast((void*) (&addFmu.simPos), 1, MPI_UINT32_T, 0, MPI_COMM_WORLD); // core num MPI_Bcast((void*) (&addFmu.corePos), 1, MPI_UINT32_T, 0, MPI_COMM_WORLD); // solver num MPI_Bcast((void*) (&addFmu.solverPos), 1, MPI_UINT32_T, 0, MPI_COMM_WORLD); // inputs num = addFmu.inputMap.size<real_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.inputMap.data<real_type>(), 2 * addFmu.inputMap.size<real_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.inputMap.size<int_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.inputMap.data<int_type>(), 2 * addFmu.inputMap.size<int_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.inputMap.size<bool_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.inputMap.data<bool_type>(), 2 * addFmu.inputMap.size<bool_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.inputMap.size<string_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.inputMap.data<string_type>(), 2 * addFmu.inputMap.size<string_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); //outputs num = addFmu.outputMap.size<real_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.outputMap.data<real_type>(), 2 * addFmu.outputMap.size<real_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.outputMap.size<int_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.outputMap.data<int_type>(), 2 * addFmu.outputMap.size<int_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.outputMap.size<bool_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.outputMap.data<bool_type>(), 2 * addFmu.outputMap.size<bool_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.outputMap.size<string_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.outputMap.data<string_type>(), 2 * addFmu.outputMap.size<string_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); } } #endif } else { #ifdef USE_MPI if (!_usingMPI) throw std::runtime_error("Cannot start mpi simulation."); // quick and dirty bcast for the remote simulation data aka. for the NetworkPlan int num = 0; MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); std::vector<std::tuple<size_type, size_type> > tmp1, tmp2, tmp3, tmp4; for (int i = 0; i < num; ++i) { np.fmuNet.push_back(Network::NetworkFmuInformation()); // sim num MPI_Recv((void*) (&np.fmuNet.back().simPos), 1, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // core num MPI_Recv((void*) (&np.fmuNet.back().corePos), 1, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // solver num MPI_Recv((void*) (&np.fmuNet.back().solverPos), 1, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //inputs MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp1.resize(num); MPI_Recv((void*) tmp1.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp2.resize(num); MPI_Recv((void*) tmp2.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp3.resize(num); MPI_Recv((void*) tmp3.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp4.resize(num); MPI_Recv((void*) tmp4.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); np.fmuNet.back().inputMap = FMI::InputMapping(tmp1, tmp2, tmp3, tmp4); //inputs MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp1.resize(num); MPI_Recv((void*) tmp1.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp2.resize(num); MPI_Recv((void*) tmp2.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp3.resize(num); MPI_Recv((void*) tmp3.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp4.resize(num); MPI_Recv((void*) tmp4.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); np.fmuNet.back().outputMap = FMI::InputMapping(tmp1, tmp2, tmp3, tmp4); } #else // test if the rank is on default (0), if not somethings wrong with @param rank. throw std::runtime_error("Internal error. Rank missmatch in network initialization."); #endif } // adding network fmu and connections to program plan Network::appendNetworkInformation(_pp, np); #endif return true; } void Program::deinitMPI() { _isInitialized = false; #ifdef USE_MPI if (_usingMPI) MPI_Finalize(); #endif } } <commit_msg>Correct spelling issue<commit_after>/* * Program.cpp * * Created on: 08.03.2016 * Author: hartung */ #include "initialization/MainFactory.hpp" #include "initialization/Program.hpp" #include "initialization/XMLConfigurationReader.hpp" #include "simulation/AbstractSimulation.hpp" #ifdef USE_MPI #include <mpi.h> #endif #ifdef USE_NETWORK_OFFLOADER #include "InitialNetworkServer.hpp" #include "NetworkFunctions.hpp" #endif namespace Initialization { Program::Program(const CommandLineArgs & cla) : _isInitialized(false), _usingMPI(false), _usingOMP(false), _commandLineArgs(cla) { } Program::Program(int* argc, char** argv[]) : _isInitialized(false), _usingMPI(false), _usingOMP(false), _commandLineArgs(CommandLineArgs(argc, argv)) { } Program::~Program() { if (_isInitialized) deinitialize(); } void Program::initialize() { if (_isInitialized) return; Util::Logger::initialize(_commandLineArgs.getLogSettings()); //create simulation plan, i.e. multiple simulation plans if mpi should be used (for each mpi process one plan) // read config file: XMLConfigurationReader reader(_commandLineArgs.getConfigFilePath()); _pp = reader.getProgramPlan(); // test for MPI initialization: int rank = 0, numRanks = 1; if (_pp.simPlans.size() > 1) if (!initMPI(rank, numRanks)) throw std::runtime_error("Couldn't initialize simulation. MPI couldn't be initialized."); if(rank == 0) printProgramInfo(_pp); // initialize server if needed if (_commandLineArgs.isSimulationServer()) { if (!initNetworkConnection(rank)) throw std::runtime_error("Simulation server couldn't be initialized"); } // initialize and create simulation: MainFactory mf; _simulations.resize(_pp.simPlans[rank].size()); // not in parallel because FmuSdkFMU::load and FmiLibFmu::load is not save to call in parallel for(size_type i=0;i<_simulations.size();++i) _simulations[i] = mf.createSimulation(_pp.simPlans[rank][i]); _isInitialized = true; } void Program::simulate() { size_type threadNum = 0; // not in parallel, Communicator::addFmu is not safe to call for (auto & sim : _simulations) sim->initialize(); #pragma omp parallel num_threads(_simulations.size()) { #ifdef USE_OPENMP threadNum = omp_get_thread_num(); #endif _simulations[threadNum]->simulate(); } } void Program::deinitialize() { if (_isInitialized) { //_simulation->deinitialize(); deinitMPI(); } } Simulation::AbstractSimulationSPtr Program::getSimulation() { #ifdef USE_OPENMP return _simulations[omp_get_thread_num()]; #else return _simulations[0]; #endif } void Program::printProgramInfo(const ProgramPlan& in) const { LOGGER_WRITE("", Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("--~~~####ParallelFmu Simulation####~~~--", Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("", Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("simulating following FMUs:", Util::LC_LOADER, Util::LL_INFO); for (size_type i = 0; i < in.simPlans.size(); ++i) for (size_type j = 0; j < in.simPlans[i].size(); ++j) for (size_type k = 0; k < in.simPlans[i][j].dataManager.solvers.size(); ++k) { const auto & fmu = *in.simPlans[i][j].dataManager.solvers[k]->fmu; LOGGER_WRITE("name: " + fmu.name, Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("path: " + fmu.path, Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("working directory: " + fmu.workingPath, Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("node/core: " + to_string(i) + "/" + to_string(j), Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("", Util::LC_LOADER, Util::LL_INFO); } LOGGER_WRITE("Program info: ", Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("numNodes: " + to_string(in.simPlans.size()), Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("Node infos: ", Util::LC_LOADER, Util::LL_INFO); for (size_type i = 0; i < in.simPlans.size(); ++i) { LOGGER_WRITE("Node " + to_string(i) + ":", Util::LC_LOADER, Util::LL_INFO); size_type numFmus = 0; for (size_type j = 0; j < in.simPlans[i].size(); ++j) numFmus += in.simPlans[i][j].dataManager.solvers.size(); LOGGER_WRITE("NumFmus: " + to_string(numFmus), Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("NumCores: " + to_string(in.simPlans[i].size()), Util::LC_LOADER, Util::LL_INFO); LOGGER_WRITE("\n", Util::LC_LOADER, Util::LL_INFO); } } bool Program::initMPI(int & rank, int & numRanks) { #ifdef USE_MPI if (!(_commandLineArgs.getProgramArgs() == make_tuple<const int *, const char ***>(nullptr, nullptr)) && MPI_SUCCESS == MPI_Init(std::get<0>(_commandLineArgs.getProgramArgs()), std::get<1>(_commandLineArgs.getProgramArgs()))) { MPI_Comm_size(MPI_COMM_WORLD, &numRanks); if (numRanks < (long long int) _pp.simPlans.size()) { deinitialize(); throw std::runtime_error("Program: Not enough mpi processes for given schedule."); } else if (numRanks > (long long int) _pp.simPlans.size()) LOGGER_WRITE("Program: More mpi process given than the simulation will use.", Util::LC_LOADER, Util::LL_WARNING); MPI_Comm_rank(MPI_COMM_WORLD, &rank); _usingMPI = true; return true; } else return false; #else //throw std::runtime_error("Program: MPI not supported by this system."); #endif } bool Program::initNetworkConnection(const int & rank) { // Need to tread special cases. In a network server case the socket can only be hold by one process. The additional information need to be send via MPI. #ifdef USE_NETWORK_OFFLOADER Network::NetworkPlan np; if (rank == 0) { // initial network phase. Gather which information need to be collected and send to the client: Network::InitialNetworkServer initServer(_commandLineArgs.getSimulationServerPort(), _pp); initServer.start(); np = initServer.getNetworkPlan(); #ifdef USE_MPI if (_usingMPI) { int num = np.fmuNet.size(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); for (const auto & addFmu : np.fmuNet) { // sim num MPI_Bcast((void*) (&addFmu.simPos), 1, MPI_UINT32_T, 0, MPI_COMM_WORLD); // core num MPI_Bcast((void*) (&addFmu.corePos), 1, MPI_UINT32_T, 0, MPI_COMM_WORLD); // solver num MPI_Bcast((void*) (&addFmu.solverPos), 1, MPI_UINT32_T, 0, MPI_COMM_WORLD); // inputs num = addFmu.inputMap.size<real_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.inputMap.data<real_type>(), 2 * addFmu.inputMap.size<real_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.inputMap.size<int_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.inputMap.data<int_type>(), 2 * addFmu.inputMap.size<int_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.inputMap.size<bool_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.inputMap.data<bool_type>(), 2 * addFmu.inputMap.size<bool_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.inputMap.size<string_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.inputMap.data<string_type>(), 2 * addFmu.inputMap.size<string_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); //outputs num = addFmu.outputMap.size<real_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.outputMap.data<real_type>(), 2 * addFmu.outputMap.size<real_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.outputMap.size<int_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.outputMap.data<int_type>(), 2 * addFmu.outputMap.size<int_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.outputMap.size<bool_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.outputMap.data<bool_type>(), 2 * addFmu.outputMap.size<bool_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); num = addFmu.outputMap.size<string_type>(); MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void*) addFmu.outputMap.data<string_type>(), 2 * addFmu.outputMap.size<string_type>(), MPI_UINT32_T, 0, MPI_COMM_WORLD); } } #endif } else { #ifdef USE_MPI if (!_usingMPI) throw std::runtime_error("Cannot start mpi simulation."); // quick and dirty bcast for the remote simulation data aka. for the NetworkPlan int num = 0; MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); std::vector<std::tuple<size_type, size_type> > tmp1, tmp2, tmp3, tmp4; for (int i = 0; i < num; ++i) { np.fmuNet.push_back(Network::NetworkFmuInformation()); // sim num MPI_Recv((void*) (&np.fmuNet.back().simPos), 1, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // core num MPI_Recv((void*) (&np.fmuNet.back().corePos), 1, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // solver num MPI_Recv((void*) (&np.fmuNet.back().solverPos), 1, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //inputs MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp1.resize(num); MPI_Recv((void*) tmp1.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp2.resize(num); MPI_Recv((void*) tmp2.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp3.resize(num); MPI_Recv((void*) tmp3.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp4.resize(num); MPI_Recv((void*) tmp4.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); np.fmuNet.back().inputMap = FMI::InputMapping(tmp1, tmp2, tmp3, tmp4); //inputs MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp1.resize(num); MPI_Recv((void*) tmp1.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp2.resize(num); MPI_Recv((void*) tmp2.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp3.resize(num); MPI_Recv((void*) tmp3.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&num, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tmp4.resize(num); MPI_Recv((void*) tmp4.data(), 2 * num, MPI_UINT32_T, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); np.fmuNet.back().outputMap = FMI::InputMapping(tmp1, tmp2, tmp3, tmp4); } #else // test if the rank is on default (0), if not somethings wrong with @param rank. throw std::runtime_error("Internal error. Rank mismatch in network initialization."); #endif } // adding network fmu and connections to program plan Network::appendNetworkInformation(_pp, np); #endif return true; } void Program::deinitMPI() { _isInitialized = false; #ifdef USE_MPI if (_usingMPI) MPI_Finalize(); #endif } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2014 Colin Hill // // 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 "Scene.h" #include "Hect/IO/AssetDecoder.h" using namespace hect; Scene::Scene(Engine& engine) : _engine(engine), _entityCount(0), _entityPool(*this) { _componentPoolMap = ComponentRegistry::createPoolMap(*this); } Engine& Scene::engine() { return _engine; } const Engine& Scene::engine() const { return _engine; } void Scene::refresh() { // Create all entities pending creation for (EntityId entityId : _entitiesPendingCreation) { Entity& entity = _entityPool.entityWithId(entityId); EntityEvent event(EntityEventType_Create, entity); _entityPool.dispatchEvent(event); } _entitiesPendingCreation.clear(); // Activate all entities pending activation for (EntityId entityId : _entitiesPendingActivation) { Entity& entity = _entityPool.entityWithId(entityId); activateEntity(entity); } _entitiesPendingActivation.clear(); // Destroy all entities set pending destruction for (EntityId entityId : _entitiesPendingDestruction) { Entity& entity = _entityPool.entityWithId(entityId); destroyEntity(entity); } _entitiesPendingDestruction.clear(); } void Scene::tick(TimeSpan timeStep) { refresh(); // Tick all systems in order Real timeStepInSeconds = timeStep.seconds(); for (auto& system : _systemTickOrder) { system->tick(timeStepInSeconds); } } Entity::Iterator Scene::createEntity() { Entity::Iterator entity = _entityPool.create(); _entitiesPendingCreation.push_back(entity->id()); return entity; } EntityPool& Scene::entities() { return _entityPool; } const EntityPool& Scene::entities() const { return _entityPool; } size_t Scene::entityCount() const { return _entityCount; } System& Scene::addOrGetSystem(SystemTypeId typeId, bool& added) { // If the system is already added then return it if (typeId < _systems.size() && _systems[typeId]) { added = false; return *_systems[typeId]; } // Otherwise, attempt to add the system else { added = true; // Resize the systems vector if needed while (typeId >= _systems.size()) { size_t oldSize = _systems.size(); _systems.resize(std::max(oldSize * 2, size_t(8))); } // Add the system auto system = SystemRegistry::create(typeId, *this); _systems[typeId] = system; _systemTickOrder.push_back(system.get()); return *system; } } Entity::Iterator Scene::cloneEntity(const Entity& entity) { Entity::ConstIterator sourceEntity = entity.iterator(); Entity::Iterator clonedEntity = createEntity(); for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { componentPool->clone(*sourceEntity, *clonedEntity); } // Recursively clone all children for (const Entity& child : sourceEntity->children()) { Entity::Iterator clonedChild = child.clone(); clonedEntity->addChild(*clonedChild); } return clonedEntity; } void Scene::destroyEntity(Entity& entity) { if (!entity.inPool()) { throw Error("Invalid entity"); } // Dispatch the entity destroy event EntityEvent event(EntityEventType_Destroy, entity); _entityPool.dispatchEvent(event); // Destroy all children std::vector<EntityId> childIds; for (Entity& child : entity.children()) { childIds.push_back(child._id); } for (EntityId childId : childIds) { _entityPool.entityWithId(childId).destroy(); } // Remove all components for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { if (componentPool->has(entity)) { componentPool->remove(entity); } } if (entity._activated) { --_entityCount; } // If the entity had a parent then remove itself as a child Entity::Iterator parent = entity.parent(); if (parent) { parent->removeChild(entity); } _entityPool.destroy(entity._id); } void Scene::activateEntity(Entity& entity) { if (!entity.inPool()) { throw Error("Invalid entity"); } if (entity._activated) { throw Error("Entity is already activated"); } for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { if (componentPool->has(entity)) { componentPool->dispatchEvent(ComponentEventType_Add, entity); } } ++_entityCount; entity._activated = true; entity._pendingActivation = false; // Dispatch the entity activate event EntityEvent event(EntityEventType_Activate, entity); _entityPool.dispatchEvent(event); } void Scene::pendEntityDestruction(Entity& entity) { if (!entity.inPool()) { throw Error("Invalid entity"); } if (entity._pendingDestruction) { throw Error("Entity is already pending destruction"); } entity._pendingDestruction = true; _entitiesPendingDestruction.push_back(entity._id); } void Scene::pendEntityActivation(Entity& entity) { if (!entity.inPool()) { throw Error("Invalid entity"); } if (entity._pendingActivation) { throw Error("Entity is already pending activation"); } else if (entity._activated) { throw Error("Entity is already activated"); } entity._pendingActivation = true; _entitiesPendingActivation.push_back(entity._id); } void Scene::addEntityComponentBase(Entity& entity, const ComponentBase& component) { if (!entity.inPool()) { throw Error("Invalid entity"); } ComponentTypeId typeId = component.typeId(); std::shared_ptr<ComponentPoolBase>& componentPool = _componentPoolMap[typeId]; componentPool->addBase(entity, component); } void Scene::encode(Encoder& encoder) const { encoder << beginObject(); // Systems encoder << beginArray("systems"); for (auto& system : _systemTickOrder) { encoder << beginObject(); std::string typeName = Type::of(*system).name(); if (encoder.isBinaryStream()) { WriteStream& stream = encoder.binaryStream(); stream << SystemRegistry::typeIdOf(typeName); } else { encoder << encodeValue("type", typeName); } system->encode(encoder); encoder << endObject(); } encoder << endArray(); // Entities encoder << beginArray("entities"); for (const Entity& entity : entities()) { // Only encode the root entities (children are encoded recursively) if (!entity.parent()) { encoder << encodeValue(entity); } } encoder << endArray(); encoder << endObject(); } void Scene::decode(Decoder& decoder) { decoder >> beginObject(); // Base if (!decoder.isBinaryStream()) { if (decoder.selectMember("base")) { Path basePath; decoder >> decodeValue(basePath); try { AssetDecoder baseDecoder(decoder.assetCache(), basePath); baseDecoder >> beginObject() >> decodeValue(*this) >> endObject(); } catch (Error& error) { throw Error(format("Failed to load base scene '%s': %s", basePath.asString().c_str(), error.what())); } } } // Systems if (decoder.selectMember("systems")) { decoder >> beginArray(); while (decoder.hasMoreElements()) { decoder >> beginObject(); SystemTypeId typeId; if (decoder.isBinaryStream()) { ReadStream& stream = decoder.binaryStream(); stream >> typeId; } else { std::string typeName; decoder >> decodeValue("type", typeName, true); typeId = SystemRegistry::typeIdOf(typeName); } bool added; System& system = addOrGetSystem(typeId, added); system.decode(decoder); decoder >> endObject(); } decoder >> endArray(); } // Entities if (decoder.selectMember("entities")) { decoder >> beginArray(); while (decoder.hasMoreElements()) { Entity::Iterator entity = createEntity(); decoder >> decodeValue(*entity); entity->activate(); } decoder >> endArray(); } decoder >> endObject(); } void Scene::encodeComponents(const Entity& entity, Encoder& encoder) { if (encoder.isBinaryStream()) { WriteStream& stream = encoder.binaryStream(); size_t componentCountPosition = stream.position(); uint8_t componentCount = 0; stream << componentCount; for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { if (componentPool->has(entity)) { ++componentCount; const ComponentBase& component = componentPool->getBase(entity); stream << component.typeId(); component.encode(encoder); } } size_t currentPosition = stream.position(); stream.seek(componentCountPosition); stream << componentCount; stream.seek(currentPosition); } else { encoder << beginArray("components"); for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { if (componentPool->has(entity)) { encoder << beginObject(); const ComponentBase& component = componentPool->getBase(entity); std::string typeName = Type::of(component).name(); encoder << encodeValue("type", typeName); component.encode(encoder); encoder << endObject(); } } encoder << endArray(); } } void Scene::decodeComponents(Entity& entity, Decoder& decoder) { if (decoder.isBinaryStream()) { ReadStream& stream = decoder.binaryStream(); uint8_t componentCount; stream >> componentCount; for (uint8_t i = 0; i < componentCount; ++i) { ComponentTypeId typeId; stream >> typeId; std::shared_ptr<ComponentBase> component = ComponentRegistry::create(typeId); component->decode(decoder); addEntityComponentBase(entity, *component); } } else { if (decoder.selectMember("components")) { decoder >> beginArray(); while (decoder.hasMoreElements()) { decoder >> beginObject(); std::string typeName; decoder >> decodeValue("type", typeName); ComponentTypeId typeId = ComponentRegistry::typeIdOf(typeName); std::shared_ptr<ComponentBase> component = ComponentRegistry::create(typeId); component->decode(decoder); addEntityComponentBase(entity, *component); decoder >> endObject(); } decoder >> endArray(); } } } namespace hect { Encoder& operator<<(Encoder& encoder, const Scene& scene) { scene.encode(encoder); return encoder; } Decoder& operator>>(Decoder& decoder, Scene& scene) { scene.decode(decoder); return decoder; } }<commit_msg>Separated system type/tick order from system encoding/decoding (see #119)<commit_after>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2014 Colin Hill // // 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 "Scene.h" #include "Hect/IO/AssetDecoder.h" using namespace hect; Scene::Scene(Engine& engine) : _engine(engine), _entityCount(0), _entityPool(*this) { _componentPoolMap = ComponentRegistry::createPoolMap(*this); } Engine& Scene::engine() { return _engine; } const Engine& Scene::engine() const { return _engine; } void Scene::refresh() { // Create all entities pending creation for (EntityId entityId : _entitiesPendingCreation) { Entity& entity = _entityPool.entityWithId(entityId); EntityEvent event(EntityEventType_Create, entity); _entityPool.dispatchEvent(event); } _entitiesPendingCreation.clear(); // Activate all entities pending activation for (EntityId entityId : _entitiesPendingActivation) { Entity& entity = _entityPool.entityWithId(entityId); activateEntity(entity); } _entitiesPendingActivation.clear(); // Destroy all entities set pending destruction for (EntityId entityId : _entitiesPendingDestruction) { Entity& entity = _entityPool.entityWithId(entityId); destroyEntity(entity); } _entitiesPendingDestruction.clear(); } void Scene::tick(TimeSpan timeStep) { refresh(); // Tick all systems in order Real timeStepInSeconds = timeStep.seconds(); for (auto& system : _systemTickOrder) { system->tick(timeStepInSeconds); } } Entity::Iterator Scene::createEntity() { Entity::Iterator entity = _entityPool.create(); _entitiesPendingCreation.push_back(entity->id()); return entity; } EntityPool& Scene::entities() { return _entityPool; } const EntityPool& Scene::entities() const { return _entityPool; } size_t Scene::entityCount() const { return _entityCount; } System& Scene::addOrGetSystem(SystemTypeId typeId, bool& added) { // If the system is already added then return it if (typeId < _systems.size() && _systems[typeId]) { added = false; return *_systems[typeId]; } // Otherwise, attempt to add the system else { added = true; // Resize the systems vector if needed while (typeId >= _systems.size()) { size_t oldSize = _systems.size(); _systems.resize(std::max(oldSize * 2, size_t(8))); } // Add the system auto system = SystemRegistry::create(typeId, *this); _systems[typeId] = system; _systemTickOrder.push_back(system.get()); return *system; } } Entity::Iterator Scene::cloneEntity(const Entity& entity) { Entity::ConstIterator sourceEntity = entity.iterator(); Entity::Iterator clonedEntity = createEntity(); for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { componentPool->clone(*sourceEntity, *clonedEntity); } // Recursively clone all children for (const Entity& child : sourceEntity->children()) { Entity::Iterator clonedChild = child.clone(); clonedEntity->addChild(*clonedChild); } return clonedEntity; } void Scene::destroyEntity(Entity& entity) { if (!entity.inPool()) { throw Error("Invalid entity"); } // Dispatch the entity destroy event EntityEvent event(EntityEventType_Destroy, entity); _entityPool.dispatchEvent(event); // Destroy all children std::vector<EntityId> childIds; for (Entity& child : entity.children()) { childIds.push_back(child._id); } for (EntityId childId : childIds) { _entityPool.entityWithId(childId).destroy(); } // Remove all components for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { if (componentPool->has(entity)) { componentPool->remove(entity); } } if (entity._activated) { --_entityCount; } // If the entity had a parent then remove itself as a child Entity::Iterator parent = entity.parent(); if (parent) { parent->removeChild(entity); } _entityPool.destroy(entity._id); } void Scene::activateEntity(Entity& entity) { if (!entity.inPool()) { throw Error("Invalid entity"); } if (entity._activated) { throw Error("Entity is already activated"); } for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { if (componentPool->has(entity)) { componentPool->dispatchEvent(ComponentEventType_Add, entity); } } ++_entityCount; entity._activated = true; entity._pendingActivation = false; // Dispatch the entity activate event EntityEvent event(EntityEventType_Activate, entity); _entityPool.dispatchEvent(event); } void Scene::pendEntityDestruction(Entity& entity) { if (!entity.inPool()) { throw Error("Invalid entity"); } if (entity._pendingDestruction) { throw Error("Entity is already pending destruction"); } entity._pendingDestruction = true; _entitiesPendingDestruction.push_back(entity._id); } void Scene::pendEntityActivation(Entity& entity) { if (!entity.inPool()) { throw Error("Invalid entity"); } if (entity._pendingActivation) { throw Error("Entity is already pending activation"); } else if (entity._activated) { throw Error("Entity is already activated"); } entity._pendingActivation = true; _entitiesPendingActivation.push_back(entity._id); } void Scene::addEntityComponentBase(Entity& entity, const ComponentBase& component) { if (!entity.inPool()) { throw Error("Invalid entity"); } ComponentTypeId typeId = component.typeId(); std::shared_ptr<ComponentPoolBase>& componentPool = _componentPoolMap[typeId]; componentPool->addBase(entity, component); } void Scene::encode(Encoder& encoder) const { encoder << beginObject(); // System types encoder << beginArray("systemTypes"); for (auto& system : _systemTickOrder) { std::string typeName = Type::of(*system).name(); if (encoder.isBinaryStream()) { WriteStream& stream = encoder.binaryStream(); stream << SystemRegistry::typeIdOf(typeName); } else { encoder << encodeValue(typeName); } } encoder << endArray(); // Systems encoder << beginArray("systems"); for (auto& system : _systemTickOrder) { encoder << beginObject(); system->encode(encoder); encoder << endObject(); } encoder << endArray(); // Entities encoder << beginArray("entities"); for (const Entity& entity : entities()) { // Only encode the root entities (children are encoded recursively) if (!entity.parent()) { encoder << encodeValue(entity); } } encoder << endArray(); encoder << endObject(); } void Scene::decode(Decoder& decoder) { decoder >> beginObject(); // Base if (!decoder.isBinaryStream()) { if (decoder.selectMember("base")) { Path basePath; decoder >> decodeValue(basePath); try { AssetDecoder baseDecoder(decoder.assetCache(), basePath); baseDecoder >> beginObject() >> decodeValue(*this) >> endObject(); } catch (Error& error) { throw Error(format("Failed to load base scene '%s': %s", basePath.asString().c_str(), error.what())); } } } // System types if (decoder.selectMember("systemTypes")) { decoder >> beginArray(); while (decoder.hasMoreElements()) { SystemTypeId typeId; if (decoder.isBinaryStream()) { ReadStream& stream = decoder.binaryStream(); stream >> typeId; } else { std::string typeName; decoder >> decodeValue(typeName); typeId = SystemRegistry::typeIdOf(typeName); } bool added; addOrGetSystem(typeId, added); } decoder >> endArray(); } // Systems if (decoder.selectMember("systems")) { decoder >> beginArray(); while (decoder.hasMoreElements()) { decoder >> beginObject(); SystemTypeId typeId; if (decoder.isBinaryStream()) { ReadStream& stream = decoder.binaryStream(); stream >> typeId; } else { std::string typeName; decoder >> decodeValue("type", typeName, true); typeId = SystemRegistry::typeIdOf(typeName); } bool added; System& system = addOrGetSystem(typeId, added); system.decode(decoder); decoder >> endObject(); } decoder >> endArray(); } // Entities if (decoder.selectMember("entities")) { decoder >> beginArray(); while (decoder.hasMoreElements()) { Entity::Iterator entity = createEntity(); decoder >> decodeValue(*entity); entity->activate(); } decoder >> endArray(); } decoder >> endObject(); } void Scene::encodeComponents(const Entity& entity, Encoder& encoder) { if (encoder.isBinaryStream()) { WriteStream& stream = encoder.binaryStream(); size_t componentCountPosition = stream.position(); uint8_t componentCount = 0; stream << componentCount; for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { if (componentPool->has(entity)) { ++componentCount; const ComponentBase& component = componentPool->getBase(entity); stream << component.typeId(); component.encode(encoder); } } size_t currentPosition = stream.position(); stream.seek(componentCountPosition); stream << componentCount; stream.seek(currentPosition); } else { encoder << beginArray("components"); for (std::shared_ptr<ComponentPoolBase>& componentPool : _componentPoolMap) { if (componentPool->has(entity)) { encoder << beginObject(); const ComponentBase& component = componentPool->getBase(entity); std::string typeName = Type::of(component).name(); encoder << encodeValue("type", typeName); component.encode(encoder); encoder << endObject(); } } encoder << endArray(); } } void Scene::decodeComponents(Entity& entity, Decoder& decoder) { if (decoder.isBinaryStream()) { ReadStream& stream = decoder.binaryStream(); uint8_t componentCount; stream >> componentCount; for (uint8_t i = 0; i < componentCount; ++i) { ComponentTypeId typeId; stream >> typeId; std::shared_ptr<ComponentBase> component = ComponentRegistry::create(typeId); component->decode(decoder); addEntityComponentBase(entity, *component); } } else { if (decoder.selectMember("components")) { decoder >> beginArray(); while (decoder.hasMoreElements()) { decoder >> beginObject(); std::string typeName; decoder >> decodeValue("type", typeName); ComponentTypeId typeId = ComponentRegistry::typeIdOf(typeName); std::shared_ptr<ComponentBase> component = ComponentRegistry::create(typeId); component->decode(decoder); addEntityComponentBase(entity, *component); decoder >> endObject(); } decoder >> endArray(); } } } namespace hect { Encoder& operator<<(Encoder& encoder, const Scene& scene) { scene.encode(encoder); return encoder; } Decoder& operator>>(Decoder& decoder, Scene& scene) { scene.decode(decoder); return decoder; } }<|endoftext|>
<commit_before>// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_WORKERPOOL_HPP #define OUZEL_CORE_WORKERPOOL_HPP #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <queue> #include <vector> #include "../thread/Thread.hpp" #include "../utils/Log.hpp" namespace ouzel::core { class TaskGroup final { friend class WorkerPool; public: TaskGroup() = default; void add(std::function<void()> task) { taskQueue.push(std::move(task)); } std::size_t getTaskCount() const noexcept { return taskQueue.size(); } bool hasTasks() const noexcept { return !taskQueue.empty(); } private: std::queue<std::function<void()>> taskQueue; }; class Future final { friend class WorkerPool; public: Future(const TaskGroup& taskGroup) noexcept: taskCount{taskGroup.getTaskCount()} { } void wait() { std::unique_lock lock{taskMutex}; taskCondition.wait(lock, [this]() noexcept { return taskCount == 0; }); } private: void finishTask() { std::unique_lock lock{taskMutex}; if (--taskCount == 0) { lock.unlock(); taskCondition.notify_all(); } } std::size_t taskCount = 0; std::mutex taskMutex; std::condition_variable taskCondition; }; class WorkerPool final { public: WorkerPool() { const std::size_t cpuCount = std::thread::hardware_concurrency(); const std::size_t count = (cpuCount > 1) ? cpuCount - 1 : 1; for (unsigned int i = 0; i < count; ++i) workers.emplace_back(&WorkerPool::work, this); } ~WorkerPool() { running = false; taskQueueCondition.notify_all(); } Future& run(TaskGroup&& taskGroup) { auto future = std::make_unique<Future>(taskGroup); auto& result = *future; std::unique_lock lock{taskQueueMutex}; taskGroupQueue.push(std::pair(std::move(future), std::move(taskGroup.taskQueue))); lock.unlock(); taskQueueCondition.notify_all(); return result; } private: void work() { log(Log::Level::info) << "Worker started"; for (;;) { std::unique_lock lock{taskQueueMutex}; taskQueueCondition.wait(lock, [this]() noexcept { return !running || !taskGroupQueue.empty(); }); if (!running) break; auto& taskGroup = taskGroupQueue.front(); const auto task = std::move(taskGroup.second.front()); taskGroup.second.pop(); lock.unlock(); task(); taskGroup.first->finishTask(); } log(Log::Level::info) << "Worker finished"; } std::vector<thread::Thread> workers; bool running = true; std::queue<std::pair<std::unique_ptr<Future>, std::queue<std::function<void()>>>> taskGroupQueue; std::mutex taskQueueMutex; std::condition_variable taskQueueCondition; }; } #endif // OUZEL_CORE_WORKERPOOL_HPP <commit_msg>Remove the task group from the queue when the last task is finished<commit_after>// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_WORKERPOOL_HPP #define OUZEL_CORE_WORKERPOOL_HPP #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <queue> #include <vector> #include "../thread/Thread.hpp" #include "../utils/Log.hpp" namespace ouzel::core { class TaskGroup final { friend class WorkerPool; public: TaskGroup() = default; void add(std::function<void()> task) { taskQueue.push(std::move(task)); } std::size_t getTaskCount() const noexcept { return taskQueue.size(); } bool hasTasks() const noexcept { return !taskQueue.empty(); } private: std::queue<std::function<void()>> taskQueue; }; class Future final { friend class WorkerPool; public: Future(const TaskGroup& taskGroup) noexcept: taskCount{taskGroup.getTaskCount()} { } void wait() { std::unique_lock lock{taskMutex}; taskCondition.wait(lock, [this]() noexcept { return taskCount == 0; }); } private: bool finishTask() { std::unique_lock lock{taskMutex}; if (--taskCount == 0) { lock.unlock(); taskCondition.notify_all(); return true; } return false; } std::size_t taskCount = 0; std::mutex taskMutex; std::condition_variable taskCondition; }; class WorkerPool final { public: WorkerPool() { const std::size_t cpuCount = std::thread::hardware_concurrency(); const std::size_t count = (cpuCount > 1) ? cpuCount - 1 : 1; for (unsigned int i = 0; i < count; ++i) workers.emplace_back(&WorkerPool::work, this); } ~WorkerPool() { running = false; taskQueueCondition.notify_all(); } Future& run(TaskGroup&& taskGroup) { auto future = std::make_unique<Future>(taskGroup); auto& result = *future; std::unique_lock lock{taskQueueMutex}; taskGroupQueue.push(std::pair(std::move(future), std::move(taskGroup.taskQueue))); lock.unlock(); taskQueueCondition.notify_all(); return result; } private: void work() { log(Log::Level::info) << "Worker started"; for (;;) { std::unique_lock lock{taskQueueMutex}; taskQueueCondition.wait(lock, [this]() noexcept { return !running || !taskGroupQueue.empty(); }); if (!running) break; auto& taskGroup = taskGroupQueue.front(); const auto task = std::move(taskGroup.second.front()); taskGroup.second.pop(); lock.unlock(); task(); if (taskGroup.first->finishTask()) { lock.lock(); taskGroupQueue.pop(); } } log(Log::Level::info) << "Worker finished"; } std::vector<thread::Thread> workers; bool running = true; std::queue<std::pair<std::unique_ptr<Future>, std::queue<std::function<void()>>>> taskGroupQueue; std::mutex taskQueueMutex; std::condition_variable taskQueueCondition; }; } #endif // OUZEL_CORE_WORKERPOOL_HPP <|endoftext|>
<commit_before>#include "FileSystem.hpp" #include <filesystem> #include <sstream> #include <iomanip> #include <algorithm> namespace AGE { namespace FileSystem { bool CreateFolder(const std::string &path) { if (Exists(path)) return true; return std::tr2::sys::create_directories(std::tr2::sys::path(path)); } bool Exists(const std::string &path) { return std::tr2::sys::exists(std::tr2::sys::path(path)); } std::string GetExtension(const std::string &path) { std::string::size_type pos; pos = path.find_last_of("."); if (pos != std::string::npos) return path.substr(pos + 1, std::string::npos); else return ""; } std::string GetDateStr(const std::string &path, const char *format /*= "%Y/%m/%d %H:%M:%S"*/) { std::stringstream res; auto timeinfo = GetLastWriteTime(path); res << std::put_time(&timeinfo, format); return res.str(); } struct tm GetLastWriteTime(const std::string &path) { auto last_write = std::tr2::sys::last_write_time(std::tr2::sys::path(path)); struct tm timeinfo; localtime_s(&timeinfo, &last_write); return timeinfo; } double GetDiffTime(struct tm &first, struct tm &second) { return difftime(mktime(&first), mktime(&second)); } double GetDiffTime(const std::string &first, const std::string &second) { return GetDiffTime(GetLastWriteTime(first), GetLastWriteTime(second)); } std::string CleanPath(const std::string &path) { auto r = path; std::replace(r.begin(), r.end(), '\\', '/'); return r; } } }<commit_msg>Old filesystem renamed<commit_after>#include "FileSystem.hpp" #include <filesystem> #include <sstream> #include <iomanip> #include <algorithm> namespace AGE { namespace FileSystemHelpers { bool CreateFolder(const std::string &path) { if (Exists(path)) return true; return std::tr2::sys::create_directories(std::tr2::sys::path(path)); } bool Exists(const std::string &path) { return std::tr2::sys::exists(std::tr2::sys::path(path)); } std::string GetExtension(const std::string &path) { std::string::size_type pos; pos = path.find_last_of("."); if (pos != std::string::npos) return path.substr(pos + 1, std::string::npos); else return ""; } std::string GetDateStr(const std::string &path, const char *format /*= "%Y/%m/%d %H:%M:%S"*/) { std::stringstream res; auto timeinfo = GetLastWriteTime(path); res << std::put_time(&timeinfo, format); return res.str(); } struct tm GetLastWriteTime(const std::string &path) { auto last_write = std::tr2::sys::last_write_time(std::tr2::sys::path(path)); struct tm timeinfo; localtime_s(&timeinfo, &last_write); return timeinfo; } double GetDiffTime(struct tm &first, struct tm &second) { return difftime(mktime(&first), mktime(&second)); } double GetDiffTime(const std::string &first, const std::string &second) { return GetDiffTime(GetLastWriteTime(first), GetLastWriteTime(second)); } std::string CleanPath(const std::string &path) { auto r = path; std::replace(r.begin(), r.end(), '\\', '/'); return r; } } }<|endoftext|>
<commit_before>// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_WORKERPOOL_HPP #define OUZEL_CORE_WORKERPOOL_HPP #include <condition_variable> #include <functional> #include <mutex> #include <queue> #include <vector> #include "../thread/Thread.hpp" #include "../utils/Log.hpp" namespace ouzel::core { class TaskGroup final { friend class WorkerPool; public: TaskGroup() = default; void add(std::function<void()> task) { taskQueue.push(std::move(task)); ++taskCount; } void wait() { std::unique_lock lock{taskMutex}; taskCondition.wait(lock, [this]() noexcept { return taskCount != 0; }); } private: void finishTask() { std::unique_lock lock{taskMutex}; if (--taskCount == 0) { lock.unlock(); taskCondition.notify_all(); } } std::queue<std::function<void()>> taskQueue; std::size_t taskCount = 0; std::mutex taskMutex; std::condition_variable taskCondition; }; class WorkerPool final { public: WorkerPool() { const std::size_t cpuCount = std::thread::hardware_concurrency(); const std::size_t count = (cpuCount > 1) ? cpuCount - 1 : 1; for (unsigned int i = 0; i < count; ++i) workers.emplace_back(&WorkerPool::work, this); } ~WorkerPool() { running = false; taskQueueCondition.notify_all(); } void run(TaskGroup& taskGroup) { std::unique_lock lock{taskQueueMutex}; taskGroupQueue.push(taskGroup); while (!taskGroup.taskQueue.empty()) { taskQueue.push(std::move(taskGroup.taskQueue.front())); taskGroup.taskQueue.pop(); } lock.unlock(); taskQueueCondition.notify_all(); } void run(std::function<void()> task) { std::unique_lock lock{taskQueueMutex}; taskQueue.push(std::move(task)); lock.unlock(); taskQueueCondition.notify_one(); } private: void work() { log(Log::Level::info) << "Worker started"; for (;;) { std::unique_lock lock{taskQueueMutex}; taskQueueCondition.wait(lock, [this]() noexcept { return !running || !taskQueue.empty(); }); if (!running) break; const auto task = std::move(taskQueue.front()); taskQueue.pop(); lock.unlock(); task(); } log(Log::Level::info) << "Worker finished"; } std::vector<thread::Thread> workers; bool running = true; std::queue<std::function<void()>> taskQueue; std::queue<std::reference_wrapper<TaskGroup>> taskGroupQueue; std::mutex taskQueueMutex; std::condition_variable taskQueueCondition; }; } #endif // OUZEL_CORE_WORKERPOOL_HPP <commit_msg>Return future from run<commit_after>// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_WORKERPOOL_HPP #define OUZEL_CORE_WORKERPOOL_HPP #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <queue> #include <vector> #include "../thread/Thread.hpp" #include "../utils/Log.hpp" namespace ouzel::core { class TaskGroup final { friend class WorkerPool; public: TaskGroup() = default; void add(std::function<void()> task) { taskQueue.push(std::move(task)); } std::size_t getTaskCount() const noexcept { return taskQueue.size(); } bool hasTasks() const noexcept { return !taskQueue.empty(); } private: std::queue<std::function<void()>> taskQueue; }; class Future final { friend class WorkerPool; public: Future(const TaskGroup& taskGroup) noexcept: taskCount{taskGroup.getTaskCount()} { } void wait() { std::unique_lock lock{taskMutex}; taskCondition.wait(lock, [this]() noexcept { return taskCount == 0; }); } private: void finishTask() { std::unique_lock lock{taskMutex}; if (--taskCount == 0) { lock.unlock(); taskCondition.notify_all(); } } std::size_t taskCount = 0; std::mutex taskMutex; std::condition_variable taskCondition; }; class WorkerPool final { public: WorkerPool() { const std::size_t cpuCount = std::thread::hardware_concurrency(); const std::size_t count = (cpuCount > 1) ? cpuCount - 1 : 1; for (unsigned int i = 0; i < count; ++i) workers.emplace_back(&WorkerPool::work, this); } ~WorkerPool() { running = false; taskQueueCondition.notify_all(); } Future& run(TaskGroup&& taskGroup) { auto future = std::make_unique<Future>(taskGroup); auto& result = *future; std::unique_lock lock{taskQueueMutex}; taskGroupQueue.push(std::pair(std::move(future), std::move(taskGroup.taskQueue))); lock.unlock(); taskQueueCondition.notify_all(); return result; } private: void work() { log(Log::Level::info) << "Worker started"; for (;;) { std::unique_lock lock{taskQueueMutex}; taskQueueCondition.wait(lock, [this]() noexcept { return !running || !taskGroupQueue.empty(); }); if (!running) break; auto& taskGroup = taskGroupQueue.front(); const auto task = std::move(taskGroup.second.front()); taskGroup.second.pop(); lock.unlock(); task(); taskGroup.first->finishTask(); } log(Log::Level::info) << "Worker finished"; } std::vector<thread::Thread> workers; bool running = true; std::queue<std::pair<std::unique_ptr<Future>, std::queue<std::function<void()>>>> taskGroupQueue; std::mutex taskQueueMutex; std::condition_variable taskQueueCondition; }; } #endif // OUZEL_CORE_WORKERPOOL_HPP <|endoftext|>
<commit_before>#include <ctti/serialization.hpp> #include <sstream> #include "catch.hpp" namespace symbols { CTTI_DEFINE_SYMBOL(A); CTTI_DEFINE_SYMBOL(B); CTTI_DEFINE_SYMBOL(a); CTTI_DEFINE_SYMBOL(b); CTTI_DEFINE_SYMBOL(c); CTTI_DEFINE_SYMBOL(d); } struct Foo { enum class Enum { A, B }; int a; std::string b; Enum c; struct Bar { std::vector<int> a{1, 2, 3, 4}; std::unordered_map<Enum, std::string> b{ {Enum::A, "A"}, {Enum::B, "B"} }; using ctti_model = ctti::model<symbols::a, symbols::b>; }; Bar d; using ctti_model = ctti::model<symbols::a, symbols::b, symbols::c, symbols::d>; }; ctti::model<symbols::A, symbols::B> ctti_model(ctti::type_tag<Foo::Enum>); TEST_CASE("serialization") { Foo foo{42, "42", Foo::Enum::A}; std::ostringstream ss; ctti::serialization::serialize(ctti::serialization::json_formatter(), ctti::serialization::ostream_otuput(ss), foo); REQUIRE(ss.str() == R"({"a": 42, "b": "42", "c": A, "d": {"a": [1, 2, 3, 4], "b": [{B: "B"}, {A: "A"}]}})"); } <commit_msg>fix serialization test<commit_after>#include <ctti/serialization.hpp> #include <sstream> #include "catch.hpp" namespace symbols { CTTI_DEFINE_SYMBOL(A); CTTI_DEFINE_SYMBOL(B); CTTI_DEFINE_SYMBOL(a); CTTI_DEFINE_SYMBOL(b); CTTI_DEFINE_SYMBOL(c); CTTI_DEFINE_SYMBOL(d); } struct Foo { enum class Enum { A, B }; int a; std::string b; Enum c; struct Bar { struct enum_hash { std::size_t operator()(Foo::Enum value) const { return std::hash<ctti::meta::type_t<std::underlying_type<Foo::Enum>>>()( static_cast<ctti::meta::type_t<std::underlying_type<Foo::Enum>>>(value) ); } }; std::vector<int> a{1, 2, 3, 4}; std::unordered_map<Enum, std::string, enum_hash> b{ {Enum::A, "A"}, {Enum::B, "B"} }; using ctti_model = ctti::model<symbols::a, symbols::b>; }; Bar d; using ctti_model = ctti::model<symbols::a, symbols::b, symbols::c, symbols::d>; }; ctti::model<symbols::A, symbols::B> ctti_model(ctti::type_tag<Foo::Enum>); TEST_CASE("serialization") { Foo foo{42, "42", Foo::Enum::A}; std::ostringstream ss; ctti::serialization::serialize(ctti::serialization::json_formatter(), ctti::serialization::ostream_otuput(ss), foo); REQUIRE(ss.str() == R"({"a": 42, "b": "42", "c": A, "d": {"a": [1, 2, 3, 4], "b": [{B: "B"}, {A: "A"}]}})"); } <|endoftext|>
<commit_before>// @(#)root/thread:$Id$ // Author: Danilo Piparo, CERN 11/2/2016 /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TThreadedObject #define ROOT_TThreadedObject #include "ROOT/TSpinMutex.hxx" #include "TDirectory.h" #include "TError.h" #include "TList.h" #include "TROOT.h" #include <algorithm> #include <exception> #include <deque> #include <functional> #include <map> #include <memory> #include <mutex> #include <sstream> #include <string> #include <thread> #include <vector> class TH1; namespace ROOT { /** * \class ROOT::TNumSlots * \brief Defines the number of threads in some of ROOT's interfaces. */ struct TNumSlots { unsigned int fVal; // number of slots friend bool operator==(TNumSlots lhs, TNumSlots rhs) { return lhs.fVal == rhs.fVal; } friend bool operator!=(TNumSlots lhs, TNumSlots rhs) { return lhs.fVal != rhs.fVal; } }; namespace Internal { namespace TThreadedObjectUtils { template<typename T, bool ISHISTO = std::is_base_of<TH1,T>::value> struct Detacher{ static T* Detach(T* obj) { return obj; } }; template<typename T> struct Detacher<T, true>{ static T* Detach(T* obj) { obj->SetDirectory(nullptr); obj->ResetBit(kMustCleanup); return obj; } }; /// Return a copy of the object or a "Clone" if the copy constructor is not implemented. template<class T, bool isCopyConstructible = std::is_copy_constructible<T>::value> struct Cloner { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = new T(*obj); } else { clone = new T(*obj); } return Detacher<T>::Detach(clone); } }; template<class T> struct Cloner<T, false> { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = (T*)obj->Clone(); } else { clone = (T*)obj->Clone(); } return clone; } }; template <class T, bool ISHISTO = std::is_base_of<TH1, T>::value> struct DirCreator { static TDirectory *Create() { static unsigned dirCounter = 0; const std::string dirName = "__TThreaded_dir_" + std::to_string(dirCounter++) + "_"; return gROOT->mkdir(dirName.c_str()); } }; template <class T> struct DirCreator<T, true> { static TDirectory *Create() { return nullptr; } }; } // End of namespace TThreadedObjectUtils } // End of namespace Internal namespace TThreadedObjectUtils { template<class T> using MergeFunctionType = std::function<void(std::shared_ptr<T>, std::vector<std::shared_ptr<T>>&)>; /// Merge TObjects template<class T> void MergeTObjects(std::shared_ptr<T> target, std::vector<std::shared_ptr<T>> &objs) { if (!target) return; TList objTList; // Cannot do better than this for (auto obj : objs) { if (obj && obj != target) objTList.Add(obj.get()); } target->Merge(&objTList); } } // end of namespace TThreadedObjectUtils /** * \class ROOT::TThreadedObject * \brief A wrapper to make object instances thread private, lazily. * \tparam T Class of the object to be made thread private (e.g. TH1F) * \ingroup Multicore * * A wrapper which makes objects thread private. The methods of the underlying * object can be invoked via the arrow operator. The object is created in * a specific thread lazily, i.e. upon invocation of one of its methods. * The correct object pointer from within a particular thread can be accessed * with the overloaded arrow operator or with the Get method. * In case an elaborate thread management is in place, e.g. in presence of * stream of operations or "processing slots", it is also possible to * manually select the correct object pointer explicitly. */ template<class T> class TThreadedObject { public: /// The initial number of empty processing slots that a TThreadedObject is constructed with by default. /// Deprecated: TThreadedObject grows as more slots are required. static constexpr const TNumSlots fgMaxSlots{64}; TThreadedObject(const TThreadedObject&) = delete; /// Construct the TThreadedObject with initSlots empty slots and the "model" of the thread private objects. /// \param initSlots Set the initial number of slots of the TThreadedObject. /// \tparam ARGS Arguments of the constructor of T /// /// This form of the constructor is useful to manually pre-set the content of a given number of slots /// when used in combination with TThreadedObject::SetAtSlot(). template <class... ARGS> TThreadedObject(TNumSlots initSlots, ARGS &&... args) : fIsMerged(false) { const auto nSlots = initSlots.fVal; fObjPointers.resize(nSlots); // create at least one directory (we need it for fModel), plus others as needed by the size of fObjPointers fDirectories.emplace_back(Internal::TThreadedObjectUtils::DirCreator<T>::Create()); for (auto i = 1u; i < nSlots; ++i) fDirectories.emplace_back(Internal::TThreadedObjectUtils::DirCreator<T>::Create()); TDirectory::TContext ctxt(fDirectories[0]); fModel.reset(Internal::TThreadedObjectUtils::Detacher<T>::Detach(new T(std::forward<ARGS>(args)...))); } /// Construct the TThreadedObject and the "model" of the thread private objects. /// \tparam ARGS Arguments of the constructor of T template<class ...ARGS> TThreadedObject(ARGS&&... args) : TThreadedObject(fgMaxSlots, args...) { } /// Return the number of currently available slot. /// /// The method is safe to call concurrently to other TThreadedObject methods. /// Note that slots could be available but contain no data (i.e. a nullptr) if /// they have not been used yet. unsigned GetNSlots() const { std::lock_guard<ROOT::TSpinMutex> lg(fSpinMutex); return fObjPointers.size(); } /// Access a particular processing slot. /// /// This method is thread-safe as long as concurrent calls request different slots (i.e. pass a different /// argument) and no thread accesses slot `i` via the arrow operator, so mixing usage of GetAtSlot /// with usage of the arrow operator can be dangerous. std::shared_ptr<T> GetAtSlot(unsigned i) { std::size_t nAvailableSlots; { // fObjPointers can grow due to a concurrent operation on this TThreadedObject, need to lock std::lock_guard<ROOT::TSpinMutex> lg(fSpinMutex); nAvailableSlots = fObjPointers.size(); } if (i >= nAvailableSlots) { Warning("TThreadedObject::GetAtSlot", "This slot does not exist."); return nullptr; } auto &objPointer = fObjPointers[i]; if (!objPointer) objPointer.reset(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get(), fDirectories[i])); return objPointer; } /// Set the value of a particular slot. /// /// This method is thread-safe as long as concurrent calls access different slots (i.e. pass a different /// argument) and no thread accesses slot `i` via the arrow operator, so mixing usage of SetAtSlot /// with usage of the arrow operator can be dangerous. void SetAtSlot(unsigned i, std::shared_ptr<T> v) { std::size_t nAvailableSlots; { // fObjPointers can grow due to a concurrent operation on this TThreadedObject, need to lock std::lock_guard<ROOT::TSpinMutex> lg(fSpinMutex); nAvailableSlots = fObjPointers.size(); } if (i >= nAvailableSlots) { Warning("TThreadedObject::SetAtSlot", "This slot does not exist, doing nothing."); return; } fObjPointers[i] = v; } /// Access a particular slot which corresponds to a single thread. /// This is in general faster than the GetAtSlot method but it is /// responsibility of the caller to make sure that the slot exists /// and to check that the contained object is initialized (and not /// a nullptr). std::shared_ptr<T> GetAtSlotUnchecked(unsigned i) const { return fObjPointers[i]; } /// Access a particular slot which corresponds to a single thread. /// This overload is faster than the GetAtSlotUnchecked method but /// the caller is responsible to make sure that the slot exists, to /// check that the contained object is initialized and that the returned /// pointer will not outlive the TThreadedObject that returned it, which /// maintains ownership of the actual object. T* GetAtSlotRaw(unsigned i) const { return fObjPointers[i].get(); } /// Access the pointer corresponding to the current slot. This method is /// not adequate for being called inside tight loops as it implies a /// lookup in a mapping between the threadIDs and the slot indices. /// A good practice consists in copying the pointer onto the stack and /// proceed with the loop as shown in this work item (psudo-code) which /// will be sent to different threads: /// ~~~{.cpp} /// auto workItem = [](){ /// auto objPtr = tthreadedObject.Get(); /// for (auto i : ROOT::TSeqI(1000)) { /// // tthreadedObject->FastMethod(i); // don't do this! Inefficient! /// objPtr->FastMethod(i); /// } /// } /// ~~~ std::shared_ptr<T> Get() { return GetAtSlot(GetThisSlotNumber()); } /// Access the wrapped object and allow to call its methods. T *operator->() { return Get().get(); } /// Merge all the thread private objects. Can be called once: it does not /// create any new object but destroys the present bookkeping collapsing /// all objects into the one at slot 0. std::shared_ptr<T> Merge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { // We do not return if we already merged. if (fIsMerged) { Warning("TThreadedObject::Merge", "This object was already merged. Returning the previous result."); return fObjPointers[0]; } // need to convert to std::vector because historically mergeFunction requires a vector auto vecOfObjPtrs = std::vector<std::shared_ptr<T>>(fObjPointers.begin(), fObjPointers.end()); mergeFunction(fObjPointers[0], vecOfObjPtrs); fIsMerged = true; return fObjPointers[0]; } /// Merge all the thread private objects. Can be called many times. It /// does create a new instance of class T to represent the "Sum" object. /// This method is not thread safe: correct or acceptable behaviours /// depend on the nature of T and of the merging function. std::unique_ptr<T> SnapshotMerge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { if (fIsMerged) { Warning("TThreadedObject::SnapshotMerge", "This object was already merged. Returning the previous result."); return std::unique_ptr<T>(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fObjPointers[0].get())); } auto targetPtr = Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get()); std::shared_ptr<T> targetPtrShared(targetPtr, [](T *) {}); // need to convert to std::vector because historically mergeFunction requires a vector auto vecOfObjPtrs = std::vector<std::shared_ptr<T>>(fObjPointers.begin(), fObjPointers.end()); mergeFunction(targetPtrShared, vecOfObjPtrs); return std::unique_ptr<T>(targetPtr); } private: std::unique_ptr<T> fModel; ///< Use to store a "model" of the object // std::deque's guarantee that references to the elements are not invalidated when appending new slots std::deque<std::shared_ptr<T>> fObjPointers; ///< An object pointer per slot // If the object is a histogram, we also create dummy directories that the histogram associates with // so we do not pollute gDirectory std::deque<TDirectory*> fDirectories; ///< A TDirectory per slot std::map<std::thread::id, unsigned> fThrIDSlotMap; ///< A mapping between the thread IDs and the slots mutable ROOT::TSpinMutex fSpinMutex; ///< Protects concurrent access to fThrIDSlotMap, fObjPointers bool fIsMerged : 1; ///< Remember if the objects have been merged already /// Get the slot number for this threadID, make a slot if needed unsigned GetThisSlotNumber() { const auto thisThreadID = std::this_thread::get_id(); std::lock_guard<ROOT::TSpinMutex> lg(fSpinMutex); const auto thisSlotNumIt = fThrIDSlotMap.find(thisThreadID); if (thisSlotNumIt != fThrIDSlotMap.end()) return thisSlotNumIt->second; const auto newIndex = fThrIDSlotMap.size(); fThrIDSlotMap[thisThreadID] = newIndex; R__ASSERT(newIndex <= fObjPointers.size() && "This should never happen, we should create new slots as needed"); if (newIndex == fObjPointers.size()) { fDirectories.emplace_back(Internal::TThreadedObjectUtils::DirCreator<T>::Create()); fObjPointers.emplace_back(nullptr); } return newIndex; } }; } // End ROOT namespace //////////////////////////////////////////////////////////////////////////////// /// Print a TThreadedObject at the prompt: namespace cling { template<class T> std::string printValue(ROOT::TThreadedObject<T> *val) { auto model = ((std::unique_ptr<T>*)(val))->get(); std::ostringstream ret; ret << "A wrapper to make object instances thread private, lazily. " << "The model which is replicated is " << printValue(model); return ret.str(); } } #endif <commit_msg>[core] Provide definition of TThreadedObject<T>::fgMaxSlots.<commit_after>// @(#)root/thread:$Id$ // Author: Danilo Piparo, CERN 11/2/2016 /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TThreadedObject #define ROOT_TThreadedObject #include "ROOT/TSpinMutex.hxx" #include "TDirectory.h" #include "TError.h" #include "TList.h" #include "TROOT.h" #include <algorithm> #include <exception> #include <deque> #include <functional> #include <map> #include <memory> #include <mutex> #include <sstream> #include <string> #include <thread> #include <vector> class TH1; namespace ROOT { /** * \class ROOT::TNumSlots * \brief Defines the number of threads in some of ROOT's interfaces. */ struct TNumSlots { unsigned int fVal; // number of slots friend bool operator==(TNumSlots lhs, TNumSlots rhs) { return lhs.fVal == rhs.fVal; } friend bool operator!=(TNumSlots lhs, TNumSlots rhs) { return lhs.fVal != rhs.fVal; } }; namespace Internal { namespace TThreadedObjectUtils { template<typename T, bool ISHISTO = std::is_base_of<TH1,T>::value> struct Detacher{ static T* Detach(T* obj) { return obj; } }; template<typename T> struct Detacher<T, true>{ static T* Detach(T* obj) { obj->SetDirectory(nullptr); obj->ResetBit(kMustCleanup); return obj; } }; /// Return a copy of the object or a "Clone" if the copy constructor is not implemented. template<class T, bool isCopyConstructible = std::is_copy_constructible<T>::value> struct Cloner { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = new T(*obj); } else { clone = new T(*obj); } return Detacher<T>::Detach(clone); } }; template<class T> struct Cloner<T, false> { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = (T*)obj->Clone(); } else { clone = (T*)obj->Clone(); } return clone; } }; template <class T, bool ISHISTO = std::is_base_of<TH1, T>::value> struct DirCreator { static TDirectory *Create() { static unsigned dirCounter = 0; const std::string dirName = "__TThreaded_dir_" + std::to_string(dirCounter++) + "_"; return gROOT->mkdir(dirName.c_str()); } }; template <class T> struct DirCreator<T, true> { static TDirectory *Create() { return nullptr; } }; } // End of namespace TThreadedObjectUtils } // End of namespace Internal namespace TThreadedObjectUtils { template<class T> using MergeFunctionType = std::function<void(std::shared_ptr<T>, std::vector<std::shared_ptr<T>>&)>; /// Merge TObjects template<class T> void MergeTObjects(std::shared_ptr<T> target, std::vector<std::shared_ptr<T>> &objs) { if (!target) return; TList objTList; // Cannot do better than this for (auto obj : objs) { if (obj && obj != target) objTList.Add(obj.get()); } target->Merge(&objTList); } } // end of namespace TThreadedObjectUtils /** * \class ROOT::TThreadedObject * \brief A wrapper to make object instances thread private, lazily. * \tparam T Class of the object to be made thread private (e.g. TH1F) * \ingroup Multicore * * A wrapper which makes objects thread private. The methods of the underlying * object can be invoked via the arrow operator. The object is created in * a specific thread lazily, i.e. upon invocation of one of its methods. * The correct object pointer from within a particular thread can be accessed * with the overloaded arrow operator or with the Get method. * In case an elaborate thread management is in place, e.g. in presence of * stream of operations or "processing slots", it is also possible to * manually select the correct object pointer explicitly. */ template<class T> class TThreadedObject { public: /// The initial number of empty processing slots that a TThreadedObject is constructed with by default. /// Deprecated: TThreadedObject grows as more slots are required. static constexpr const TNumSlots fgMaxSlots{64}; TThreadedObject(const TThreadedObject&) = delete; /// Construct the TThreadedObject with initSlots empty slots and the "model" of the thread private objects. /// \param initSlots Set the initial number of slots of the TThreadedObject. /// \tparam ARGS Arguments of the constructor of T /// /// This form of the constructor is useful to manually pre-set the content of a given number of slots /// when used in combination with TThreadedObject::SetAtSlot(). template <class... ARGS> TThreadedObject(TNumSlots initSlots, ARGS &&... args) : fIsMerged(false) { const auto nSlots = initSlots.fVal; fObjPointers.resize(nSlots); // create at least one directory (we need it for fModel), plus others as needed by the size of fObjPointers fDirectories.emplace_back(Internal::TThreadedObjectUtils::DirCreator<T>::Create()); for (auto i = 1u; i < nSlots; ++i) fDirectories.emplace_back(Internal::TThreadedObjectUtils::DirCreator<T>::Create()); TDirectory::TContext ctxt(fDirectories[0]); fModel.reset(Internal::TThreadedObjectUtils::Detacher<T>::Detach(new T(std::forward<ARGS>(args)...))); } /// Construct the TThreadedObject and the "model" of the thread private objects. /// \tparam ARGS Arguments of the constructor of T template<class ...ARGS> TThreadedObject(ARGS&&... args) : TThreadedObject(fgMaxSlots, args...) { } /// Return the number of currently available slot. /// /// The method is safe to call concurrently to other TThreadedObject methods. /// Note that slots could be available but contain no data (i.e. a nullptr) if /// they have not been used yet. unsigned GetNSlots() const { std::lock_guard<ROOT::TSpinMutex> lg(fSpinMutex); return fObjPointers.size(); } /// Access a particular processing slot. /// /// This method is thread-safe as long as concurrent calls request different slots (i.e. pass a different /// argument) and no thread accesses slot `i` via the arrow operator, so mixing usage of GetAtSlot /// with usage of the arrow operator can be dangerous. std::shared_ptr<T> GetAtSlot(unsigned i) { std::size_t nAvailableSlots; { // fObjPointers can grow due to a concurrent operation on this TThreadedObject, need to lock std::lock_guard<ROOT::TSpinMutex> lg(fSpinMutex); nAvailableSlots = fObjPointers.size(); } if (i >= nAvailableSlots) { Warning("TThreadedObject::GetAtSlot", "This slot does not exist."); return nullptr; } auto &objPointer = fObjPointers[i]; if (!objPointer) objPointer.reset(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get(), fDirectories[i])); return objPointer; } /// Set the value of a particular slot. /// /// This method is thread-safe as long as concurrent calls access different slots (i.e. pass a different /// argument) and no thread accesses slot `i` via the arrow operator, so mixing usage of SetAtSlot /// with usage of the arrow operator can be dangerous. void SetAtSlot(unsigned i, std::shared_ptr<T> v) { std::size_t nAvailableSlots; { // fObjPointers can grow due to a concurrent operation on this TThreadedObject, need to lock std::lock_guard<ROOT::TSpinMutex> lg(fSpinMutex); nAvailableSlots = fObjPointers.size(); } if (i >= nAvailableSlots) { Warning("TThreadedObject::SetAtSlot", "This slot does not exist, doing nothing."); return; } fObjPointers[i] = v; } /// Access a particular slot which corresponds to a single thread. /// This is in general faster than the GetAtSlot method but it is /// responsibility of the caller to make sure that the slot exists /// and to check that the contained object is initialized (and not /// a nullptr). std::shared_ptr<T> GetAtSlotUnchecked(unsigned i) const { return fObjPointers[i]; } /// Access a particular slot which corresponds to a single thread. /// This overload is faster than the GetAtSlotUnchecked method but /// the caller is responsible to make sure that the slot exists, to /// check that the contained object is initialized and that the returned /// pointer will not outlive the TThreadedObject that returned it, which /// maintains ownership of the actual object. T* GetAtSlotRaw(unsigned i) const { return fObjPointers[i].get(); } /// Access the pointer corresponding to the current slot. This method is /// not adequate for being called inside tight loops as it implies a /// lookup in a mapping between the threadIDs and the slot indices. /// A good practice consists in copying the pointer onto the stack and /// proceed with the loop as shown in this work item (psudo-code) which /// will be sent to different threads: /// ~~~{.cpp} /// auto workItem = [](){ /// auto objPtr = tthreadedObject.Get(); /// for (auto i : ROOT::TSeqI(1000)) { /// // tthreadedObject->FastMethod(i); // don't do this! Inefficient! /// objPtr->FastMethod(i); /// } /// } /// ~~~ std::shared_ptr<T> Get() { return GetAtSlot(GetThisSlotNumber()); } /// Access the wrapped object and allow to call its methods. T *operator->() { return Get().get(); } /// Merge all the thread private objects. Can be called once: it does not /// create any new object but destroys the present bookkeping collapsing /// all objects into the one at slot 0. std::shared_ptr<T> Merge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { // We do not return if we already merged. if (fIsMerged) { Warning("TThreadedObject::Merge", "This object was already merged. Returning the previous result."); return fObjPointers[0]; } // need to convert to std::vector because historically mergeFunction requires a vector auto vecOfObjPtrs = std::vector<std::shared_ptr<T>>(fObjPointers.begin(), fObjPointers.end()); mergeFunction(fObjPointers[0], vecOfObjPtrs); fIsMerged = true; return fObjPointers[0]; } /// Merge all the thread private objects. Can be called many times. It /// does create a new instance of class T to represent the "Sum" object. /// This method is not thread safe: correct or acceptable behaviours /// depend on the nature of T and of the merging function. std::unique_ptr<T> SnapshotMerge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { if (fIsMerged) { Warning("TThreadedObject::SnapshotMerge", "This object was already merged. Returning the previous result."); return std::unique_ptr<T>(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fObjPointers[0].get())); } auto targetPtr = Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get()); std::shared_ptr<T> targetPtrShared(targetPtr, [](T *) {}); // need to convert to std::vector because historically mergeFunction requires a vector auto vecOfObjPtrs = std::vector<std::shared_ptr<T>>(fObjPointers.begin(), fObjPointers.end()); mergeFunction(targetPtrShared, vecOfObjPtrs); return std::unique_ptr<T>(targetPtr); } private: std::unique_ptr<T> fModel; ///< Use to store a "model" of the object // std::deque's guarantee that references to the elements are not invalidated when appending new slots std::deque<std::shared_ptr<T>> fObjPointers; ///< An object pointer per slot // If the object is a histogram, we also create dummy directories that the histogram associates with // so we do not pollute gDirectory std::deque<TDirectory*> fDirectories; ///< A TDirectory per slot std::map<std::thread::id, unsigned> fThrIDSlotMap; ///< A mapping between the thread IDs and the slots mutable ROOT::TSpinMutex fSpinMutex; ///< Protects concurrent access to fThrIDSlotMap, fObjPointers bool fIsMerged : 1; ///< Remember if the objects have been merged already /// Get the slot number for this threadID, make a slot if needed unsigned GetThisSlotNumber() { const auto thisThreadID = std::this_thread::get_id(); std::lock_guard<ROOT::TSpinMutex> lg(fSpinMutex); const auto thisSlotNumIt = fThrIDSlotMap.find(thisThreadID); if (thisSlotNumIt != fThrIDSlotMap.end()) return thisSlotNumIt->second; const auto newIndex = fThrIDSlotMap.size(); fThrIDSlotMap[thisThreadID] = newIndex; R__ASSERT(newIndex <= fObjPointers.size() && "This should never happen, we should create new slots as needed"); if (newIndex == fObjPointers.size()) { fDirectories.emplace_back(Internal::TThreadedObjectUtils::DirCreator<T>::Create()); fObjPointers.emplace_back(nullptr); } return newIndex; } }; template<class T> constexpr const TNumSlots TThreadedObject<T>::fgMaxSlots; } // End ROOT namespace //////////////////////////////////////////////////////////////////////////////// /// Print a TThreadedObject at the prompt: namespace cling { template<class T> std::string printValue(ROOT::TThreadedObject<T> *val) { auto model = ((std::unique_ptr<T>*)(val))->get(); std::ostringstream ret; ret << "A wrapper to make object instances thread private, lazily. " << "The model which is replicated is " << printValue(model); return ret.str(); } } #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_cc_infobar.h" #include "app/resource_bundle.h" #include "chrome/browser/views/event_utils.h" #include "chrome/browser/views/infobars/infobar_button_border.h" #include "chrome/browser/views/infobars/infobars.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "views/controls/button/text_button.h" #include "views/controls/link.h" class SaveCCInfoConfirmInfoBar : public AlertInfoBar, public views::LinkController { public: explicit SaveCCInfoConfirmInfoBar(ConfirmInfoBarDelegate* delegate); virtual ~SaveCCInfoConfirmInfoBar(); // Overridden from views::View: virtual void Layout(); // Overridden from views::LinkController: virtual void LinkActivated(views::Link* source, int event_flags); protected: // Overridden from views::View: virtual void ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child); // Overridden from views::ButtonListener: virtual void ButtonPressed(views::Button* sender, const views::Event& event); // Overridden from InfoBar: virtual int GetAvailableWidth() const; private: void Init(); views::TextButton* CreateTextButton(const std::wstring& text); ConfirmInfoBarDelegate* GetDelegate(); // The buttons are owned by InfoBar view from the moment they are added to its // hierarchy (Init() called), but we still need pointers to them to process // messages from them. views::TextButton* save_button_; views::TextButton* dont_save_button_; views::Link* link_; bool initialized_; DISALLOW_COPY_AND_ASSIGN(SaveCCInfoConfirmInfoBar); }; SaveCCInfoConfirmInfoBar::SaveCCInfoConfirmInfoBar( ConfirmInfoBarDelegate* delegate) : AlertInfoBar(delegate), initialized_(false) { save_button_ = CreateTextButton(delegate->GetButtonLabel( ConfirmInfoBarDelegate::BUTTON_OK)); dont_save_button_ = CreateTextButton(delegate->GetButtonLabel( ConfirmInfoBarDelegate::BUTTON_CANCEL)); // Set up the link. link_ = new views::Link; link_->SetText(delegate->GetLinkText()); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); link_->SetFont(rb.GetFont(ResourceBundle::MediumFont)); link_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); link_->SetController(this); link_->MakeReadableOverBackgroundColor(background()->get_color()); } SaveCCInfoConfirmInfoBar::~SaveCCInfoConfirmInfoBar() { if (!initialized_) { delete save_button_; delete dont_save_button_; delete link_; } } void SaveCCInfoConfirmInfoBar::Layout() { // Layout the close button. InfoBar::Layout(); int available_width = AlertInfoBar::GetAvailableWidth(); // Now append the link to the label's right edge. link_->SetVisible(!link_->GetText().empty()); gfx::Size link_ps = link_->GetPreferredSize(); int link_x = available_width - kButtonButtonSpacing - link_ps.width(); link_->SetBounds(link_x, OffsetY(this, link_ps), link_ps.width(), link_ps.height()); available_width = link_x; // Layout the cancel and OK buttons. gfx::Size save_ps = save_button_->GetPreferredSize(); gfx::Size dont_save_ps = dont_save_button_->GetPreferredSize(); // Layout the icon and label. AlertInfoBar::Layout(); int save_x = label()->bounds().right() + kEndOfLabelSpacing; save_x = std::max(0, std::min(save_x, available_width - (save_ps.width() + dont_save_ps.width() + kButtonButtonSpacing))); save_button_->SetVisible(true); dont_save_button_->SetVisible(true); save_button_->SetBounds(save_x, OffsetY(this, save_ps), save_ps.width(), save_ps.height()); int dont_save_x = save_x + save_ps.width() + kButtonButtonSpacing; dont_save_button_->SetBounds(dont_save_x, OffsetY(this, dont_save_ps), dont_save_ps.width(), dont_save_ps.height()); } void SaveCCInfoConfirmInfoBar::LinkActivated(views::Link* source, int event_flags) { DCHECK(source == link_); DCHECK(link_->IsVisible()); DCHECK(!link_->GetText().empty()); GetDelegate()->LinkClicked( event_utils::DispositionFromEventFlags(event_flags)); } void SaveCCInfoConfirmInfoBar::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { InfoBar::ViewHierarchyChanged(is_add, parent, child); if (is_add && child == this && !initialized_) { Init(); initialized_ = true; } } void SaveCCInfoConfirmInfoBar::ButtonPressed(views::Button* sender, const views::Event& event) { InfoBar::ButtonPressed(sender, event); if (sender == save_button_) { if (GetDelegate()->Accept()) RemoveInfoBar(); } else if (sender == dont_save_button_) { if (GetDelegate()->Cancel()) RemoveInfoBar(); } } int SaveCCInfoConfirmInfoBar::GetAvailableWidth() const { int buttons_area_size = save_button_->GetPreferredSize().width() + dont_save_button_->GetPreferredSize().width() + kButtonButtonSpacing + kEndOfLabelSpacing; return std::max(0, link_->x() - buttons_area_size); } void SaveCCInfoConfirmInfoBar::Init() { AddChildView(save_button_); AddChildView(dont_save_button_); AddChildView(link_); } views::TextButton* SaveCCInfoConfirmInfoBar::CreateTextButton( const std::wstring& text) { views::TextButton* text_button = new views::TextButton(this, std::wstring()); text_button->set_border(new InfoBarButtonBorder); // Set font colors for different states. text_button->SetEnabledColor(SK_ColorBLACK); text_button->SetHighlightColor(SK_ColorBLACK); text_button->SetHoverColor(SK_ColorBLACK); text_button->SetNormalHasBorder(true); // Set font then text, then size button to fit text. text_button->SetFont(ResourceBundle::GetSharedInstance().GetFont( ResourceBundle::MediumFont)); text_button->SetText(text); text_button->ClearMaxTextSize(); text_button->SizeToPreferredSize(); return text_button; } ConfirmInfoBarDelegate* SaveCCInfoConfirmInfoBar::GetDelegate() { return delegate()->AsConfirmInfoBarDelegate(); } InfoBar* CreateAutofillCcInfoBar(ConfirmInfoBarDelegate* delegate) { DCHECK(delegate); return new SaveCCInfoConfirmInfoBar(delegate); } <commit_msg>views: Use InfoBarTextButton in the Autofill credit card infobar.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_cc_infobar.h" #include "app/resource_bundle.h" #include "chrome/browser/views/event_utils.h" #include "chrome/browser/views/infobars/infobars.h" #include "chrome/browser/views/infobars/infobar_text_button.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "views/controls/button/text_button.h" #include "views/controls/link.h" class SaveCCInfoConfirmInfoBar : public AlertInfoBar, public views::LinkController { public: explicit SaveCCInfoConfirmInfoBar(ConfirmInfoBarDelegate* delegate); virtual ~SaveCCInfoConfirmInfoBar(); // Overridden from views::View: virtual void Layout(); // Overridden from views::LinkController: virtual void LinkActivated(views::Link* source, int event_flags); protected: // Overridden from views::View: virtual void ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child); // Overridden from views::ButtonListener: virtual void ButtonPressed(views::Button* sender, const views::Event& event); // Overridden from InfoBar: virtual int GetAvailableWidth() const; private: void Init(); ConfirmInfoBarDelegate* GetDelegate(); // The buttons are owned by InfoBar view from the moment they are added to its // hierarchy (Init() called), but we still need pointers to them to process // messages from them. InfoBarTextButton* save_button_; InfoBarTextButton* dont_save_button_; views::Link* link_; bool initialized_; DISALLOW_COPY_AND_ASSIGN(SaveCCInfoConfirmInfoBar); }; SaveCCInfoConfirmInfoBar::SaveCCInfoConfirmInfoBar( ConfirmInfoBarDelegate* delegate) : AlertInfoBar(delegate), initialized_(false) { save_button_ = InfoBarTextButton::Create(this, delegate->GetButtonLabel(ConfirmInfoBarDelegate::BUTTON_OK)); dont_save_button_ = InfoBarTextButton::Create(this, delegate->GetButtonLabel(ConfirmInfoBarDelegate::BUTTON_CANCEL)); // Set up the link. link_ = new views::Link; link_->SetText(delegate->GetLinkText()); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); link_->SetFont(rb.GetFont(ResourceBundle::MediumFont)); link_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); link_->SetController(this); link_->MakeReadableOverBackgroundColor(background()->get_color()); } SaveCCInfoConfirmInfoBar::~SaveCCInfoConfirmInfoBar() { if (!initialized_) { delete save_button_; delete dont_save_button_; delete link_; } } void SaveCCInfoConfirmInfoBar::Layout() { // Layout the close button. InfoBar::Layout(); int available_width = AlertInfoBar::GetAvailableWidth(); // Now append the link to the label's right edge. link_->SetVisible(!link_->GetText().empty()); gfx::Size link_ps = link_->GetPreferredSize(); int link_x = available_width - kButtonButtonSpacing - link_ps.width(); link_->SetBounds(link_x, OffsetY(this, link_ps), link_ps.width(), link_ps.height()); available_width = link_x; // Layout the cancel and OK buttons. gfx::Size save_ps = save_button_->GetPreferredSize(); gfx::Size dont_save_ps = dont_save_button_->GetPreferredSize(); // Layout the icon and label. AlertInfoBar::Layout(); int save_x = label()->bounds().right() + kEndOfLabelSpacing; save_x = std::max(0, std::min(save_x, available_width - (save_ps.width() + dont_save_ps.width() + kButtonButtonSpacing))); save_button_->SetVisible(true); dont_save_button_->SetVisible(true); save_button_->SetBounds(save_x, OffsetY(this, save_ps), save_ps.width(), save_ps.height()); int dont_save_x = save_x + save_ps.width() + kButtonButtonSpacing; dont_save_button_->SetBounds(dont_save_x, OffsetY(this, dont_save_ps), dont_save_ps.width(), dont_save_ps.height()); } void SaveCCInfoConfirmInfoBar::LinkActivated(views::Link* source, int event_flags) { DCHECK(source == link_); DCHECK(link_->IsVisible()); DCHECK(!link_->GetText().empty()); GetDelegate()->LinkClicked( event_utils::DispositionFromEventFlags(event_flags)); } void SaveCCInfoConfirmInfoBar::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { InfoBar::ViewHierarchyChanged(is_add, parent, child); if (is_add && child == this && !initialized_) { Init(); initialized_ = true; } } void SaveCCInfoConfirmInfoBar::ButtonPressed(views::Button* sender, const views::Event& event) { InfoBar::ButtonPressed(sender, event); if (sender == save_button_) { if (GetDelegate()->Accept()) RemoveInfoBar(); } else if (sender == dont_save_button_) { if (GetDelegate()->Cancel()) RemoveInfoBar(); } } int SaveCCInfoConfirmInfoBar::GetAvailableWidth() const { int buttons_area_size = save_button_->GetPreferredSize().width() + dont_save_button_->GetPreferredSize().width() + kButtonButtonSpacing + kEndOfLabelSpacing; return std::max(0, link_->x() - buttons_area_size); } void SaveCCInfoConfirmInfoBar::Init() { AddChildView(save_button_); AddChildView(dont_save_button_); AddChildView(link_); } ConfirmInfoBarDelegate* SaveCCInfoConfirmInfoBar::GetDelegate() { return delegate()->AsConfirmInfoBarDelegate(); } InfoBar* CreateAutofillCcInfoBar(ConfirmInfoBarDelegate* delegate) { DCHECK(delegate); return new SaveCCInfoConfirmInfoBar(delegate); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/path_service.h" #include "base/string_util.h" #include "chrome/browser/extensions/extensions_ui.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/json_value_serializer.h" #include "testing/gtest/include/gtest/gtest.h" namespace { static DictionaryValue* DeserializeJSONTestData(const FilePath& path, std::string *error) { Value* value; JSONFileValueSerializer serializer(path); value = serializer.Deserialize(error); return static_cast<DictionaryValue*>(value); } static bool CompareExpectedAndActualOutput( const FilePath& extension_path, const std::vector<ExtensionPage>& pages, const FilePath& expected_output_path) { // TODO(rafaelw): Using the extension_path passed in above, causes this // unit test to fail on linux. The Values come back valid, but the // UserScript.path() values return "". #if defined(OS_WIN) FilePath path(FILE_PATH_LITERAL("c:\\foo")); #elif defined(OS_POSIX) FilePath path(FILE_PATH_LITERAL("/foo")); #endif Extension extension(path); std::string error; FilePath manifest_path = extension_path.AppendASCII( Extension::kManifestFilename); scoped_ptr<DictionaryValue> extension_data(DeserializeJSONTestData( manifest_path, &error)); EXPECT_EQ("", error); EXPECT_TRUE(extension.InitFromValue(*extension_data, true, &error)); EXPECT_EQ("", error); scoped_ptr<DictionaryValue>expected_output_data(DeserializeJSONTestData( expected_output_path, &error)); EXPECT_EQ("", error); // Produce test output. scoped_ptr<DictionaryValue> actual_output_data( ExtensionsDOMHandler::CreateExtensionDetailValue(&extension, pages)); // Compare the outputs. return expected_output_data->Equals(actual_output_data.get()); } } // namespace class ExtensionUITest : public testing::Test { }; TEST(ExtensionUITest, GenerateExtensionsJSONData) { FilePath data_test_dir_path, extension_path, expected_output_path; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_test_dir_path)); // Test Extension1 extension_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); std::vector<ExtensionPage> pages; pages.push_back(ExtensionPage( GURL("chrome-extension://behllobkkfkfnphdnhnkndlbkcpglgmj/bar.html"), 42, 88)); pages.push_back(ExtensionPage( GURL("chrome-extension://behllobkkfkfnphdnhnkndlbkcpglgmj/dog.html"), 0, 0)); expected_output_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("ui") .AppendASCII("create_extension_detail_value_expected_output") .AppendASCII("good-extension1.json"); EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages, expected_output_path)) << extension_path.value(); // Test Extension2 extension_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("hpiknbiabeeppbpihjehijgoemciehgk") .AppendASCII("2"); expected_output_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("ui") .AppendASCII("create_extension_detail_value_expected_output") .AppendASCII("good-extension2.json"); // It's OK to have duplicate URLs, so long as the IDs are different. pages[1].url = pages[0].url; EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages, expected_output_path)) << extension_path.value(); // Test Extension3 extension_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"); expected_output_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("ui") .AppendASCII("create_extension_detail_value_expected_output") .AppendASCII("good-extension3.json"); pages.clear(); EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages, expected_output_path)) << extension_path.value(); } <commit_msg>Fix unit_test breakage from http://codereview.chromium.org/140018<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/path_service.h" #include "base/string_util.h" #include "chrome/browser/extensions/extensions_ui.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/json_value_serializer.h" #include "testing/gtest/include/gtest/gtest.h" namespace { static DictionaryValue* DeserializeJSONTestData(const FilePath& path, std::string *error) { Value* value; JSONFileValueSerializer serializer(path); value = serializer.Deserialize(error); return static_cast<DictionaryValue*>(value); } static bool CompareExpectedAndActualOutput( const FilePath& extension_path, const std::vector<ExtensionPage>& pages, const FilePath& expected_output_path) { // TODO(rafaelw): Using the extension_path passed in above, causes this // unit test to fail on linux. The Values come back valid, but the // UserScript.path() values return "". #if defined(OS_WIN) FilePath path(FILE_PATH_LITERAL("c:\\foo")); #elif defined(OS_POSIX) FilePath path(FILE_PATH_LITERAL("/foo")); #endif Extension extension(path); std::string error; FilePath manifest_path = extension_path.AppendASCII( Extension::kManifestFilename); scoped_ptr<DictionaryValue> extension_data(DeserializeJSONTestData( manifest_path, &error)); EXPECT_EQ("", error); EXPECT_TRUE(extension.InitFromValue(*extension_data, true, &error)); EXPECT_EQ("", error); scoped_ptr<DictionaryValue>expected_output_data(DeserializeJSONTestData( expected_output_path, &error)); EXPECT_EQ("", error); // Produce test output. scoped_ptr<DictionaryValue> actual_output_data( ExtensionsDOMHandler::CreateExtensionDetailValue(&extension, pages)); // Compare the outputs. return expected_output_data->Equals(actual_output_data.get()); } } // namespace class ExtensionUITest : public testing::Test { }; TEST(ExtensionUITest, GenerateExtensionsJSONData) { FilePath data_test_dir_path, extension_path, expected_output_path; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_test_dir_path)); // Test Extension1 extension_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); std::vector<ExtensionPage> pages; pages.push_back(ExtensionPage( GURL("chrome-extension://behllobkkfkfnphdnhnkndlbkcpglgmj/bar.html"), 42, 88)); pages.push_back(ExtensionPage( GURL("chrome-extension://behllobkkfkfnphdnhnkndlbkcpglgmj/dog.html"), 0, 0)); expected_output_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("ui") .AppendASCII("create_extension_detail_value_expected_output") .AppendASCII("good-extension1.json"); EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages, expected_output_path)) << extension_path.value(); // Test Extension2 extension_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("hpiknbiabeeppbpihjehijgoemciehgk") .AppendASCII("2"); expected_output_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("ui") .AppendASCII("create_extension_detail_value_expected_output") .AppendASCII("good-extension2.json"); // It's OK to have duplicate URLs, so long as the IDs are different. pages[1].url = pages[0].url; EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages, expected_output_path)) << extension_path.value(); // Test Extension3 extension_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"); expected_output_path = data_test_dir_path.AppendASCII("extensions") .AppendASCII("ui") .AppendASCII("create_extension_detail_value_expected_output") .AppendASCII("good-extension3.json"); pages.clear(); EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages, expected_output_path)) << extension_path.value(); } <|endoftext|>
<commit_before>/* Q Light Controller mastertimer.cpp Copyright (C) Heikki Junnila This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The license is in the file "COPYING". You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <QDebug> #include <QMutexLocker> #if defined(WIN32) || defined(Q_OS_WIN) # include "mastertimer-win32.h" #else # include <unistd.h> # include "mastertimer-unix.h" #endif #include "universearray.h" #include "genericfader.h" #include "mastertimer.h" #include "outputmap.h" #include "dmxsource.h" #include "qlcmacros.h" #include "function.h" #include "doc.h" #define MASTERTIMER_FREQUENCY "mastertimer/frequency" /** The timer tick frequency in Hertz */ uint MasterTimer::s_frequency = 50; uint MasterTimer::s_tick = 20; /***************************************************************************** * Initialization *****************************************************************************/ MasterTimer::MasterTimer(Doc* doc) : QObject(doc) , m_stopAllFunctions(false) , m_fadeAllSequence(false) , m_fadeSequenceTimeout(0) , m_fadeSequenceTimeoutCount(0) , m_originalGMvalue(0) , m_fader(new GenericFader(doc)) , d_ptr(new MasterTimerPrivate(this)) { Q_ASSERT(doc != NULL); Q_ASSERT(d_ptr != NULL); QSettings settings; QVariant var = settings.value(MASTERTIMER_FREQUENCY); if (var.isValid() == true) s_frequency = var.toUInt(); s_tick = uint(double(1000) / double(s_frequency)); } MasterTimer::~MasterTimer() { if (d_ptr->isRunning() == true) stop(); delete d_ptr; d_ptr = NULL; } void MasterTimer::start() { Q_ASSERT(d_ptr != NULL); d_ptr->start(); } void MasterTimer::stop() { Q_ASSERT(d_ptr != NULL); stopAllFunctions(); d_ptr->stop(); } void MasterTimer::timerTick() { Doc* doc = qobject_cast<Doc*> (parent()); Q_ASSERT(doc != NULL); UniverseArray* universes = doc->outputMap()->claimUniverses(); universes->zeroIntensityChannels(); if (m_fadeAllSequence == true) { m_fadeSequenceTimeoutCount -= tick(); uchar newGMvalue = ((float)m_fadeSequenceTimeoutCount / (float)m_fadeSequenceTimeout) * m_originalGMvalue; //qDebug() << "---> setting GM to" << newGMvalue << "timeout:" << m_fadeSequenceTimeoutCount; universes->setGMValue(newGMvalue); if (m_fadeSequenceTimeoutCount <= 0) { m_fadeAllSequence = false; m_stopAllFunctions = true; } } timerTickFunctions(universes); timerTickDMXSources(universes); timerTickFader(universes); doc->outputMap()->releaseUniverses(); doc->outputMap()->dumpUniverses(); } uint MasterTimer::frequency() { return s_frequency; } uint MasterTimer::tick() { return s_tick; } /***************************************************************************** * Functions *****************************************************************************/ void MasterTimer::startFunction(Function* function) { if (function == NULL) return; QMutexLocker locker(&m_functionListMutex); if (m_startQueue.contains(function) == false) m_startQueue.append(function); } void MasterTimer::stopAllFunctions() { m_stopAllFunctions = true; /* Wait until all functions have been stopped */ while (runningFunctions() > 0) { #if defined(WIN32) || defined(Q_OS_WIN) Sleep(10); #else usleep(10000); #endif } /* Remove all generic fader's channels */ m_functionListMutex.lock(); m_dmxSourceListMutex.lock(); fader()->removeAll(); m_dmxSourceListMutex.unlock(); m_functionListMutex.unlock(); if (m_originalGMvalue != 0) { Doc* doc = qobject_cast<Doc*> (parent()); Q_ASSERT(doc != NULL); UniverseArray* universes = doc->outputMap()->claimUniverses(); universes->setGMValue(m_originalGMvalue); doc->outputMap()->releaseUniverses(); m_originalGMvalue = 0; } m_stopAllFunctions = false; } void MasterTimer::fadeAndStopAll(int timeout) { if (timeout == 0) return; Doc* doc = qobject_cast<Doc*> (parent()); Q_ASSERT(doc != NULL); UniverseArray* universes = doc->outputMap()->claimUniverses(); m_originalGMvalue = universes->gMValue(); doc->outputMap()->releaseUniverses(); m_fadeSequenceTimeout = timeout; m_fadeSequenceTimeoutCount = timeout; m_fadeAllSequence = true; } int MasterTimer::runningFunctions() const { return m_functionList.size(); } void MasterTimer::timerTickFunctions(UniverseArray* universes) { // List of m_functionList indices that should be removed at the end of this // function. The functions at the indices have been stopped. QList <int> removeList; /* Lock before accessing the running functions list. */ m_functionListMutex.lock(); for (int i = 0; i < m_functionList.size(); i++) { Function* function = m_functionList.at(i); /* No need to access function list on this round anymore */ m_functionListMutex.unlock(); if (function != NULL) { /* Run the function unless it's supposed to be stopped */ if (function->stopped() == false && m_stopAllFunctions == false) function->write(this, universes); if (function->stopped() == true || m_stopAllFunctions == true) { /* Function should be stopped instead */ m_functionListMutex.lock(); function->postRun(this, universes); //qDebug() << "[MasterTimer] Add function (ID: " << function->id() << ") to remove list "; removeList << i; // Don't remove the item from the list just yet. m_functionListMutex.unlock(); emit functionListChanged(); } } /* Lock function list for the next round. */ m_functionListMutex.lock(); } // Remove functions that need to be removed AFTER all functions have been run // for this round. This is done separately to prevent a case when a function // is first removed and then another is added (chaser, for example), keeping the // list's size the same, thus preventing the last added function from being run // on this round. The indices in removeList are automatically sorted because the // list is iterated with an int above from 0 to size, so iterating the removeList // backwards here will always remove the correct indices. QListIterator <int> it(removeList); it.toBack(); while (it.hasPrevious() == true) m_functionList.removeAt(it.previous()); /* No more functions. Get out and wait for next timer event. */ m_functionListMutex.unlock(); foreach (Function* f, m_startQueue) { //qDebug() << "[MasterTimer] Processing ID: " << f->id(); if (m_functionList.contains(f) == false) { m_functionListMutex.lock(); m_functionList.append(f); m_functionListMutex.unlock(); //qDebug() << "[MasterTimer] Starting up ID: " << f->id(); f->preRun(this); f->write(this, universes); emit functionListChanged(); } m_startQueue.removeOne(f); } } void MasterTimer::fadeSequenceCompleted() { } /**************************************************************************** * DMX Sources ****************************************************************************/ void MasterTimer::registerDMXSource(DMXSource* source) { Q_ASSERT(source != NULL); m_dmxSourceListMutex.lock(); if (m_dmxSourceList.contains(source) == false) m_dmxSourceList.append(source); m_dmxSourceListMutex.unlock(); } void MasterTimer::unregisterDMXSource(DMXSource* source) { Q_ASSERT(source != NULL); m_dmxSourceListMutex.lock(); m_dmxSourceList.removeAll(source); m_dmxSourceListMutex.unlock(); } void MasterTimer::timerTickDMXSources(UniverseArray* universes) { /* Lock before accessing the running functions list. */ m_dmxSourceListMutex.lock(); for (int i = 0; i < m_dmxSourceList.size(); i++) { DMXSource* source = m_dmxSourceList.at(i); Q_ASSERT(source != NULL); /* No need to access the list on this round anymore. */ m_dmxSourceListMutex.unlock(); /* Get DMX data from the source */ source->writeDMX(this, universes); /* Lock for the next round. */ m_dmxSourceListMutex.lock(); } /* No more sources. Get out and wait for next timer event. */ m_dmxSourceListMutex.unlock(); } /**************************************************************************** * Generic Fader ****************************************************************************/ GenericFader* MasterTimer::fader() const { return m_fader; } void MasterTimer::timerTickFader(UniverseArray* universes) { m_functionListMutex.lock(); m_dmxSourceListMutex.lock(); fader()->write(universes); m_dmxSourceListMutex.unlock(); m_functionListMutex.unlock(); } <commit_msg>Even more locking improvements<commit_after>/* Q Light Controller mastertimer.cpp Copyright (C) Heikki Junnila This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The license is in the file "COPYING". You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <QDebug> #include <QMutexLocker> #if defined(WIN32) || defined(Q_OS_WIN) # include "mastertimer-win32.h" #else # include <unistd.h> # include "mastertimer-unix.h" #endif #include "universearray.h" #include "genericfader.h" #include "mastertimer.h" #include "outputmap.h" #include "dmxsource.h" #include "qlcmacros.h" #include "function.h" #include "doc.h" #define MASTERTIMER_FREQUENCY "mastertimer/frequency" /** The timer tick frequency in Hertz */ uint MasterTimer::s_frequency = 50; uint MasterTimer::s_tick = 20; /***************************************************************************** * Initialization *****************************************************************************/ MasterTimer::MasterTimer(Doc* doc) : QObject(doc) , m_stopAllFunctions(false) , m_fadeAllSequence(false) , m_fadeSequenceTimeout(0) , m_fadeSequenceTimeoutCount(0) , m_originalGMvalue(0) , m_fader(new GenericFader(doc)) , d_ptr(new MasterTimerPrivate(this)) { Q_ASSERT(doc != NULL); Q_ASSERT(d_ptr != NULL); QSettings settings; QVariant var = settings.value(MASTERTIMER_FREQUENCY); if (var.isValid() == true) s_frequency = var.toUInt(); s_tick = uint(double(1000) / double(s_frequency)); } MasterTimer::~MasterTimer() { if (d_ptr->isRunning() == true) stop(); delete d_ptr; d_ptr = NULL; } void MasterTimer::start() { Q_ASSERT(d_ptr != NULL); d_ptr->start(); } void MasterTimer::stop() { Q_ASSERT(d_ptr != NULL); stopAllFunctions(); d_ptr->stop(); } void MasterTimer::timerTick() { Doc* doc = qobject_cast<Doc*> (parent()); Q_ASSERT(doc != NULL); UniverseArray* universes = doc->outputMap()->claimUniverses(); universes->zeroIntensityChannels(); if (m_fadeAllSequence == true) { m_fadeSequenceTimeoutCount -= tick(); uchar newGMvalue = ((float)m_fadeSequenceTimeoutCount / (float)m_fadeSequenceTimeout) * m_originalGMvalue; //qDebug() << "---> setting GM to" << newGMvalue << "timeout:" << m_fadeSequenceTimeoutCount; universes->setGMValue(newGMvalue); if (m_fadeSequenceTimeoutCount <= 0) { m_fadeAllSequence = false; m_stopAllFunctions = true; } } timerTickFunctions(universes); timerTickDMXSources(universes); timerTickFader(universes); doc->outputMap()->releaseUniverses(); doc->outputMap()->dumpUniverses(); } uint MasterTimer::frequency() { return s_frequency; } uint MasterTimer::tick() { return s_tick; } /***************************************************************************** * Functions *****************************************************************************/ void MasterTimer::startFunction(Function* function) { if (function == NULL) return; QMutexLocker locker(&m_functionListMutex); if (m_startQueue.contains(function) == false) m_startQueue.append(function); } void MasterTimer::stopAllFunctions() { m_stopAllFunctions = true; /* Wait until all functions have been stopped */ while (runningFunctions() > 0) { #if defined(WIN32) || defined(Q_OS_WIN) Sleep(10); #else usleep(10000); #endif } { /* Remove all generic fader's channels */ QMutexLocker functionLocker(&m_functionListMutex); QMutexLocker dmxLocker(&m_dmxSourceListMutex); fader()->removeAll(); } if (m_originalGMvalue != 0) { Doc* doc = qobject_cast<Doc*> (parent()); Q_ASSERT(doc != NULL); UniverseArray* universes = doc->outputMap()->claimUniverses(); universes->setGMValue(m_originalGMvalue); doc->outputMap()->releaseUniverses(); m_originalGMvalue = 0; } m_stopAllFunctions = false; } void MasterTimer::fadeAndStopAll(int timeout) { if (timeout == 0) return; Doc* doc = qobject_cast<Doc*> (parent()); Q_ASSERT(doc != NULL); UniverseArray* universes = doc->outputMap()->claimUniverses(); m_originalGMvalue = universes->gMValue(); doc->outputMap()->releaseUniverses(); m_fadeSequenceTimeout = timeout; m_fadeSequenceTimeoutCount = timeout; m_fadeAllSequence = true; } int MasterTimer::runningFunctions() const { return m_functionList.size(); } void MasterTimer::timerTickFunctions(UniverseArray* universes) { // List of m_functionList indices that should be removed at the end of this // function. The functions at the indices have been stopped. QList <int> removeList; /* Lock before accessing the running functions list. */ m_functionListMutex.lock(); for (int i = 0; i < m_functionList.size(); i++) { Function* function = m_functionList.at(i); /* No need to access function list on this round anymore */ m_functionListMutex.unlock(); if (function != NULL) { /* Run the function unless it's supposed to be stopped */ if (function->stopped() == false && m_stopAllFunctions == false) { function->write(this, universes); } else { /* Function should be stopped instead */ m_functionListMutex.lock(); function->postRun(this, universes); //qDebug() << "[MasterTimer] Add function (ID: " << function->id() << ") to remove list "; removeList << i; // Don't remove the item from the list just yet. m_functionListMutex.unlock(); emit functionListChanged(); } } /* Lock function list for the next round. */ m_functionListMutex.lock(); } // Remove functions that need to be removed AFTER all functions have been run // for this round. This is done separately to prevent a case when a function // is first removed and then another is added (chaser, for example), keeping the // list's size the same, thus preventing the last added function from being run // on this round. The indices in removeList are automatically sorted because the // list is iterated with an int above from 0 to size, so iterating the removeList // backwards here will always remove the correct indices. QListIterator <int> it(removeList); it.toBack(); while (it.hasPrevious() == true) m_functionList.removeAt(it.previous()); foreach (Function* f, m_startQueue) { //qDebug() << "[MasterTimer] Processing ID: " << f->id(); if (m_functionList.contains(f) == false) { m_functionList.append(f); m_functionListMutex.unlock(); //qDebug() << "[MasterTimer] Starting up ID: " << f->id(); f->preRun(this); f->write(this, universes); emit functionListChanged(); m_functionListMutex.lock(); } m_startQueue.removeOne(f); } /* No more functions. Get out and wait for next timer event. */ m_functionListMutex.unlock(); } void MasterTimer::fadeSequenceCompleted() { } /**************************************************************************** * DMX Sources ****************************************************************************/ void MasterTimer::registerDMXSource(DMXSource* source) { Q_ASSERT(source != NULL); QMutexLocker lock(&m_dmxSourceListMutex); if (m_dmxSourceList.contains(source) == false) m_dmxSourceList.append(source); } void MasterTimer::unregisterDMXSource(DMXSource* source) { Q_ASSERT(source != NULL); QMutexLocker lock(&m_dmxSourceListMutex); m_dmxSourceList.removeAll(source); } void MasterTimer::timerTickDMXSources(UniverseArray* universes) { /* Lock before accessing the DMX sources list. */ m_dmxSourceListMutex.lock(); for (int i = 0; i < m_dmxSourceList.size(); i++) { DMXSource* source = m_dmxSourceList.at(i); Q_ASSERT(source != NULL); /* No need to access the list on this round anymore. */ m_dmxSourceListMutex.unlock(); /* Get DMX data from the source */ source->writeDMX(this, universes); /* Lock for the next round. */ m_dmxSourceListMutex.lock(); } /* No more sources. Get out and wait for next timer event. */ m_dmxSourceListMutex.unlock(); } /**************************************************************************** * Generic Fader ****************************************************************************/ GenericFader* MasterTimer::fader() const { return m_fader; } void MasterTimer::timerTickFader(UniverseArray* universes) { QMutexLocker functionLocker(&m_functionListMutex); QMutexLocker dmxLOcker(&m_dmxSourceListMutex); fader()->write(universes); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtk/gtk.h> #include "base/string_util.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profile.h" #include "chrome/browser/gtk/bookmark_editor_gtk.h" #include "chrome/browser/gtk/bookmark_tree_model.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; using bookmark_utils::GetTitleFromTreeIter; // Base class for bookmark editor tests. This class is a copy from // bookmark_editor_view_unittest.cc, and all the tests in this file are // GTK-ifications of the corresponding views tests. Testing here is really // important because on Linux, we make round trip copies from chrome's // BookmarkModel class to GTK's native GtkTreeStore. class BookmarkEditorGtkTest : public testing::Test { public: BookmarkEditorGtkTest() : model_(NULL) { } virtual void SetUp() { profile_.reset(new TestingProfile()); profile_->set_has_history_service(true); profile_->CreateBookmarkModel(true); model_ = profile_->GetBookmarkModel(); AddTestData(); } virtual void TearDown() { } protected: MessageLoopForUI message_loop_; BookmarkModel* model_; scoped_ptr<TestingProfile> profile_; std::string base_path() const { return "file:///c:/tmp/"; } BookmarkNode* GetNode(const std::string& name) { return model_->GetMostRecentlyAddedNodeForURL(GURL(base_path() + name)); } private: // Creates the following structure: // bookmark bar node // a // F1 // f1a // F11 // f11a // F2 // other node // oa // OF1 // of1a void AddTestData() { std::string test_base = base_path(); model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a", GURL(test_base + "a")); BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1"); model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a")); BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11"); model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a")); model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2"); // Children of the other node. model_->AddURL(model_->other_node(), 0, L"oa", GURL(test_base + "oa")); BookmarkNode* of1 = model_->AddGroup(model_->other_node(), 1, L"OF1"); model_->AddURL(of1, 0, L"of1a", GURL(test_base + "of1a")); } }; // Makes sure the tree model matches that of the bookmark bar model. // Disabled: See crbug.com/15436 TEST_F(BookmarkEditorGtkTest, DISABLED_ModelsMatch) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL, BookmarkEditor::SHOW_TREE, NULL); // The root should have two children, one for the bookmark bar node, // the other for the 'other bookmarks' folder. GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); GtkTreeIter toplevel; ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &toplevel)); GtkTreeIter bookmark_bar_node = toplevel; ASSERT_TRUE(gtk_tree_model_iter_next(store, &toplevel)); GtkTreeIter other_node = toplevel; ASSERT_FALSE(gtk_tree_model_iter_next(store, &toplevel)); // The bookmark bar should have 2 nodes: folder F1 and F2. GtkTreeIter f1_iter; GtkTreeIter child; ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node)); ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &bookmark_bar_node)); f1_iter = child; ASSERT_EQ(L"F1", GetTitleFromTreeIter(store, &child)); ASSERT_TRUE(gtk_tree_model_iter_next(store, &child)); ASSERT_EQ(L"F2", GetTitleFromTreeIter(store, &child)); ASSERT_FALSE(gtk_tree_model_iter_next(store, &child)); // F1 should have one child, F11 ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f1_iter)); ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &f1_iter)); ASSERT_EQ(L"F11", GetTitleFromTreeIter(store, &child)); ASSERT_FALSE(gtk_tree_model_iter_next(store, &child)); // Other node should have one child (OF1). ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &other_node)); ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &other_node)); ASSERT_EQ(L"OF1", GetTitleFromTreeIter(store, &child)); ASSERT_FALSE(gtk_tree_model_iter_next(store, &child)); } // Changes the title and makes sure parent/visual order doesn't change. TEST_F(BookmarkEditorGtkTest, EditTitleKeepsPosition) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a"); GtkTreeIter bookmark_bar_node; GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node)); editor.ApplyEdits(&bookmark_bar_node); BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode(); ASSERT_EQ(L"new_a", bb_node->GetChild(0)->GetTitle()); // The URL shouldn't have changed. ASSERT_TRUE(GURL(base_path() + "a") == bb_node->GetChild(0)->GetURL()); } // Changes the url and makes sure parent/visual order doesn't change. TEST_F(BookmarkEditorGtkTest, EditURLKeepsPosition) { Time node_time = Time::Now() + TimeDelta::FromDays(2); GetNode("a")->date_added_ = node_time; BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.url_entry_), GURL(base_path() + "new_a").spec().c_str()); GtkTreeIter bookmark_bar_node; GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node)); editor.ApplyEdits(&bookmark_bar_node); BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode(); ASSERT_EQ(L"a", bb_node->GetChild(0)->GetTitle()); // The URL should have changed. ASSERT_TRUE(GURL(base_path() + "new_a") == bb_node->GetChild(0)->GetURL()); ASSERT_TRUE(node_time == bb_node->GetChild(0)->date_added()); } // Moves 'a' to be a child of the other node. TEST_F(BookmarkEditorGtkTest, ChangeParent) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); GtkTreeIter gtk_other_node; ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &gtk_other_node)); ASSERT_TRUE(gtk_tree_model_iter_next(store, &gtk_other_node)); editor.ApplyEdits(&gtk_other_node); BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node(); ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle()); ASSERT_TRUE(GURL(base_path() + "a") == other_node->GetChild(2)->GetURL()); } // Moves 'a' to be a child of the other node. // Moves 'a' to be a child of the other node and changes its url to new_a. TEST_F(BookmarkEditorGtkTest, ChangeParentAndURL) { Time node_time = Time::Now() + TimeDelta::FromDays(2); GetNode("a")->date_added_ = node_time; BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.url_entry_), GURL(base_path() + "new_a").spec().c_str()); GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); GtkTreeIter gtk_other_node; ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &gtk_other_node)); ASSERT_TRUE(gtk_tree_model_iter_next(store, &gtk_other_node)); editor.ApplyEdits(&gtk_other_node); BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node(); ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle()); ASSERT_TRUE(GURL(base_path() + "new_a") == other_node->GetChild(2)->GetURL()); ASSERT_TRUE(node_time == other_node->GetChild(2)->date_added()); } // Creates a new folder and moves a node to it. TEST_F(BookmarkEditorGtkTest, MoveToNewParent) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); GtkTreeIter bookmark_bar_node; GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node)); // The bookmark bar should have 2 nodes: folder F1 and F2. GtkTreeIter f2_iter; ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node)); ASSERT_TRUE(gtk_tree_model_iter_children(store, &f2_iter, &bookmark_bar_node)); ASSERT_TRUE(gtk_tree_model_iter_next(store, &f2_iter)); // Create two nodes: "F21" as a child of "F2" and "F211" as a child of "F21". GtkTreeIter f21_iter; editor.AddNewGroup(&f2_iter, &f21_iter); gtk_tree_store_set(editor.tree_store_, &f21_iter, bookmark_utils::FOLDER_NAME, "F21", -1); GtkTreeIter f211_iter; editor.AddNewGroup(&f21_iter, &f211_iter); gtk_tree_store_set(editor.tree_store_, &f211_iter, bookmark_utils::FOLDER_NAME, "F211", -1); ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f2_iter)); editor.ApplyEdits(&f2_iter); BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode(); BookmarkNode* mf2 = bb_node->GetChild(1); // F2 in the model should have two children now: F21 and the node edited. ASSERT_EQ(2, mf2->GetChildCount()); // F21 should be first. ASSERT_EQ(L"F21", mf2->GetChild(0)->GetTitle()); // Then a. ASSERT_EQ(L"a", mf2->GetChild(1)->GetTitle()); // F21 should have one child, F211. BookmarkNode* mf21 = mf2->GetChild(0); ASSERT_EQ(1, mf21->GetChildCount()); ASSERT_EQ(L"F211", mf21->GetChild(0)->GetTitle()); } // Brings up the editor, creating a new URL on the bookmark bar. TEST_F(BookmarkEditorGtkTest, NewURL) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL, BookmarkEditor::SHOW_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.url_entry_), GURL(base_path() + "a").spec().c_str()); gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a"); GtkTreeIter bookmark_bar_node; GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node)); editor.ApplyEdits(&bookmark_bar_node); BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode(); ASSERT_EQ(4, bb_node->GetChildCount()); BookmarkNode* new_node = bb_node->GetChild(3); EXPECT_EQ(L"new_a", new_node->GetTitle()); EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL()); } // Brings up the editor with no tree and modifies the url. TEST_F(BookmarkEditorGtkTest, ChangeURLNoTree) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, model_->other_node()->GetChild(0), BookmarkEditor::NO_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.url_entry_), GURL(base_path() + "a").spec().c_str()); gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a"); editor.ApplyEdits(NULL); BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node(); ASSERT_EQ(2, other_node->GetChildCount()); BookmarkNode* new_node = other_node->GetChild(0); EXPECT_EQ(L"new_a", new_node->GetTitle()); EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL()); } // Brings up the editor with no tree and modifies only the title. TEST_F(BookmarkEditorGtkTest, ChangeTitleNoTree) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, model_->other_node()->GetChild(0), BookmarkEditor::NO_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a"); editor.ApplyEdits(); BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node(); ASSERT_EQ(2, other_node->GetChildCount()); BookmarkNode* new_node = other_node->GetChild(0); EXPECT_EQ(L"new_a", new_node->GetTitle()); } <commit_msg>Fix breakage<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtk/gtk.h> #include "base/string_util.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profile.h" #include "chrome/browser/gtk/bookmark_editor_gtk.h" #include "chrome/browser/gtk/bookmark_tree_model.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; using bookmark_utils::GetTitleFromTreeIter; // Base class for bookmark editor tests. This class is a copy from // bookmark_editor_view_unittest.cc, and all the tests in this file are // GTK-ifications of the corresponding views tests. Testing here is really // important because on Linux, we make round trip copies from chrome's // BookmarkModel class to GTK's native GtkTreeStore. class BookmarkEditorGtkTest : public testing::Test { public: BookmarkEditorGtkTest() : model_(NULL) { } virtual void SetUp() { profile_.reset(new TestingProfile()); profile_->set_has_history_service(true); profile_->CreateBookmarkModel(true); model_ = profile_->GetBookmarkModel(); AddTestData(); } virtual void TearDown() { } protected: MessageLoopForUI message_loop_; BookmarkModel* model_; scoped_ptr<TestingProfile> profile_; std::string base_path() const { return "file:///c:/tmp/"; } BookmarkNode* GetNode(const std::string& name) { return model_->GetMostRecentlyAddedNodeForURL(GURL(base_path() + name)); } private: // Creates the following structure: // bookmark bar node // a // F1 // f1a // F11 // f11a // F2 // other node // oa // OF1 // of1a void AddTestData() { std::string test_base = base_path(); model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a", GURL(test_base + "a")); BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1"); model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a")); BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11"); model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a")); model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2"); // Children of the other node. model_->AddURL(model_->other_node(), 0, L"oa", GURL(test_base + "oa")); BookmarkNode* of1 = model_->AddGroup(model_->other_node(), 1, L"OF1"); model_->AddURL(of1, 0, L"of1a", GURL(test_base + "of1a")); } }; // Makes sure the tree model matches that of the bookmark bar model. // Disabled: See crbug.com/15436 #if 0 TEST_F(BookmarkEditorGtkTest, ModelsMatch) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL, BookmarkEditor::SHOW_TREE, NULL); // The root should have two children, one for the bookmark bar node, // the other for the 'other bookmarks' folder. GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); GtkTreeIter toplevel; ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &toplevel)); GtkTreeIter bookmark_bar_node = toplevel; ASSERT_TRUE(gtk_tree_model_iter_next(store, &toplevel)); GtkTreeIter other_node = toplevel; ASSERT_FALSE(gtk_tree_model_iter_next(store, &toplevel)); // The bookmark bar should have 2 nodes: folder F1 and F2. GtkTreeIter f1_iter; GtkTreeIter child; ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node)); ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &bookmark_bar_node)); f1_iter = child; ASSERT_EQ(L"F1", GetTitleFromTreeIter(store, &child)); ASSERT_TRUE(gtk_tree_model_iter_next(store, &child)); ASSERT_EQ(L"F2", GetTitleFromTreeIter(store, &child)); ASSERT_FALSE(gtk_tree_model_iter_next(store, &child)); // F1 should have one child, F11 ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f1_iter)); ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &f1_iter)); ASSERT_EQ(L"F11", GetTitleFromTreeIter(store, &child)); ASSERT_FALSE(gtk_tree_model_iter_next(store, &child)); // Other node should have one child (OF1). ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &other_node)); ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &other_node)); ASSERT_EQ(L"OF1", GetTitleFromTreeIter(store, &child)); ASSERT_FALSE(gtk_tree_model_iter_next(store, &child)); } #endif // Changes the title and makes sure parent/visual order doesn't change. TEST_F(BookmarkEditorGtkTest, EditTitleKeepsPosition) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a"); GtkTreeIter bookmark_bar_node; GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node)); editor.ApplyEdits(&bookmark_bar_node); BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode(); ASSERT_EQ(L"new_a", bb_node->GetChild(0)->GetTitle()); // The URL shouldn't have changed. ASSERT_TRUE(GURL(base_path() + "a") == bb_node->GetChild(0)->GetURL()); } // Changes the url and makes sure parent/visual order doesn't change. TEST_F(BookmarkEditorGtkTest, EditURLKeepsPosition) { Time node_time = Time::Now() + TimeDelta::FromDays(2); GetNode("a")->date_added_ = node_time; BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.url_entry_), GURL(base_path() + "new_a").spec().c_str()); GtkTreeIter bookmark_bar_node; GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node)); editor.ApplyEdits(&bookmark_bar_node); BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode(); ASSERT_EQ(L"a", bb_node->GetChild(0)->GetTitle()); // The URL should have changed. ASSERT_TRUE(GURL(base_path() + "new_a") == bb_node->GetChild(0)->GetURL()); ASSERT_TRUE(node_time == bb_node->GetChild(0)->date_added()); } // Moves 'a' to be a child of the other node. TEST_F(BookmarkEditorGtkTest, ChangeParent) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); GtkTreeIter gtk_other_node; ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &gtk_other_node)); ASSERT_TRUE(gtk_tree_model_iter_next(store, &gtk_other_node)); editor.ApplyEdits(&gtk_other_node); BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node(); ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle()); ASSERT_TRUE(GURL(base_path() + "a") == other_node->GetChild(2)->GetURL()); } // Moves 'a' to be a child of the other node. // Moves 'a' to be a child of the other node and changes its url to new_a. TEST_F(BookmarkEditorGtkTest, ChangeParentAndURL) { Time node_time = Time::Now() + TimeDelta::FromDays(2); GetNode("a")->date_added_ = node_time; BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.url_entry_), GURL(base_path() + "new_a").spec().c_str()); GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); GtkTreeIter gtk_other_node; ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &gtk_other_node)); ASSERT_TRUE(gtk_tree_model_iter_next(store, &gtk_other_node)); editor.ApplyEdits(&gtk_other_node); BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node(); ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle()); ASSERT_TRUE(GURL(base_path() + "new_a") == other_node->GetChild(2)->GetURL()); ASSERT_TRUE(node_time == other_node->GetChild(2)->date_added()); } // Creates a new folder and moves a node to it. TEST_F(BookmarkEditorGtkTest, MoveToNewParent) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"), BookmarkEditor::SHOW_TREE, NULL); GtkTreeIter bookmark_bar_node; GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node)); // The bookmark bar should have 2 nodes: folder F1 and F2. GtkTreeIter f2_iter; ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node)); ASSERT_TRUE(gtk_tree_model_iter_children(store, &f2_iter, &bookmark_bar_node)); ASSERT_TRUE(gtk_tree_model_iter_next(store, &f2_iter)); // Create two nodes: "F21" as a child of "F2" and "F211" as a child of "F21". GtkTreeIter f21_iter; editor.AddNewGroup(&f2_iter, &f21_iter); gtk_tree_store_set(editor.tree_store_, &f21_iter, bookmark_utils::FOLDER_NAME, "F21", -1); GtkTreeIter f211_iter; editor.AddNewGroup(&f21_iter, &f211_iter); gtk_tree_store_set(editor.tree_store_, &f211_iter, bookmark_utils::FOLDER_NAME, "F211", -1); ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f2_iter)); editor.ApplyEdits(&f2_iter); BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode(); BookmarkNode* mf2 = bb_node->GetChild(1); // F2 in the model should have two children now: F21 and the node edited. ASSERT_EQ(2, mf2->GetChildCount()); // F21 should be first. ASSERT_EQ(L"F21", mf2->GetChild(0)->GetTitle()); // Then a. ASSERT_EQ(L"a", mf2->GetChild(1)->GetTitle()); // F21 should have one child, F211. BookmarkNode* mf21 = mf2->GetChild(0); ASSERT_EQ(1, mf21->GetChildCount()); ASSERT_EQ(L"F211", mf21->GetChild(0)->GetTitle()); } // Brings up the editor, creating a new URL on the bookmark bar. TEST_F(BookmarkEditorGtkTest, NewURL) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL, BookmarkEditor::SHOW_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.url_entry_), GURL(base_path() + "a").spec().c_str()); gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a"); GtkTreeIter bookmark_bar_node; GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_); ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node)); editor.ApplyEdits(&bookmark_bar_node); BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode(); ASSERT_EQ(4, bb_node->GetChildCount()); BookmarkNode* new_node = bb_node->GetChild(3); EXPECT_EQ(L"new_a", new_node->GetTitle()); EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL()); } // Brings up the editor with no tree and modifies the url. TEST_F(BookmarkEditorGtkTest, ChangeURLNoTree) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, model_->other_node()->GetChild(0), BookmarkEditor::NO_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.url_entry_), GURL(base_path() + "a").spec().c_str()); gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a"); editor.ApplyEdits(NULL); BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node(); ASSERT_EQ(2, other_node->GetChildCount()); BookmarkNode* new_node = other_node->GetChild(0); EXPECT_EQ(L"new_a", new_node->GetTitle()); EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL()); } // Brings up the editor with no tree and modifies only the title. TEST_F(BookmarkEditorGtkTest, ChangeTitleNoTree) { BookmarkEditorGtk editor(NULL, profile_.get(), NULL, model_->other_node()->GetChild(0), BookmarkEditor::NO_TREE, NULL); gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a"); editor.ApplyEdits(); BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node(); ASSERT_EQ(2, other_node->GetChildCount()); BookmarkNode* new_node = other_node->GetChild(0); EXPECT_EQ(L"new_a", new_node->GetTitle()); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/bookmark_menu_controller_gtk.h" #include <gtk/gtk.h> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/gfx/gtk_util.h" #include "base/string_util.h" #include "chrome/browser/bookmarks/bookmark_context_menu.h" #include "chrome/browser/gtk/menu_gtk.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/page_navigator.h" #include "chrome/common/gtk_util.h" #include "grit/app_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "webkit/glue/window_open_disposition.h" namespace { void SetImageMenuItem(GtkWidget* menu_item, const SkBitmap& bitmap) { GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&bitmap); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), gtk_image_new_from_pixbuf(pixbuf)); g_object_unref(pixbuf); } BookmarkNode* GetNodeFromMenuItem(GtkWidget* menu_item) { return static_cast<BookmarkNode*>( g_object_get_data(G_OBJECT(menu_item), "bookmark-node")); } } // namespace BookmarkMenuController::BookmarkMenuController(Browser* browser, Profile* profile, PageNavigator* navigator, GtkWindow* window, BookmarkNode* node, int start_child_index, bool show_other_folder) : browser_(browser), profile_(profile), page_navigator_(navigator), parent_window_(window), node_(node) { menu_.Own(gtk_menu_new()); BuildMenu(node, start_child_index, menu_.get()); gtk_widget_show_all(menu_.get()); } BookmarkMenuController::~BookmarkMenuController() { profile_->GetBookmarkModel()->RemoveObserver(this); menu_.Destroy(); } void BookmarkMenuController::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) { profile_->GetBookmarkModel()->AddObserver(this); gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, &MenuGtk::MenuPositionFunc, widget, button_type, timestamp); } void BookmarkMenuController::BookmarkModelChanged() { gtk_menu_popdown(GTK_MENU(menu_.get())); } void BookmarkMenuController::BookmarkNodeFavIconLoaded(BookmarkModel* model, BookmarkNode* node) { std::map<BookmarkNode*, GtkWidget*>::iterator it = node_to_menu_widget_map_.find(node); if (it != node_to_menu_widget_map_.end()) SetImageMenuItem(it->second, model->GetFavIcon(node)); } void BookmarkMenuController::NavigateToMenuItem( GtkWidget* menu_item, WindowOpenDisposition disposition) { BookmarkNode* node = GetNodeFromMenuItem(menu_item); DCHECK(node); DCHECK(page_navigator_); page_navigator_->OpenURL( node->GetURL(), GURL(), disposition, PageTransition::AUTO_BOOKMARK); } void BookmarkMenuController::BuildMenu(BookmarkNode* parent, int start_child_index, GtkWidget* menu) { DCHECK(!parent->GetChildCount() || start_child_index < parent->GetChildCount()); for (int i = start_child_index; i < parent->GetChildCount(); ++i) { BookmarkNode* node = parent->GetChild(i); GtkWidget* menu_item = gtk_image_menu_item_new_with_label( WideToUTF8(node->GetTitle()).c_str()); if (node->is_url()) { SkBitmap icon = profile_->GetBookmarkModel()->GetFavIcon(node); if (icon.width() == 0) { icon = *ResourceBundle::GetSharedInstance(). GetBitmapNamed(IDR_DEFAULT_FAVICON); } SetImageMenuItem(menu_item, icon); g_object_set_data(G_OBJECT(menu_item), "bookmark-node", node); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); g_signal_connect(G_OBJECT(menu_item), "button-press-event", G_CALLBACK(OnButtonPressed), this); g_signal_connect(G_OBJECT(menu_item), "button-release-event", G_CALLBACK(OnButtonReleased), this); } else if (node->is_folder()) { SkBitmap* folder_icon = ResourceBundle::GetSharedInstance(). GetBitmapNamed(IDR_BOOKMARK_BAR_FOLDER); SetImageMenuItem(menu_item, *folder_icon); GtkWidget* submenu = gtk_menu_new(); BuildMenu(node, 0, submenu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else { NOTREACHED(); } gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item); node_to_menu_widget_map_[node] = menu_item; } if (parent->GetChildCount() == 0) { GtkWidget* empty_menu = gtk_menu_item_new_with_label( l10n_util::GetStringUTF8(IDS_MENU_EMPTY_SUBMENU).c_str()); gtk_widget_set_sensitive(empty_menu, FALSE); gtk_menu_shell_append(GTK_MENU_SHELL(menu), empty_menu); } } gboolean BookmarkMenuController::OnButtonPressed( GtkWidget* sender, GdkEventButton* event, BookmarkMenuController* controller) { if (event->button == 3) { // Show the right click menu and stop processing this button event. BookmarkNode* node = GetNodeFromMenuItem(sender); BookmarkNode* parent = node->GetParent(); std::vector<BookmarkNode*> nodes; nodes.push_back(node); controller->context_menu_.reset( new BookmarkContextMenu( sender, controller->profile_, controller->browser_, controller->page_navigator_, parent, nodes, BookmarkContextMenu::BOOKMARK_BAR)); controller->context_menu_->PopupAsContext(event->time); return TRUE; } return FALSE; } gboolean BookmarkMenuController::OnButtonReleased( GtkWidget* sender, GdkEventButton* event, BookmarkMenuController* controller) { // TODO(erg): The OnButtonPressed and OnButtonReleased handlers should have // the same guard code that prevents them from interfering with DnD as // BookmarkBarGtk's versions. // Releasing button 1 should trigger the bookmark menu. if (event->button == 1) { WindowOpenDisposition disposition = event_utils::DispositionFromEventFlags(event->state); controller->NavigateToMenuItem(sender, disposition); // We need to manually dismiss the popup menu because we're overriding // button-release-event. gtk_menu_popdown(GTK_MENU(controller->menu_.get())); return TRUE; } return FALSE; } void BookmarkMenuController::OnMenuItemActivated( GtkMenuItem* menu_item, BookmarkMenuController* controller) { controller->NavigateToMenuItem(GTK_WIDGET(menu_item), CURRENT_TAB); } <commit_msg>GTK: Fix middle click in bookmark menus opening with wrong disposition.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/bookmark_menu_controller_gtk.h" #include <gtk/gtk.h> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/gfx/gtk_util.h" #include "base/string_util.h" #include "chrome/browser/bookmarks/bookmark_context_menu.h" #include "chrome/browser/gtk/menu_gtk.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/page_navigator.h" #include "chrome/common/gtk_util.h" #include "grit/app_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "webkit/glue/window_open_disposition.h" namespace { void SetImageMenuItem(GtkWidget* menu_item, const SkBitmap& bitmap) { GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&bitmap); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), gtk_image_new_from_pixbuf(pixbuf)); g_object_unref(pixbuf); } BookmarkNode* GetNodeFromMenuItem(GtkWidget* menu_item) { return static_cast<BookmarkNode*>( g_object_get_data(G_OBJECT(menu_item), "bookmark-node")); } } // namespace BookmarkMenuController::BookmarkMenuController(Browser* browser, Profile* profile, PageNavigator* navigator, GtkWindow* window, BookmarkNode* node, int start_child_index, bool show_other_folder) : browser_(browser), profile_(profile), page_navigator_(navigator), parent_window_(window), node_(node) { menu_.Own(gtk_menu_new()); BuildMenu(node, start_child_index, menu_.get()); gtk_widget_show_all(menu_.get()); } BookmarkMenuController::~BookmarkMenuController() { profile_->GetBookmarkModel()->RemoveObserver(this); menu_.Destroy(); } void BookmarkMenuController::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) { profile_->GetBookmarkModel()->AddObserver(this); gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, &MenuGtk::MenuPositionFunc, widget, button_type, timestamp); } void BookmarkMenuController::BookmarkModelChanged() { gtk_menu_popdown(GTK_MENU(menu_.get())); } void BookmarkMenuController::BookmarkNodeFavIconLoaded(BookmarkModel* model, BookmarkNode* node) { std::map<BookmarkNode*, GtkWidget*>::iterator it = node_to_menu_widget_map_.find(node); if (it != node_to_menu_widget_map_.end()) SetImageMenuItem(it->second, model->GetFavIcon(node)); } void BookmarkMenuController::NavigateToMenuItem( GtkWidget* menu_item, WindowOpenDisposition disposition) { BookmarkNode* node = GetNodeFromMenuItem(menu_item); DCHECK(node); DCHECK(page_navigator_); page_navigator_->OpenURL( node->GetURL(), GURL(), disposition, PageTransition::AUTO_BOOKMARK); } void BookmarkMenuController::BuildMenu(BookmarkNode* parent, int start_child_index, GtkWidget* menu) { DCHECK(!parent->GetChildCount() || start_child_index < parent->GetChildCount()); for (int i = start_child_index; i < parent->GetChildCount(); ++i) { BookmarkNode* node = parent->GetChild(i); GtkWidget* menu_item = gtk_image_menu_item_new_with_label( WideToUTF8(node->GetTitle()).c_str()); if (node->is_url()) { SkBitmap icon = profile_->GetBookmarkModel()->GetFavIcon(node); if (icon.width() == 0) { icon = *ResourceBundle::GetSharedInstance(). GetBitmapNamed(IDR_DEFAULT_FAVICON); } SetImageMenuItem(menu_item, icon); g_object_set_data(G_OBJECT(menu_item), "bookmark-node", node); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); g_signal_connect(G_OBJECT(menu_item), "button-press-event", G_CALLBACK(OnButtonPressed), this); g_signal_connect(G_OBJECT(menu_item), "button-release-event", G_CALLBACK(OnButtonReleased), this); } else if (node->is_folder()) { SkBitmap* folder_icon = ResourceBundle::GetSharedInstance(). GetBitmapNamed(IDR_BOOKMARK_BAR_FOLDER); SetImageMenuItem(menu_item, *folder_icon); GtkWidget* submenu = gtk_menu_new(); BuildMenu(node, 0, submenu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else { NOTREACHED(); } gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item); node_to_menu_widget_map_[node] = menu_item; } if (parent->GetChildCount() == 0) { GtkWidget* empty_menu = gtk_menu_item_new_with_label( l10n_util::GetStringUTF8(IDS_MENU_EMPTY_SUBMENU).c_str()); gtk_widget_set_sensitive(empty_menu, FALSE); gtk_menu_shell_append(GTK_MENU_SHELL(menu), empty_menu); } } gboolean BookmarkMenuController::OnButtonPressed( GtkWidget* sender, GdkEventButton* event, BookmarkMenuController* controller) { if (event->button == 3) { // Show the right click menu and stop processing this button event. BookmarkNode* node = GetNodeFromMenuItem(sender); BookmarkNode* parent = node->GetParent(); std::vector<BookmarkNode*> nodes; nodes.push_back(node); controller->context_menu_.reset( new BookmarkContextMenu( sender, controller->profile_, controller->browser_, controller->page_navigator_, parent, nodes, BookmarkContextMenu::BOOKMARK_BAR)); controller->context_menu_->PopupAsContext(event->time); return TRUE; } return FALSE; } gboolean BookmarkMenuController::OnButtonReleased( GtkWidget* sender, GdkEventButton* event, BookmarkMenuController* controller) { // TODO(erg): The OnButtonPressed and OnButtonReleased handlers should have // the same guard code that prevents them from interfering with DnD as // BookmarkBarGtk's versions. // Releasing either button 1 or 2 should trigger the bookmark menu. if (event->button == 1 || event->button == 2) { WindowOpenDisposition disposition = event_utils::DispositionFromEventFlags(event->state); controller->NavigateToMenuItem(sender, disposition); // We need to manually dismiss the popup menu because we're overriding // button-release-event. gtk_menu_popdown(GTK_MENU(controller->menu_.get())); return TRUE; } return FALSE; } void BookmarkMenuController::OnMenuItemActivated( GtkMenuItem* menu_item, BookmarkMenuController* controller) { controller->NavigateToMenuItem(GTK_WIDGET(menu_item), CURRENT_TAB); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/speech/speech_input_bubble.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/views/info_bubble.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "gfx/canvas.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/standard_layout.h" #include "views/view.h" namespace { const int kBubbleHorizMargin = 6; const int kBubbleVertMargin = 0; // This is the content view which is placed inside a SpeechInputBubble. class ContentView : public views::View, public views::ButtonListener { public: explicit ContentView(SpeechInputBubbleDelegate* delegate); void UpdateLayout(SpeechInputBubbleBase::DisplayMode mode, const string16& message_text); // views::ButtonListener methods. virtual void ButtonPressed(views::Button* source, const views::Event& event); // views::View overrides. virtual gfx::Size GetPreferredSize(); virtual void Layout(); private: SpeechInputBubbleDelegate* delegate_; views::ImageView* icon_; views::Label* heading_; views::Label* message_; views::NativeButton* try_again_; views::NativeButton* cancel_; DISALLOW_COPY_AND_ASSIGN(ContentView); }; ContentView::ContentView(SpeechInputBubbleDelegate* delegate) : delegate_(delegate) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::MediumFont); heading_ = new views::Label( l10n_util::GetString(IDS_SPEECH_INPUT_BUBBLE_HEADING)); heading_->SetFont(font); heading_->SetHorizontalAlignment(views::Label::ALIGN_CENTER); AddChildView(heading_); message_ = new views::Label(); message_->SetFont(font); message_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); message_->SetMultiLine(true); AddChildView(message_); icon_ = new views::ImageView(); icon_->SetImage(*ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_SPEECH_INPUT_RECORDING)); icon_->SetHorizontalAlignment(views::ImageView::CENTER); AddChildView(icon_); cancel_ = new views::NativeButton(this, l10n_util::GetString(IDS_CANCEL)); AddChildView(cancel_); try_again_ = new views::NativeButton( this, l10n_util::GetString(IDS_SPEECH_INPUT_TRY_AGAIN)); AddChildView(try_again_); } void ContentView::UpdateLayout(SpeechInputBubbleBase::DisplayMode mode, const string16& message_text) { bool is_message = (mode == SpeechInputBubbleBase::DISPLAY_MODE_MESSAGE); heading_->SetVisible(!is_message); icon_->SetVisible(!is_message); message_->SetVisible(is_message); try_again_->SetVisible(is_message); if (mode == SpeechInputBubbleBase::DISPLAY_MODE_MESSAGE) { message_->SetText(message_text); } else { icon_->SetImage(*ResourceBundle::GetSharedInstance().GetBitmapNamed( (mode == SpeechInputBubbleBase::DISPLAY_MODE_RECORDING) ? IDR_SPEECH_INPUT_RECORDING : IDR_SPEECH_INPUT_PROCESSING)); } } void ContentView::ButtonPressed(views::Button* source, const views::Event& event) { if (source == cancel_) { delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_CANCEL); } else if (source == try_again_) { delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_TRY_AGAIN); } else { NOTREACHED() << "Unknown button"; } } gfx::Size ContentView::GetPreferredSize() { int width = heading_->GetPreferredSize().width(); int control_width = cancel_->GetPreferredSize().width() + try_again_->GetPreferredSize().width() + kRelatedButtonHSpacing; if (control_width > width) width = control_width; control_width = icon_->GetPreferredSize().width(); if (control_width > width) width = control_width; int height = cancel_->GetPreferredSize().height(); if (message_->IsVisible()) { height += message_->GetHeightForWidth(width) + kLabelToControlVerticalSpacing; } else { height += heading_->GetPreferredSize().height() + icon_->GetImage().height(); } width += kBubbleHorizMargin * 2; height += kBubbleVertMargin * 2; return gfx::Size(width, height); } void ContentView::Layout() { int x = kBubbleHorizMargin; int y = kBubbleVertMargin; int available_width = width() - kBubbleHorizMargin * 2; int available_height = height() - kBubbleVertMargin * 2; if (message_->IsVisible()) { DCHECK(try_again_->IsVisible()); int height = try_again_->GetPreferredSize().height(); int try_again_width = try_again_->GetPreferredSize().width(); int cancel_width = cancel_->GetPreferredSize().width(); y += available_height - height; x += (available_width - cancel_width - try_again_width - kRelatedButtonHSpacing) / 2; try_again_->SetBounds(x, y, try_again_width, height); cancel_->SetBounds(x + try_again_width + kRelatedButtonHSpacing, y, cancel_width, height); height = message_->GetHeightForWidth(available_width); if (height > y - kBubbleVertMargin) height = y - kBubbleVertMargin; message_->SetBounds(kBubbleHorizMargin, kBubbleVertMargin, available_width, height); } else { DCHECK(heading_->IsVisible()); DCHECK(icon_->IsVisible()); int height = heading_->GetPreferredSize().height(); heading_->SetBounds(x, y, available_width, height); y += height; height = icon_->GetImage().height(); icon_->SetBounds(x, y, available_width, height); y += height; height = cancel_->GetPreferredSize().height(); int width = cancel_->GetPreferredSize().width(); cancel_->SetBounds(x + (available_width - width) / 2, y, width, height); } } // Implementation of SpeechInputBubble. class SpeechInputBubbleImpl : public SpeechInputBubbleBase, public InfoBubbleDelegate, public NotificationObserver { public: SpeechInputBubbleImpl(TabContents* tab_contents, Delegate* delegate, const gfx::Rect& element_rect); virtual ~SpeechInputBubbleImpl(); // SpeechInputBubble methods. virtual void Show(); virtual void Hide(); // SpeechInputBubbleBase methods. virtual void UpdateLayout(); // Returns the screen rectangle to use as the info bubble's target. // |element_rect| is the html element's bounds in page coordinates. gfx::Rect GetInfoBubbleTarget(const gfx::Rect& element_rect); // NotificationObserver implementation. virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details); // InfoBubbleDelegate virtual void InfoBubbleClosing(InfoBubble* info_bubble, bool closed_by_escape); virtual bool CloseOnEscape(); virtual bool FadeInOnShow(); private: Delegate* delegate_; InfoBubble* info_bubble_; TabContents* tab_contents_; ContentView* bubble_content_; NotificationRegistrar registrar_; gfx::Rect element_rect_; // Set to true if the object is being destroyed normally instead of the // user clicking outside the window causing it to close automatically. bool did_invoke_close_; DISALLOW_COPY_AND_ASSIGN(SpeechInputBubbleImpl); }; SpeechInputBubbleImpl::SpeechInputBubbleImpl(TabContents* tab_contents, Delegate* delegate, const gfx::Rect& element_rect) : delegate_(delegate), info_bubble_(NULL), tab_contents_(tab_contents), bubble_content_(NULL), element_rect_(element_rect), did_invoke_close_(false) { } SpeechInputBubbleImpl::~SpeechInputBubbleImpl() { did_invoke_close_ = true; Hide(); } gfx::Rect SpeechInputBubbleImpl::GetInfoBubbleTarget( const gfx::Rect& element_rect) { gfx::Rect container_rect; tab_contents_->GetContainerBounds(&container_rect); return gfx::Rect( container_rect.x() + element_rect.x() + kBubbleTargetOffsetX, container_rect.y() + element_rect.y() + element_rect.height(), 1, 1); } void SpeechInputBubbleImpl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::TAB_CONTENTS_DESTROYED) { delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_CANCEL); } else { NOTREACHED() << "Unknown notification"; } } void SpeechInputBubbleImpl::InfoBubbleClosing(InfoBubble* info_bubble, bool closed_by_escape) { registrar_.Remove(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(tab_contents_)); info_bubble_ = NULL; bubble_content_ = NULL; if (!did_invoke_close_) delegate_->InfoBubbleFocusChanged(); } bool SpeechInputBubbleImpl::CloseOnEscape() { return false; } bool SpeechInputBubbleImpl::FadeInOnShow() { return false; } void SpeechInputBubbleImpl::Show() { if (info_bubble_) return; // nothing to do, already visible. bubble_content_ = new ContentView(delegate_); UpdateLayout(); views::Widget* parent = views::Widget::GetWidgetFromNativeWindow( tab_contents_->view()->GetTopLevelNativeWindow()); info_bubble_ = InfoBubble::Show(parent, GetInfoBubbleTarget(element_rect_), BubbleBorder::TOP_LEFT, bubble_content_, this); // We don't want fade outs when closing because it makes speech recognition // appear slower than it is. Also setting it to false allows |Close| to // destroy the bubble immediately instead of waiting for the fade animation // to end so the caller can manage this object's life cycle like a normal // stack based or member variable object. info_bubble_->set_fade_away_on_close(false); registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(tab_contents_)); } void SpeechInputBubbleImpl::Hide() { if (info_bubble_) info_bubble_->Close(); } void SpeechInputBubbleImpl::UpdateLayout() { if (bubble_content_) bubble_content_->UpdateLayout(display_mode(), message_text()); if (info_bubble_) // Will be null on first call. info_bubble_->SizeToContents(); } } // namespace SpeechInputBubble* SpeechInputBubble::CreateNativeBubble( TabContents* tab_contents, SpeechInputBubble::Delegate* delegate, const gfx::Rect& element_rect) { return new SpeechInputBubbleImpl(tab_contents, delegate, element_rect); } <commit_msg>Fix chrome os build break caused by passing string16 where a wstring was expected.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/speech/speech_input_bubble.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/views/info_bubble.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "gfx/canvas.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/standard_layout.h" #include "views/view.h" namespace { const int kBubbleHorizMargin = 6; const int kBubbleVertMargin = 0; // This is the content view which is placed inside a SpeechInputBubble. class ContentView : public views::View, public views::ButtonListener { public: explicit ContentView(SpeechInputBubbleDelegate* delegate); void UpdateLayout(SpeechInputBubbleBase::DisplayMode mode, const string16& message_text); // views::ButtonListener methods. virtual void ButtonPressed(views::Button* source, const views::Event& event); // views::View overrides. virtual gfx::Size GetPreferredSize(); virtual void Layout(); private: SpeechInputBubbleDelegate* delegate_; views::ImageView* icon_; views::Label* heading_; views::Label* message_; views::NativeButton* try_again_; views::NativeButton* cancel_; DISALLOW_COPY_AND_ASSIGN(ContentView); }; ContentView::ContentView(SpeechInputBubbleDelegate* delegate) : delegate_(delegate) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::MediumFont); heading_ = new views::Label( l10n_util::GetString(IDS_SPEECH_INPUT_BUBBLE_HEADING)); heading_->SetFont(font); heading_->SetHorizontalAlignment(views::Label::ALIGN_CENTER); AddChildView(heading_); message_ = new views::Label(); message_->SetFont(font); message_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); message_->SetMultiLine(true); AddChildView(message_); icon_ = new views::ImageView(); icon_->SetImage(*ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_SPEECH_INPUT_RECORDING)); icon_->SetHorizontalAlignment(views::ImageView::CENTER); AddChildView(icon_); cancel_ = new views::NativeButton(this, l10n_util::GetString(IDS_CANCEL)); AddChildView(cancel_); try_again_ = new views::NativeButton( this, l10n_util::GetString(IDS_SPEECH_INPUT_TRY_AGAIN)); AddChildView(try_again_); } void ContentView::UpdateLayout(SpeechInputBubbleBase::DisplayMode mode, const string16& message_text) { bool is_message = (mode == SpeechInputBubbleBase::DISPLAY_MODE_MESSAGE); heading_->SetVisible(!is_message); icon_->SetVisible(!is_message); message_->SetVisible(is_message); try_again_->SetVisible(is_message); if (mode == SpeechInputBubbleBase::DISPLAY_MODE_MESSAGE) { message_->SetText(UTF16ToWideHack(message_text)); } else { icon_->SetImage(*ResourceBundle::GetSharedInstance().GetBitmapNamed( (mode == SpeechInputBubbleBase::DISPLAY_MODE_RECORDING) ? IDR_SPEECH_INPUT_RECORDING : IDR_SPEECH_INPUT_PROCESSING)); } } void ContentView::ButtonPressed(views::Button* source, const views::Event& event) { if (source == cancel_) { delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_CANCEL); } else if (source == try_again_) { delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_TRY_AGAIN); } else { NOTREACHED() << "Unknown button"; } } gfx::Size ContentView::GetPreferredSize() { int width = heading_->GetPreferredSize().width(); int control_width = cancel_->GetPreferredSize().width() + try_again_->GetPreferredSize().width() + kRelatedButtonHSpacing; if (control_width > width) width = control_width; control_width = icon_->GetPreferredSize().width(); if (control_width > width) width = control_width; int height = cancel_->GetPreferredSize().height(); if (message_->IsVisible()) { height += message_->GetHeightForWidth(width) + kLabelToControlVerticalSpacing; } else { height += heading_->GetPreferredSize().height() + icon_->GetImage().height(); } width += kBubbleHorizMargin * 2; height += kBubbleVertMargin * 2; return gfx::Size(width, height); } void ContentView::Layout() { int x = kBubbleHorizMargin; int y = kBubbleVertMargin; int available_width = width() - kBubbleHorizMargin * 2; int available_height = height() - kBubbleVertMargin * 2; if (message_->IsVisible()) { DCHECK(try_again_->IsVisible()); int height = try_again_->GetPreferredSize().height(); int try_again_width = try_again_->GetPreferredSize().width(); int cancel_width = cancel_->GetPreferredSize().width(); y += available_height - height; x += (available_width - cancel_width - try_again_width - kRelatedButtonHSpacing) / 2; try_again_->SetBounds(x, y, try_again_width, height); cancel_->SetBounds(x + try_again_width + kRelatedButtonHSpacing, y, cancel_width, height); height = message_->GetHeightForWidth(available_width); if (height > y - kBubbleVertMargin) height = y - kBubbleVertMargin; message_->SetBounds(kBubbleHorizMargin, kBubbleVertMargin, available_width, height); } else { DCHECK(heading_->IsVisible()); DCHECK(icon_->IsVisible()); int height = heading_->GetPreferredSize().height(); heading_->SetBounds(x, y, available_width, height); y += height; height = icon_->GetImage().height(); icon_->SetBounds(x, y, available_width, height); y += height; height = cancel_->GetPreferredSize().height(); int width = cancel_->GetPreferredSize().width(); cancel_->SetBounds(x + (available_width - width) / 2, y, width, height); } } // Implementation of SpeechInputBubble. class SpeechInputBubbleImpl : public SpeechInputBubbleBase, public InfoBubbleDelegate, public NotificationObserver { public: SpeechInputBubbleImpl(TabContents* tab_contents, Delegate* delegate, const gfx::Rect& element_rect); virtual ~SpeechInputBubbleImpl(); // SpeechInputBubble methods. virtual void Show(); virtual void Hide(); // SpeechInputBubbleBase methods. virtual void UpdateLayout(); // Returns the screen rectangle to use as the info bubble's target. // |element_rect| is the html element's bounds in page coordinates. gfx::Rect GetInfoBubbleTarget(const gfx::Rect& element_rect); // NotificationObserver implementation. virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details); // InfoBubbleDelegate virtual void InfoBubbleClosing(InfoBubble* info_bubble, bool closed_by_escape); virtual bool CloseOnEscape(); virtual bool FadeInOnShow(); private: Delegate* delegate_; InfoBubble* info_bubble_; TabContents* tab_contents_; ContentView* bubble_content_; NotificationRegistrar registrar_; gfx::Rect element_rect_; // Set to true if the object is being destroyed normally instead of the // user clicking outside the window causing it to close automatically. bool did_invoke_close_; DISALLOW_COPY_AND_ASSIGN(SpeechInputBubbleImpl); }; SpeechInputBubbleImpl::SpeechInputBubbleImpl(TabContents* tab_contents, Delegate* delegate, const gfx::Rect& element_rect) : delegate_(delegate), info_bubble_(NULL), tab_contents_(tab_contents), bubble_content_(NULL), element_rect_(element_rect), did_invoke_close_(false) { } SpeechInputBubbleImpl::~SpeechInputBubbleImpl() { did_invoke_close_ = true; Hide(); } gfx::Rect SpeechInputBubbleImpl::GetInfoBubbleTarget( const gfx::Rect& element_rect) { gfx::Rect container_rect; tab_contents_->GetContainerBounds(&container_rect); return gfx::Rect( container_rect.x() + element_rect.x() + kBubbleTargetOffsetX, container_rect.y() + element_rect.y() + element_rect.height(), 1, 1); } void SpeechInputBubbleImpl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::TAB_CONTENTS_DESTROYED) { delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_CANCEL); } else { NOTREACHED() << "Unknown notification"; } } void SpeechInputBubbleImpl::InfoBubbleClosing(InfoBubble* info_bubble, bool closed_by_escape) { registrar_.Remove(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(tab_contents_)); info_bubble_ = NULL; bubble_content_ = NULL; if (!did_invoke_close_) delegate_->InfoBubbleFocusChanged(); } bool SpeechInputBubbleImpl::CloseOnEscape() { return false; } bool SpeechInputBubbleImpl::FadeInOnShow() { return false; } void SpeechInputBubbleImpl::Show() { if (info_bubble_) return; // nothing to do, already visible. bubble_content_ = new ContentView(delegate_); UpdateLayout(); views::Widget* parent = views::Widget::GetWidgetFromNativeWindow( tab_contents_->view()->GetTopLevelNativeWindow()); info_bubble_ = InfoBubble::Show(parent, GetInfoBubbleTarget(element_rect_), BubbleBorder::TOP_LEFT, bubble_content_, this); // We don't want fade outs when closing because it makes speech recognition // appear slower than it is. Also setting it to false allows |Close| to // destroy the bubble immediately instead of waiting for the fade animation // to end so the caller can manage this object's life cycle like a normal // stack based or member variable object. info_bubble_->set_fade_away_on_close(false); registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(tab_contents_)); } void SpeechInputBubbleImpl::Hide() { if (info_bubble_) info_bubble_->Close(); } void SpeechInputBubbleImpl::UpdateLayout() { if (bubble_content_) bubble_content_->UpdateLayout(display_mode(), message_text()); if (info_bubble_) // Will be null on first call. info_bubble_->SizeToContents(); } } // namespace SpeechInputBubble* SpeechInputBubble::CreateNativeBubble( TabContents* tab_contents, SpeechInputBubble::Delegate* delegate, const gfx::Rect& element_rect) { return new SpeechInputBubbleImpl(tab_contents, delegate, element_rect); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/thumbnail_generator.h" #include <algorithm> #include "base/histogram.h" #include "base/time.h" #include "chrome/browser/renderer_host/backing_store.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/common/notification_service.h" #include "chrome/common/property_bag.h" #include "skia/ext/image_operations.h" #include "skia/ext/platform_canvas.h" #include "third_party/skia/include/core/SkBitmap.h" // Overview // -------- // This class provides current thumbnails for tabs. The simplest operation is // when a request for a thumbnail comes in, to grab the backing store and make // a smaller version of that. // // A complication happens because we don't always have nice backing stores for // all tabs (there is a cache of several tabs we'll keep backing stores for). // To get thumbnails for tabs with expired backing stores, we listen for // backing stores that are being thrown out, and generate thumbnails before // that happens. We attach them to the RenderWidgetHost via the property bag // so we can retrieve them later. When a tab has a live backing store again, // we throw away the thumbnail since it's now out-of-date. // // Another complication is performance. If the user brings up a tab switcher, we // don't want to get all 5 cached backing stores since it is a very large amount // of data. As a result, we generate thumbnails for tabs that are hidden even // if the backing store is still valid. This means we'll have to do a maximum // of generating thumbnails for the visible tabs at any point. // // The last performance consideration is when the user switches tabs quickly. // This can happen by doing Control-PageUp/Down or juct clicking quickly on // many different tabs (like when you're looking for one). We don't want to // slow this down by making thumbnails for each tab as it's hidden. Therefore, // we have a timer so that we don't invalidate thumbnails for tabs that are // only shown briefly (which would cause the thumbnail to be regenerated when // the tab is hidden). namespace { static const int kThumbnailWidth = 294; static const int kThumbnailHeight = 204; // Indicates the time that the RWH must be visible for us to update the // thumbnail on it. If the user holds down control enter, there will be a lot // of backing stores created and destroyed. WE don't want to interfere with // that. // // Any operation that happens within this time of being shown is ignored. // This means we won't throw the thumbnail away when the backing store is // painted in this time. static const int kVisibilitySlopMS = 3000; static const char kThumbnailHistogramName[] = "Thumbnail.ComputeMS"; struct WidgetThumbnail { SkBitmap thumbnail; // Indicates the last time the RWH was shown and hidden. base::TimeTicks last_shown; base::TimeTicks last_hidden; }; PropertyAccessor<WidgetThumbnail>* GetThumbnailAccessor() { static PropertyAccessor<WidgetThumbnail> accessor; return &accessor; } // Returns the existing WidgetThumbnail for a RVH, or creates a new one and // returns that if none exists. WidgetThumbnail* GetDataForHost(RenderWidgetHost* host) { WidgetThumbnail* wt = GetThumbnailAccessor()->GetProperty( host->property_bag()); if (wt) return wt; GetThumbnailAccessor()->SetProperty(host->property_bag(), WidgetThumbnail()); return GetThumbnailAccessor()->GetProperty(host->property_bag()); } #if defined(OS_WIN) // PlatformDevices/Canvases can't be copied like a regular SkBitmap (at least // on Windows). So the second parameter is the canvas to draw into. It should // be sized to the size of the backing store. void GetBitmapForBackingStore(BackingStore* backing_store, skia::PlatformCanvas* canvas) { HDC dc = canvas->beginPlatformPaint(); BitBlt(dc, 0, 0, backing_store->size().width(), backing_store->size().height(), backing_store->hdc(), 0, 0, SRCCOPY); canvas->endPlatformPaint(); } #endif // Creates a downsampled thumbnail for the given backing store. The returned // bitmap will be isNull if there was an error creating it. SkBitmap GetThumbnailForBackingStore(BackingStore* backing_store) { base::TimeTicks begin_compute_thumbnail = base::TimeTicks::Now(); SkBitmap result; // TODO(brettw) write this for other platforms. If you enable this, be sure // to also enable the unit tests for the same platform in // thumbnail_generator_unittest.cc #if defined(OS_WIN) // Get the bitmap as a Skia object so we can resample it. This is a large // allocation and we can tolerate failure here, so give up if the allocation // fails. skia::PlatformCanvas temp_canvas; if (!temp_canvas.initialize(backing_store->size().width(), backing_store->size().height(), true)) return result; GetBitmapForBackingStore(backing_store, &temp_canvas); // Get the bitmap out of the canvas and resample it. It would be nice if this // whole Windows-specific block could be put into a function, but the memory // management wouldn't work out because the bitmap is a PlatformDevice which // can't actually be copied. const SkBitmap& bmp = temp_canvas.getTopPlatformDevice().accessBitmap(false); #elif defined(OS_LINUX) SkBitmap bmp = backing_store->PaintRectToBitmap( gfx::Rect(0, 0, backing_store->size().width(), backing_store->size().height())); #elif defined(OS_MAC) SkBitmap bmp; NOTEIMPLEMENTED(); #endif result = skia::ImageOperations::DownsampleByTwoUntilSize( bmp, kThumbnailWidth, kThumbnailHeight); #if defined(OS_WIN) // This is a bit subtle. SkBitmaps are refcounted, but the magic ones in // PlatformCanvas on Windows can't be ssigned to SkBitmap with proper // refcounting. If the bitmap doesn't change, then the downsampler will // return the input bitmap, which will be the reference to the weird // PlatformCanvas one insetad of a regular one. To get a regular refcounted // bitmap, we need to copy it. if (bmp.width() == result.width() && bmp.height() == result.height()) bmp.copyTo(&result, SkBitmap::kARGB_8888_Config); #endif HISTOGRAM_TIMES(kThumbnailHistogramName, base::TimeTicks::Now() - begin_compute_thumbnail); return result; } } // namespace ThumbnailGenerator::ThumbnailGenerator() : no_timeout_(false) { // The BrowserProcessImpl creates this non-lazily. If you add nontrivial // stuff here, be sure to convert it to being lazily created. // // We don't register for notifications here since BrowserProcessImpl creates // us before the NotificationService is. } ThumbnailGenerator::~ThumbnailGenerator() { } void ThumbnailGenerator::StartThumbnailing() { if (registrar_.IsEmpty()) { // Even though we deal in RenderWidgetHosts, we only care about its // subclass, RenderViewHost when it is in a tab. We don't make thumbnails // for RenderViewHosts that aren't in tabs, or RenderWidgetHosts that // aren't views like select popups. registrar_.Add(this, NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB, NotificationService::AllSources()); registrar_.Add(this, NotificationType::RENDER_WIDGET_VISIBILITY_CHANGED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); } } SkBitmap ThumbnailGenerator::GetThumbnailForRenderer( RenderWidgetHost* renderer) const { // Return a cached one if we have it and it's still valid. This will only be // valid when there used to be a backing store, but there isn't now. WidgetThumbnail* wt = GetDataForHost(renderer); if (!wt->thumbnail.isNull() && (no_timeout_ || base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) < wt->last_shown)) return wt->thumbnail; BackingStore* backing_store = renderer->GetBackingStore(false); if (!backing_store) return SkBitmap(); // Save this thumbnail in case we need to use it again soon. It will be // invalidated on the next paint. wt->thumbnail = GetThumbnailForBackingStore(backing_store); return wt->thumbnail; } void ThumbnailGenerator::WidgetWillDestroyBackingStore( RenderWidgetHost* widget, BackingStore* backing_store) { // Since the backing store is going away, we need to save it as a thumbnail. WidgetThumbnail* wt = GetDataForHost(widget); // If there is already a thumbnail on the RWH that's visible, it means that // not enough time has elapsed since being shown, and we can ignore generating // a new one. if (!wt->thumbnail.isNull()) return; // Save a scaled-down image of the page in case we're asked for the thumbnail // when there is no RenderViewHost. If this fails, we don't want to overwrite // an existing thumbnail. SkBitmap new_thumbnail = GetThumbnailForBackingStore(backing_store); if (!new_thumbnail.isNull()) wt->thumbnail = new_thumbnail; } void ThumbnailGenerator::WidgetDidUpdateBackingStore( RenderWidgetHost* widget) { // Clear the current thumbnail since it's no longer valid. WidgetThumbnail* wt = GetThumbnailAccessor()->GetProperty( widget->property_bag()); if (!wt) return; // Nothing to do. // If this operation is within the time slop after being shown, keep the // existing thumbnail. if (no_timeout_ || base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) < wt->last_shown) return; // TODO(brettw) schedule thumbnail generation for this renderer in // case we don't get a paint for it after the time slop, but it's // still visible. // Clear the thumbnail, since it's now out of date. wt->thumbnail = SkBitmap(); } void ThumbnailGenerator::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB: { // Install our observer for all new RVHs. RenderViewHost* renderer = Details<RenderViewHost>(details).ptr(); renderer->set_painting_observer(this); break; } case NotificationType::RENDER_WIDGET_VISIBILITY_CHANGED: if (*Details<bool>(details).ptr()) WidgetShown(Source<RenderWidgetHost>(source).ptr()); else WidgetHidden(Source<RenderWidgetHost>(source).ptr()); break; case NotificationType::RENDER_WIDGET_HOST_DESTROYED: WidgetDestroyed(Source<RenderWidgetHost>(source).ptr()); break; default: NOTREACHED(); } } void ThumbnailGenerator::WidgetShown(RenderWidgetHost* widget) { WidgetThumbnail* wt = GetDataForHost(widget); wt->last_shown = base::TimeTicks::Now(); // If there is no thumbnail (like we're displaying a background tab for the // first time), then we don't have do to invalidate the existing one. if (wt->thumbnail.isNull()) return; std::vector<RenderWidgetHost*>::iterator found = std::find(shown_hosts_.begin(), shown_hosts_.end(), widget); if (found != shown_hosts_.end()) { NOTREACHED() << "Showing a RWH we already think is shown"; shown_hosts_.erase(found); } shown_hosts_.push_back(widget); // Keep the old thumbnail for a small amount of time after the tab has been // shown. This is so in case it's hidden quickly again, we don't waste any // work regenerating it. if (timer_.IsRunning()) return; timer_.Start(base::TimeDelta::FromMilliseconds( no_timeout_ ? 0 : kVisibilitySlopMS), this, &ThumbnailGenerator::ShownDelayHandler); } void ThumbnailGenerator::WidgetHidden(RenderWidgetHost* widget) { WidgetThumbnail* wt = GetDataForHost(widget); wt->last_hidden = base::TimeTicks::Now(); // If the tab is on the list of ones to invalidate the thumbnail, we need to // remove it. EraseHostFromShownList(widget); // There may still be a valid cached thumbnail on the RWH, so we don't need to // make a new one. if (!wt->thumbnail.isNull()) return; wt->thumbnail = GetThumbnailForRenderer(widget); } void ThumbnailGenerator::WidgetDestroyed(RenderWidgetHost* widget) { EraseHostFromShownList(widget); } void ThumbnailGenerator::ShownDelayHandler() { base::TimeTicks threshold = base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS); // Check the list of all pending RWHs (normally only one) to see if any of // their times have expired. for (size_t i = 0; i < shown_hosts_.size(); i++) { WidgetThumbnail* wt = GetDataForHost(shown_hosts_[i]); if (no_timeout_ || wt->last_shown <= threshold) { // This thumbnail has expired, delete it. wt->thumbnail = SkBitmap(); shown_hosts_.erase(shown_hosts_.begin() + i); i--; } } // We need to schedule another run if there are still items in the list to // process. We use half the timeout for these re-runs to catch the items // that were added since the timer was run the first time. if (!shown_hosts_.empty()) { DCHECK(!no_timeout_); timer_.Start(base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) / 2, this, &ThumbnailGenerator::ShownDelayHandler); } } void ThumbnailGenerator::EraseHostFromShownList(RenderWidgetHost* widget) { std::vector<RenderWidgetHost*>::iterator found = std::find(shown_hosts_.begin(), shown_hosts_.end(), widget); if (found != shown_hosts_.end()) shown_hosts_.erase(found); } <commit_msg>Build fix, use the correct define for mac.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/thumbnail_generator.h" #include <algorithm> #include "base/histogram.h" #include "base/time.h" #include "chrome/browser/renderer_host/backing_store.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/common/notification_service.h" #include "chrome/common/property_bag.h" #include "skia/ext/image_operations.h" #include "skia/ext/platform_canvas.h" #include "third_party/skia/include/core/SkBitmap.h" // Overview // -------- // This class provides current thumbnails for tabs. The simplest operation is // when a request for a thumbnail comes in, to grab the backing store and make // a smaller version of that. // // A complication happens because we don't always have nice backing stores for // all tabs (there is a cache of several tabs we'll keep backing stores for). // To get thumbnails for tabs with expired backing stores, we listen for // backing stores that are being thrown out, and generate thumbnails before // that happens. We attach them to the RenderWidgetHost via the property bag // so we can retrieve them later. When a tab has a live backing store again, // we throw away the thumbnail since it's now out-of-date. // // Another complication is performance. If the user brings up a tab switcher, we // don't want to get all 5 cached backing stores since it is a very large amount // of data. As a result, we generate thumbnails for tabs that are hidden even // if the backing store is still valid. This means we'll have to do a maximum // of generating thumbnails for the visible tabs at any point. // // The last performance consideration is when the user switches tabs quickly. // This can happen by doing Control-PageUp/Down or juct clicking quickly on // many different tabs (like when you're looking for one). We don't want to // slow this down by making thumbnails for each tab as it's hidden. Therefore, // we have a timer so that we don't invalidate thumbnails for tabs that are // only shown briefly (which would cause the thumbnail to be regenerated when // the tab is hidden). namespace { static const int kThumbnailWidth = 294; static const int kThumbnailHeight = 204; // Indicates the time that the RWH must be visible for us to update the // thumbnail on it. If the user holds down control enter, there will be a lot // of backing stores created and destroyed. WE don't want to interfere with // that. // // Any operation that happens within this time of being shown is ignored. // This means we won't throw the thumbnail away when the backing store is // painted in this time. static const int kVisibilitySlopMS = 3000; static const char kThumbnailHistogramName[] = "Thumbnail.ComputeMS"; struct WidgetThumbnail { SkBitmap thumbnail; // Indicates the last time the RWH was shown and hidden. base::TimeTicks last_shown; base::TimeTicks last_hidden; }; PropertyAccessor<WidgetThumbnail>* GetThumbnailAccessor() { static PropertyAccessor<WidgetThumbnail> accessor; return &accessor; } // Returns the existing WidgetThumbnail for a RVH, or creates a new one and // returns that if none exists. WidgetThumbnail* GetDataForHost(RenderWidgetHost* host) { WidgetThumbnail* wt = GetThumbnailAccessor()->GetProperty( host->property_bag()); if (wt) return wt; GetThumbnailAccessor()->SetProperty(host->property_bag(), WidgetThumbnail()); return GetThumbnailAccessor()->GetProperty(host->property_bag()); } #if defined(OS_WIN) // PlatformDevices/Canvases can't be copied like a regular SkBitmap (at least // on Windows). So the second parameter is the canvas to draw into. It should // be sized to the size of the backing store. void GetBitmapForBackingStore(BackingStore* backing_store, skia::PlatformCanvas* canvas) { HDC dc = canvas->beginPlatformPaint(); BitBlt(dc, 0, 0, backing_store->size().width(), backing_store->size().height(), backing_store->hdc(), 0, 0, SRCCOPY); canvas->endPlatformPaint(); } #endif // Creates a downsampled thumbnail for the given backing store. The returned // bitmap will be isNull if there was an error creating it. SkBitmap GetThumbnailForBackingStore(BackingStore* backing_store) { base::TimeTicks begin_compute_thumbnail = base::TimeTicks::Now(); SkBitmap result; // TODO(brettw) write this for other platforms. If you enable this, be sure // to also enable the unit tests for the same platform in // thumbnail_generator_unittest.cc #if defined(OS_WIN) // Get the bitmap as a Skia object so we can resample it. This is a large // allocation and we can tolerate failure here, so give up if the allocation // fails. skia::PlatformCanvas temp_canvas; if (!temp_canvas.initialize(backing_store->size().width(), backing_store->size().height(), true)) return result; GetBitmapForBackingStore(backing_store, &temp_canvas); // Get the bitmap out of the canvas and resample it. It would be nice if this // whole Windows-specific block could be put into a function, but the memory // management wouldn't work out because the bitmap is a PlatformDevice which // can't actually be copied. const SkBitmap& bmp = temp_canvas.getTopPlatformDevice().accessBitmap(false); #elif defined(OS_LINUX) SkBitmap bmp = backing_store->PaintRectToBitmap( gfx::Rect(0, 0, backing_store->size().width(), backing_store->size().height())); #elif defined(OS_MACOSX) SkBitmap bmp; NOTIMPLEMENTED(); #endif result = skia::ImageOperations::DownsampleByTwoUntilSize( bmp, kThumbnailWidth, kThumbnailHeight); #if defined(OS_WIN) // This is a bit subtle. SkBitmaps are refcounted, but the magic ones in // PlatformCanvas on Windows can't be ssigned to SkBitmap with proper // refcounting. If the bitmap doesn't change, then the downsampler will // return the input bitmap, which will be the reference to the weird // PlatformCanvas one insetad of a regular one. To get a regular refcounted // bitmap, we need to copy it. if (bmp.width() == result.width() && bmp.height() == result.height()) bmp.copyTo(&result, SkBitmap::kARGB_8888_Config); #endif HISTOGRAM_TIMES(kThumbnailHistogramName, base::TimeTicks::Now() - begin_compute_thumbnail); return result; } } // namespace ThumbnailGenerator::ThumbnailGenerator() : no_timeout_(false) { // The BrowserProcessImpl creates this non-lazily. If you add nontrivial // stuff here, be sure to convert it to being lazily created. // // We don't register for notifications here since BrowserProcessImpl creates // us before the NotificationService is. } ThumbnailGenerator::~ThumbnailGenerator() { } void ThumbnailGenerator::StartThumbnailing() { if (registrar_.IsEmpty()) { // Even though we deal in RenderWidgetHosts, we only care about its // subclass, RenderViewHost when it is in a tab. We don't make thumbnails // for RenderViewHosts that aren't in tabs, or RenderWidgetHosts that // aren't views like select popups. registrar_.Add(this, NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB, NotificationService::AllSources()); registrar_.Add(this, NotificationType::RENDER_WIDGET_VISIBILITY_CHANGED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); } } SkBitmap ThumbnailGenerator::GetThumbnailForRenderer( RenderWidgetHost* renderer) const { // Return a cached one if we have it and it's still valid. This will only be // valid when there used to be a backing store, but there isn't now. WidgetThumbnail* wt = GetDataForHost(renderer); if (!wt->thumbnail.isNull() && (no_timeout_ || base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) < wt->last_shown)) return wt->thumbnail; BackingStore* backing_store = renderer->GetBackingStore(false); if (!backing_store) return SkBitmap(); // Save this thumbnail in case we need to use it again soon. It will be // invalidated on the next paint. wt->thumbnail = GetThumbnailForBackingStore(backing_store); return wt->thumbnail; } void ThumbnailGenerator::WidgetWillDestroyBackingStore( RenderWidgetHost* widget, BackingStore* backing_store) { // Since the backing store is going away, we need to save it as a thumbnail. WidgetThumbnail* wt = GetDataForHost(widget); // If there is already a thumbnail on the RWH that's visible, it means that // not enough time has elapsed since being shown, and we can ignore generating // a new one. if (!wt->thumbnail.isNull()) return; // Save a scaled-down image of the page in case we're asked for the thumbnail // when there is no RenderViewHost. If this fails, we don't want to overwrite // an existing thumbnail. SkBitmap new_thumbnail = GetThumbnailForBackingStore(backing_store); if (!new_thumbnail.isNull()) wt->thumbnail = new_thumbnail; } void ThumbnailGenerator::WidgetDidUpdateBackingStore( RenderWidgetHost* widget) { // Clear the current thumbnail since it's no longer valid. WidgetThumbnail* wt = GetThumbnailAccessor()->GetProperty( widget->property_bag()); if (!wt) return; // Nothing to do. // If this operation is within the time slop after being shown, keep the // existing thumbnail. if (no_timeout_ || base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) < wt->last_shown) return; // TODO(brettw) schedule thumbnail generation for this renderer in // case we don't get a paint for it after the time slop, but it's // still visible. // Clear the thumbnail, since it's now out of date. wt->thumbnail = SkBitmap(); } void ThumbnailGenerator::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB: { // Install our observer for all new RVHs. RenderViewHost* renderer = Details<RenderViewHost>(details).ptr(); renderer->set_painting_observer(this); break; } case NotificationType::RENDER_WIDGET_VISIBILITY_CHANGED: if (*Details<bool>(details).ptr()) WidgetShown(Source<RenderWidgetHost>(source).ptr()); else WidgetHidden(Source<RenderWidgetHost>(source).ptr()); break; case NotificationType::RENDER_WIDGET_HOST_DESTROYED: WidgetDestroyed(Source<RenderWidgetHost>(source).ptr()); break; default: NOTREACHED(); } } void ThumbnailGenerator::WidgetShown(RenderWidgetHost* widget) { WidgetThumbnail* wt = GetDataForHost(widget); wt->last_shown = base::TimeTicks::Now(); // If there is no thumbnail (like we're displaying a background tab for the // first time), then we don't have do to invalidate the existing one. if (wt->thumbnail.isNull()) return; std::vector<RenderWidgetHost*>::iterator found = std::find(shown_hosts_.begin(), shown_hosts_.end(), widget); if (found != shown_hosts_.end()) { NOTREACHED() << "Showing a RWH we already think is shown"; shown_hosts_.erase(found); } shown_hosts_.push_back(widget); // Keep the old thumbnail for a small amount of time after the tab has been // shown. This is so in case it's hidden quickly again, we don't waste any // work regenerating it. if (timer_.IsRunning()) return; timer_.Start(base::TimeDelta::FromMilliseconds( no_timeout_ ? 0 : kVisibilitySlopMS), this, &ThumbnailGenerator::ShownDelayHandler); } void ThumbnailGenerator::WidgetHidden(RenderWidgetHost* widget) { WidgetThumbnail* wt = GetDataForHost(widget); wt->last_hidden = base::TimeTicks::Now(); // If the tab is on the list of ones to invalidate the thumbnail, we need to // remove it. EraseHostFromShownList(widget); // There may still be a valid cached thumbnail on the RWH, so we don't need to // make a new one. if (!wt->thumbnail.isNull()) return; wt->thumbnail = GetThumbnailForRenderer(widget); } void ThumbnailGenerator::WidgetDestroyed(RenderWidgetHost* widget) { EraseHostFromShownList(widget); } void ThumbnailGenerator::ShownDelayHandler() { base::TimeTicks threshold = base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS); // Check the list of all pending RWHs (normally only one) to see if any of // their times have expired. for (size_t i = 0; i < shown_hosts_.size(); i++) { WidgetThumbnail* wt = GetDataForHost(shown_hosts_[i]); if (no_timeout_ || wt->last_shown <= threshold) { // This thumbnail has expired, delete it. wt->thumbnail = SkBitmap(); shown_hosts_.erase(shown_hosts_.begin() + i); i--; } } // We need to schedule another run if there are still items in the list to // process. We use half the timeout for these re-runs to catch the items // that were added since the timer was run the first time. if (!shown_hosts_.empty()) { DCHECK(!no_timeout_); timer_.Start(base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) / 2, this, &ThumbnailGenerator::ShownDelayHandler); } } void ThumbnailGenerator::EraseHostFromShownList(RenderWidgetHost* widget) { std::vector<RenderWidgetHost*>::iterator found = std::find(shown_hosts_.begin(), shown_hosts_.end(), widget); if (found != shown_hosts_.end()) shown_hosts_.erase(found); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "chrome/common/url_constants.h" LoginUIService::LoginUIService(Profile* profile) : ui_(NULL), profile_(profile) { } LoginUIService::~LoginUIService() {} void LoginUIService::AddObserver(LoginUIService::Observer* observer) { observer_list_.AddObserver(observer); } void LoginUIService::RemoveObserver(LoginUIService::Observer* observer) { observer_list_.RemoveObserver(observer); } void LoginUIService::SetLoginUI(LoginUI* ui) { DCHECK(!current_login_ui() || current_login_ui() == ui); ui_ = ui; FOR_EACH_OBSERVER(Observer, observer_list_, OnLoginUIShown(ui_)); } void LoginUIService::LoginUIClosed(LoginUI* ui) { if (current_login_ui() != ui) return; ui_ = NULL; FOR_EACH_OBSERVER(Observer, observer_list_, OnLoginUIClosed(ui)); } void LoginUIService::ShowLoginPopup() { if (current_login_ui()) { current_login_ui()->FocusUI(); return; } Browser* browser = new Browser(Browser::CreateParams(Browser::TYPE_POPUP, profile_)); // TODO(munjal): Change the source from SOURCE_NTP_LINK to something else // once we have added a new source for extension API. GURL signin_url(SyncPromoUI::GetSyncPromoURL(GURL(), SyncPromoUI::SOURCE_NTP_LINK, true)); chrome::NavigateParams params(browser, signin_url, content::PAGE_TRANSITION_AUTO_TOPLEVEL); params.disposition = CURRENT_TAB; params.window_action = chrome::NavigateParams::SHOW_WINDOW; chrome::Navigate(&params); } <commit_msg>Force alternative path for ShowLoginPopup to use the active desktop to create the login popup.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "chrome/common/url_constants.h" LoginUIService::LoginUIService(Profile* profile) : ui_(NULL), profile_(profile) { } LoginUIService::~LoginUIService() {} void LoginUIService::AddObserver(LoginUIService::Observer* observer) { observer_list_.AddObserver(observer); } void LoginUIService::RemoveObserver(LoginUIService::Observer* observer) { observer_list_.RemoveObserver(observer); } void LoginUIService::SetLoginUI(LoginUI* ui) { DCHECK(!current_login_ui() || current_login_ui() == ui); ui_ = ui; FOR_EACH_OBSERVER(Observer, observer_list_, OnLoginUIShown(ui_)); } void LoginUIService::LoginUIClosed(LoginUI* ui) { if (current_login_ui() != ui) return; ui_ = NULL; FOR_EACH_OBSERVER(Observer, observer_list_, OnLoginUIClosed(ui)); } void LoginUIService::ShowLoginPopup() { if (current_login_ui()) { current_login_ui()->FocusUI(); return; } Browser* browser = new Browser(Browser::CreateParams(Browser::TYPE_POPUP, profile_, chrome::GetActiveDesktop())); // TODO(munjal): Change the source from SOURCE_NTP_LINK to something else // once we have added a new source for extension API. GURL signin_url(SyncPromoUI::GetSyncPromoURL(GURL(), SyncPromoUI::SOURCE_NTP_LINK, true)); chrome::NavigateParams params(browser, signin_url, content::PAGE_TRANSITION_AUTO_TOPLEVEL); params.disposition = CURRENT_TAB; params.window_action = chrome::NavigateParams::SHOW_WINDOW; chrome::Navigate(&params); } <|endoftext|>
<commit_before>#include "mitkMovieGenerator.h" #include <GL/gl.h> bool mitk::MovieGenerator::WriteMovie() { bool ok = false; if (m_stepper) { m_stepper->First(); ok = InitGenerator(); if (!ok) return false; int imgSize = 3 * m_width * m_height; printf( "Video size = %i x %i\n", m_width, m_height ); BYTE *data = new BYTE[imgSize]; for (int i=0; i<m_stepper->GetSteps(); i++) { if (m_renderer) m_renderer->MakeCurrent(); glReadPixels( 0, 0, m_width, m_height, GL_BGR_EXT, GL_UNSIGNED_BYTE, (void*)data ); AddFrame( data ); m_stepper->Next(); } ok = TerminateGenerator(); delete[] data; } return ok; }<commit_msg>FIX: data type "BYTE" changed to "glByte"<commit_after>#include "mitkMovieGenerator.h" #include <GL/gl.h> bool mitk::MovieGenerator::WriteMovie() { bool ok = false; if (m_stepper) { m_stepper->First(); ok = InitGenerator(); if (!ok) return false; int imgSize = 3 * m_width * m_height; printf( "Video size = %i x %i\n", m_width, m_height ); GLbyte *data = new GLbyte[imgSize]; for (int i=0; i<m_stepper->GetSteps(); i++) { if (m_renderer) m_renderer->MakeCurrent(); glReadPixels( 0, 0, m_width, m_height, GL_BGR_EXT, GL_UNSIGNED_BYTE, (void*)data ); AddFrame( data ); m_stepper->Next(); } ok = TerminateGenerator(); delete[] data; } return ok; }<|endoftext|>
<commit_before>//===- llvm/unittest/ADT/ValueMapTest.cpp - ValueMap unit tests -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ValueMap.h" #include "llvm/Instructions.h" #include "llvm/LLVMContext.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Config/config.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture template<typename T> class ValueMapTest : public testing::Test { protected: Constant *ConstantV; OwningPtr<BitCastInst> BitcastV; OwningPtr<BinaryOperator> AddV; ValueMapTest() : ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)), BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))), AddV(BinaryOperator::CreateAdd(ConstantV, ConstantV)) { } }; // Run everything on Value*, a subtype to make sure that casting works as // expected, and a const subtype to make sure we cast const correctly. typedef ::testing::Types<Value, Instruction, const Instruction> KeyTypes; TYPED_TEST_CASE(ValueMapTest, KeyTypes); TYPED_TEST(ValueMapTest, Null) { ValueMap<TypeParam*, int> VM1; VM1[NULL] = 7; EXPECT_EQ(7, VM1.lookup(NULL)); } TYPED_TEST(ValueMapTest, FollowsValue) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->AddV.get())); EXPECT_EQ(0, VM.count(this->BitcastV.get())); this->AddV.reset(); EXPECT_EQ(0, VM.count(this->AddV.get())); EXPECT_EQ(0, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); } TYPED_TEST(ValueMapTest, OperationsWork) { ValueMap<TypeParam*, int> VM; ValueMap<TypeParam*, int> VM2(16); (void)VM2; typename ValueMapConfig<TypeParam*>::ExtraData Data; ValueMap<TypeParam*, int> VM3(Data, 16); (void)VM3; EXPECT_TRUE(VM.empty()); VM[this->BitcastV.get()] = 7; // Find: typename ValueMap<TypeParam*, int>::iterator I = VM.find(this->BitcastV.get()); ASSERT_TRUE(I != VM.end()); EXPECT_EQ(BitcastV.get(), I->first); EXPECT_EQ(7, I->second); EXPECT_TRUE(VM.find(AddV.get()) == VM.end()); // Const find: const ValueMap<TypeParam*, int> &CVM = VM; typename ValueMap<TypeParam*, int>::const_iterator CI = CVM.find(this->BitcastV.get()); ASSERT_TRUE(CI != CVM.end()); EXPECT_EQ(BitcastV.get(), CI->first); EXPECT_EQ(7, CI->second); EXPECT_TRUE(CVM.find(this->AddV.get()) == CVM.end()); // Insert: std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult1 = VM.insert(std::make_pair(this->AddV.get(), 3)); EXPECT_EQ(/*->this*/AddV.get(), InsertResult1.first->first); EXPECT_EQ(3, InsertResult1.first->second); EXPECT_TRUE(InsertResult1.second); EXPECT_EQ(true, VM.count(this->AddV.get())); std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult2 = VM.insert(std::make_pair(this->AddV.get(), 5)); EXPECT_EQ(/*this->*/AddV.get(), InsertResult2.first->first); EXPECT_EQ(3, InsertResult2.first->second); EXPECT_FALSE(InsertResult2.second); // Erase: VM.erase(InsertResult2.first); EXPECT_EQ(0U, VM.count(this->AddV.get())); EXPECT_EQ(1U, VM.count(this->BitcastV.get())); VM.erase(this->BitcastV.get()); EXPECT_EQ(0U, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); // Range insert: SmallVector<std::pair<Instruction*, int>, 2> Elems; Elems.push_back(std::make_pair(this->AddV.get(), 1)); Elems.push_back(std::make_pair(this->BitcastV.get(), 2)); VM.insert(Elems.begin(), Elems.end()); EXPECT_EQ(1, VM.lookup(this->AddV.get())); EXPECT_EQ(2, VM.lookup(this->BitcastV.get())); } template<typename ExpectedType, typename VarType> void CompileAssertHasType(VarType) { typedef char assert[is_same<ExpectedType, VarType>::value ? 1 : -1]; } TYPED_TEST(ValueMapTest, Iteration) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 2; VM[this->AddV.get()] = 3; size_t size = 0; for (typename ValueMap<TypeParam*, int>::iterator I = VM.begin(), E = VM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 2) { EXPECT_EQ(/*this->*/BitcastV.get(), I->first); I->second = 5; } else if (I->second == 3) { EXPECT_EQ(/*this->*/AddV.get(), I->first); I->second = 6; } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); EXPECT_EQ(5, VM[this->BitcastV.get()]); EXPECT_EQ(6, VM[this->AddV.get()]); size = 0; // Cast to const ValueMap to avoid a bug in DenseMap's iterators. const ValueMap<TypeParam*, int>& CVM = VM; for (typename ValueMap<TypeParam*, int>::const_iterator I = CVM.begin(), E = CVM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 5) { EXPECT_EQ(/*this->*/BitcastV.get(), I->first); } else if (I->second == 6) { EXPECT_EQ(/*this->*/AddV.get(), I->first); } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); } TYPED_TEST(ValueMapTest, DefaultCollisionBehavior) { // By default, we overwrite the old value with the replaced value. ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; VM[this->AddV.get()] = 9; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, VM.count(this->BitcastV.get())); EXPECT_EQ(9, VM.lookup(this->AddV.get())); } TYPED_TEST(ValueMapTest, ConfiguredCollisionBehavior) { // TODO: Implement this when someone needs it. } template<typename KeyT> struct LockMutex : ValueMapConfig<KeyT> { struct ExtraData { sys::Mutex *M; bool *CalledRAUW; bool *CalledDeleted; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { *Data.CalledRAUW = true; EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked."; } static void onDelete(const ExtraData &Data, KeyT Old) { *Data.CalledDeleted = true; EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked."; } static sys::Mutex *getMutex(const ExtraData &Data) { return Data.M; } }; #if ENABLE_THREADS TYPED_TEST(ValueMapTest, LocksMutex) { sys::Mutex M(false); // Not recursive. bool CalledRAUW = false, CalledDeleted = false; typename LockMutex<TypeParam*>::ExtraData Data = {&M, &CalledRAUW, &CalledDeleted}; ValueMap<TypeParam*, int, LockMutex<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); this->AddV.reset(); EXPECT_TRUE(CalledRAUW); EXPECT_TRUE(CalledDeleted); } #endif template<typename KeyT> struct NoFollow : ValueMapConfig<KeyT> { enum { FollowRAUW = false }; }; TYPED_TEST(ValueMapTest, NoFollowRAUW) { ValueMap<TypeParam*, int, NoFollow<TypeParam*> > VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->AddV.reset(); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->BitcastV.reset(); EXPECT_EQ(0, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); EXPECT_EQ(0U, VM.size()); } template<typename KeyT> struct CountOps : ValueMapConfig<KeyT> { struct ExtraData { int *Deletions; int *RAUWs; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { ++*Data.RAUWs; } static void onDelete(const ExtraData &Data, KeyT Old) { ++*Data.Deletions; } }; TYPED_TEST(ValueMapTest, CallsConfig) { int Deletions = 0, RAUWs = 0; typename CountOps<TypeParam*>::ExtraData Data = {&Deletions, &RAUWs}; ValueMap<TypeParam*, int, CountOps<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, Deletions); EXPECT_EQ(1, RAUWs); this->AddV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); this->BitcastV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); } template<typename KeyT> struct ModifyingConfig : ValueMapConfig<KeyT> { // We'll put a pointer here back to the ValueMap this key is in, so // that we can modify it (and clobber *this) before the ValueMap // tries to do the same modification. In previous versions of // ValueMap, that exploded. typedef ValueMap<KeyT, int, ModifyingConfig<KeyT> > **ExtraData; static void onRAUW(ExtraData Map, KeyT Old, KeyT New) { (*Map)->erase(Old); } static void onDelete(ExtraData Map, KeyT Old) { (*Map)->erase(Old); } }; TYPED_TEST(ValueMapTest, SurvivesModificationByConfig) { ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > *MapAddress; ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > VM(&MapAddress); MapAddress = &VM; // Now the ModifyingConfig can modify the Map inside a callback. VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_FALSE(VM.count(this->BitcastV.get())); EXPECT_FALSE(VM.count(this->AddV.get())); VM[this->AddV.get()] = 7; this->AddV.reset(); EXPECT_FALSE(VM.count(this->AddV.get())); } } <commit_msg>Revert 119600 to unbreak the build. Francois, please investigate.<commit_after>//===- llvm/unittest/ADT/ValueMapTest.cpp - ValueMap unit tests -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ValueMap.h" #include "llvm/Instructions.h" #include "llvm/LLVMContext.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Config/config.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture template<typename T> class ValueMapTest : public testing::Test { protected: Constant *ConstantV; OwningPtr<BitCastInst> BitcastV; OwningPtr<BinaryOperator> AddV; ValueMapTest() : ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)), BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))), AddV(BinaryOperator::CreateAdd(ConstantV, ConstantV)) { } }; // Run everything on Value*, a subtype to make sure that casting works as // expected, and a const subtype to make sure we cast const correctly. typedef ::testing::Types<Value, Instruction, const Instruction> KeyTypes; TYPED_TEST_CASE(ValueMapTest, KeyTypes); TYPED_TEST(ValueMapTest, Null) { ValueMap<TypeParam*, int> VM1; VM1[NULL] = 7; EXPECT_EQ(7, VM1.lookup(NULL)); } TYPED_TEST(ValueMapTest, FollowsValue) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->AddV.get())); EXPECT_EQ(0, VM.count(this->BitcastV.get())); this->AddV.reset(); EXPECT_EQ(0, VM.count(this->AddV.get())); EXPECT_EQ(0, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); } TYPED_TEST(ValueMapTest, OperationsWork) { ValueMap<TypeParam*, int> VM; ValueMap<TypeParam*, int> VM2(16); (void)VM2; typename ValueMapConfig<TypeParam*>::ExtraData Data; ValueMap<TypeParam*, int> VM3(Data, 16); (void)VM3; EXPECT_TRUE(VM.empty()); VM[this->BitcastV.get()] = 7; // Find: typename ValueMap<TypeParam*, int>::iterator I = VM.find(this->BitcastV.get()); ASSERT_TRUE(I != VM.end()); EXPECT_EQ(this->BitcastV.get(), I->first); EXPECT_EQ(7, I->second); EXPECT_TRUE(VM.find(this->AddV.get()) == VM.end()); // Const find: const ValueMap<TypeParam*, int> &CVM = VM; typename ValueMap<TypeParam*, int>::const_iterator CI = CVM.find(this->BitcastV.get()); ASSERT_TRUE(CI != CVM.end()); EXPECT_EQ(this->BitcastV.get(), CI->first); EXPECT_EQ(7, CI->second); EXPECT_TRUE(CVM.find(this->AddV.get()) == CVM.end()); // Insert: std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult1 = VM.insert(std::make_pair(this->AddV.get(), 3)); EXPECT_EQ(this->AddV.get(), InsertResult1.first->first); EXPECT_EQ(3, InsertResult1.first->second); EXPECT_TRUE(InsertResult1.second); EXPECT_EQ(true, VM.count(this->AddV.get())); std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult2 = VM.insert(std::make_pair(this->AddV.get(), 5)); EXPECT_EQ(this->AddV.get(), InsertResult2.first->first); EXPECT_EQ(3, InsertResult2.first->second); EXPECT_FALSE(InsertResult2.second); // Erase: VM.erase(InsertResult2.first); EXPECT_EQ(0U, VM.count(this->AddV.get())); EXPECT_EQ(1U, VM.count(this->BitcastV.get())); VM.erase(this->BitcastV.get()); EXPECT_EQ(0U, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); // Range insert: SmallVector<std::pair<Instruction*, int>, 2> Elems; Elems.push_back(std::make_pair(this->AddV.get(), 1)); Elems.push_back(std::make_pair(this->BitcastV.get(), 2)); VM.insert(Elems.begin(), Elems.end()); EXPECT_EQ(1, VM.lookup(this->AddV.get())); EXPECT_EQ(2, VM.lookup(this->BitcastV.get())); } template<typename ExpectedType, typename VarType> void CompileAssertHasType(VarType) { typedef char assert[is_same<ExpectedType, VarType>::value ? 1 : -1]; } TYPED_TEST(ValueMapTest, Iteration) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 2; VM[this->AddV.get()] = 3; size_t size = 0; for (typename ValueMap<TypeParam*, int>::iterator I = VM.begin(), E = VM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 2) { EXPECT_EQ(this->BitcastV.get(), I->first); I->second = 5; } else if (I->second == 3) { EXPECT_EQ(this->AddV.get(), I->first); I->second = 6; } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); EXPECT_EQ(5, VM[this->BitcastV.get()]); EXPECT_EQ(6, VM[this->AddV.get()]); size = 0; // Cast to const ValueMap to avoid a bug in DenseMap's iterators. const ValueMap<TypeParam*, int>& CVM = VM; for (typename ValueMap<TypeParam*, int>::const_iterator I = CVM.begin(), E = CVM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 5) { EXPECT_EQ(this->BitcastV.get(), I->first); } else if (I->second == 6) { EXPECT_EQ(this->AddV.get(), I->first); } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); } TYPED_TEST(ValueMapTest, DefaultCollisionBehavior) { // By default, we overwrite the old value with the replaced value. ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; VM[this->AddV.get()] = 9; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, VM.count(this->BitcastV.get())); EXPECT_EQ(9, VM.lookup(this->AddV.get())); } TYPED_TEST(ValueMapTest, ConfiguredCollisionBehavior) { // TODO: Implement this when someone needs it. } template<typename KeyT> struct LockMutex : ValueMapConfig<KeyT> { struct ExtraData { sys::Mutex *M; bool *CalledRAUW; bool *CalledDeleted; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { *Data.CalledRAUW = true; EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked."; } static void onDelete(const ExtraData &Data, KeyT Old) { *Data.CalledDeleted = true; EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked."; } static sys::Mutex *getMutex(const ExtraData &Data) { return Data.M; } }; #if ENABLE_THREADS TYPED_TEST(ValueMapTest, LocksMutex) { sys::Mutex M(false); // Not recursive. bool CalledRAUW = false, CalledDeleted = false; typename LockMutex<TypeParam*>::ExtraData Data = {&M, &CalledRAUW, &CalledDeleted}; ValueMap<TypeParam*, int, LockMutex<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); this->AddV.reset(); EXPECT_TRUE(CalledRAUW); EXPECT_TRUE(CalledDeleted); } #endif template<typename KeyT> struct NoFollow : ValueMapConfig<KeyT> { enum { FollowRAUW = false }; }; TYPED_TEST(ValueMapTest, NoFollowRAUW) { ValueMap<TypeParam*, int, NoFollow<TypeParam*> > VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->AddV.reset(); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->BitcastV.reset(); EXPECT_EQ(0, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); EXPECT_EQ(0U, VM.size()); } template<typename KeyT> struct CountOps : ValueMapConfig<KeyT> { struct ExtraData { int *Deletions; int *RAUWs; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { ++*Data.RAUWs; } static void onDelete(const ExtraData &Data, KeyT Old) { ++*Data.Deletions; } }; TYPED_TEST(ValueMapTest, CallsConfig) { int Deletions = 0, RAUWs = 0; typename CountOps<TypeParam*>::ExtraData Data = {&Deletions, &RAUWs}; ValueMap<TypeParam*, int, CountOps<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, Deletions); EXPECT_EQ(1, RAUWs); this->AddV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); this->BitcastV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); } template<typename KeyT> struct ModifyingConfig : ValueMapConfig<KeyT> { // We'll put a pointer here back to the ValueMap this key is in, so // that we can modify it (and clobber *this) before the ValueMap // tries to do the same modification. In previous versions of // ValueMap, that exploded. typedef ValueMap<KeyT, int, ModifyingConfig<KeyT> > **ExtraData; static void onRAUW(ExtraData Map, KeyT Old, KeyT New) { (*Map)->erase(Old); } static void onDelete(ExtraData Map, KeyT Old) { (*Map)->erase(Old); } }; TYPED_TEST(ValueMapTest, SurvivesModificationByConfig) { ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > *MapAddress; ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > VM(&MapAddress); MapAddress = &VM; // Now the ModifyingConfig can modify the Map inside a callback. VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_FALSE(VM.count(this->BitcastV.get())); EXPECT_FALSE(VM.count(this->AddV.get())); VM[this->AddV.get()] = 7; this->AddV.reset(); EXPECT_FALSE(VM.count(this->AddV.get())); } } <|endoftext|>
<commit_before>//===-- SourceCodeTests.cpp ------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Evaluating scoring functions isn't a great fit for assert-based tests. // For interesting cases, both exact scores and "X beats Y" are too brittle to // make good hard assertions. // // Here we test the signal extraction and sanity-check that signals point in // the right direction. This should be supplemented by quality metrics which // we can compute from a corpus of queries and preferred rankings. // //===----------------------------------------------------------------------===// #include "Quality.h" #include "TestTU.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace clang { namespace clangd { namespace { TEST(QualityTests, SymbolQualitySignalExtraction) { auto Header = TestTU::withHeaderCode(R"cpp( int x; [[deprecated]] int f() { return x; } )cpp"); auto Symbols = Header.headerSymbols(); auto AST = Header.build(); SymbolQualitySignals Quality; Quality.merge(findSymbol(Symbols, "x")); EXPECT_FALSE(Quality.Deprecated); EXPECT_EQ(Quality.SemaCCPriority, SymbolQualitySignals().SemaCCPriority); EXPECT_EQ(Quality.References, SymbolQualitySignals().References); Symbol F = findSymbol(Symbols, "f"); F.References = 24; // TestTU doesn't count references, so fake it. Quality = {}; Quality.merge(F); EXPECT_FALSE(Quality.Deprecated); // FIXME: Include deprecated bit in index. EXPECT_EQ(Quality.SemaCCPriority, SymbolQualitySignals().SemaCCPriority); EXPECT_EQ(Quality.References, 24u); Quality = {}; Quality.merge(CodeCompletionResult(&findDecl(AST, "f"), /*Priority=*/42)); EXPECT_TRUE(Quality.Deprecated); EXPECT_EQ(Quality.SemaCCPriority, 42u); EXPECT_EQ(Quality.References, SymbolQualitySignals().References); } TEST(QualityTests, SymbolRelevanceSignalExtraction) { auto AST = TestTU::withHeaderCode(R"cpp( [[deprecated]] int f() { return 0; } )cpp") .build(); SymbolRelevanceSignals Relevance; Relevance.merge(CodeCompletionResult(&findDecl(AST, "f"), /*Priority=*/42, nullptr, false, /*Accessible=*/false)); EXPECT_EQ(Relevance.NameMatch, SymbolRelevanceSignals().NameMatch); EXPECT_TRUE(Relevance.Forbidden); } // Do the signals move the scores in the direction we expect? TEST(QualityTests, SymbolQualitySignalsSanity) { SymbolQualitySignals Default; EXPECT_EQ(Default.evaluate(), 1); SymbolQualitySignals Deprecated; Deprecated.Deprecated = true; EXPECT_LT(Deprecated.evaluate(), Default.evaluate()); SymbolQualitySignals WithReferences, ManyReferences; WithReferences.References = 10; ManyReferences.References = 1000; EXPECT_GT(WithReferences.evaluate(), Default.evaluate()); EXPECT_GT(ManyReferences.evaluate(), WithReferences.evaluate()); SymbolQualitySignals LowPriority, HighPriority; LowPriority.SemaCCPriority = 60; HighPriority.SemaCCPriority = 20; EXPECT_GT(HighPriority.evaluate(), Default.evaluate()); EXPECT_LT(LowPriority.evaluate(), Default.evaluate()); } TEST(QualityTests, SymbolRelevanceSignalsSanity) { SymbolRelevanceSignals Default; EXPECT_EQ(Default.evaluate(), 1); SymbolRelevanceSignals Forbidden; Forbidden.Forbidden = true; EXPECT_LT(Forbidden.evaluate(), Default.evaluate()); SymbolRelevanceSignals PoorNameMatch; PoorNameMatch.NameMatch = 0.2; EXPECT_LT(PoorNameMatch.evaluate(), Default.evaluate()); } TEST(QualityTests, SortText) { EXPECT_LT(sortText(std::numeric_limits<float>::infinity()), sortText(1000.2)); EXPECT_LT(sortText(1000.2), sortText(1)); EXPECT_LT(sortText(1), sortText(0.3)); EXPECT_LT(sortText(0.3), sortText(0)); EXPECT_LT(sortText(0), sortText(-10)); EXPECT_LT(sortText(-10), sortText(-std::numeric_limits<float>::infinity())); EXPECT_LT(sortText(1, "z"), sortText(0, "a")); EXPECT_LT(sortText(0, "a"), sortText(0, "z")); } } // namespace } // namespace clangd } // namespace clang <commit_msg>Silence more truncation warnings; NFC.<commit_after>//===-- SourceCodeTests.cpp ------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Evaluating scoring functions isn't a great fit for assert-based tests. // For interesting cases, both exact scores and "X beats Y" are too brittle to // make good hard assertions. // // Here we test the signal extraction and sanity-check that signals point in // the right direction. This should be supplemented by quality metrics which // we can compute from a corpus of queries and preferred rankings. // //===----------------------------------------------------------------------===// #include "Quality.h" #include "TestTU.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace clang { namespace clangd { namespace { TEST(QualityTests, SymbolQualitySignalExtraction) { auto Header = TestTU::withHeaderCode(R"cpp( int x; [[deprecated]] int f() { return x; } )cpp"); auto Symbols = Header.headerSymbols(); auto AST = Header.build(); SymbolQualitySignals Quality; Quality.merge(findSymbol(Symbols, "x")); EXPECT_FALSE(Quality.Deprecated); EXPECT_EQ(Quality.SemaCCPriority, SymbolQualitySignals().SemaCCPriority); EXPECT_EQ(Quality.References, SymbolQualitySignals().References); Symbol F = findSymbol(Symbols, "f"); F.References = 24; // TestTU doesn't count references, so fake it. Quality = {}; Quality.merge(F); EXPECT_FALSE(Quality.Deprecated); // FIXME: Include deprecated bit in index. EXPECT_EQ(Quality.SemaCCPriority, SymbolQualitySignals().SemaCCPriority); EXPECT_EQ(Quality.References, 24u); Quality = {}; Quality.merge(CodeCompletionResult(&findDecl(AST, "f"), /*Priority=*/42)); EXPECT_TRUE(Quality.Deprecated); EXPECT_EQ(Quality.SemaCCPriority, 42u); EXPECT_EQ(Quality.References, SymbolQualitySignals().References); } TEST(QualityTests, SymbolRelevanceSignalExtraction) { auto AST = TestTU::withHeaderCode(R"cpp( [[deprecated]] int f() { return 0; } )cpp") .build(); SymbolRelevanceSignals Relevance; Relevance.merge(CodeCompletionResult(&findDecl(AST, "f"), /*Priority=*/42, nullptr, false, /*Accessible=*/false)); EXPECT_EQ(Relevance.NameMatch, SymbolRelevanceSignals().NameMatch); EXPECT_TRUE(Relevance.Forbidden); } // Do the signals move the scores in the direction we expect? TEST(QualityTests, SymbolQualitySignalsSanity) { SymbolQualitySignals Default; EXPECT_EQ(Default.evaluate(), 1); SymbolQualitySignals Deprecated; Deprecated.Deprecated = true; EXPECT_LT(Deprecated.evaluate(), Default.evaluate()); SymbolQualitySignals WithReferences, ManyReferences; WithReferences.References = 10; ManyReferences.References = 1000; EXPECT_GT(WithReferences.evaluate(), Default.evaluate()); EXPECT_GT(ManyReferences.evaluate(), WithReferences.evaluate()); SymbolQualitySignals LowPriority, HighPriority; LowPriority.SemaCCPriority = 60; HighPriority.SemaCCPriority = 20; EXPECT_GT(HighPriority.evaluate(), Default.evaluate()); EXPECT_LT(LowPriority.evaluate(), Default.evaluate()); } TEST(QualityTests, SymbolRelevanceSignalsSanity) { SymbolRelevanceSignals Default; EXPECT_EQ(Default.evaluate(), 1); SymbolRelevanceSignals Forbidden; Forbidden.Forbidden = true; EXPECT_LT(Forbidden.evaluate(), Default.evaluate()); SymbolRelevanceSignals PoorNameMatch; PoorNameMatch.NameMatch = 0.2f; EXPECT_LT(PoorNameMatch.evaluate(), Default.evaluate()); } TEST(QualityTests, SortText) { EXPECT_LT(sortText(std::numeric_limits<float>::infinity()), sortText(1000.2f)); EXPECT_LT(sortText(1000.2f), sortText(1)); EXPECT_LT(sortText(1), sortText(0.3f)); EXPECT_LT(sortText(0.3f), sortText(0)); EXPECT_LT(sortText(0), sortText(-10)); EXPECT_LT(sortText(-10), sortText(-std::numeric_limits<float>::infinity())); EXPECT_LT(sortText(1, "z"), sortText(0, "a")); EXPECT_LT(sortText(0, "a"), sortText(0, "z")); } } // namespace } // namespace clangd } // namespace clang <|endoftext|>
<commit_before>#include "MPITestFixture.h" #include "testparams.h" extern TestParams globalTestParams; using namespace std; using namespace clusterlib; /* * My user event handler. */ class MyUserEventHandler : public UserEventHandler { public: /* * Constructor. */ MyUserEventHandler(Notifyable *ntp, Event mask, ClientData cd) : UserEventHandler(ntp, mask, cd), m_counter(0), m_targetCounter(0) { } virtual void handleUserEvent(Event e) { cerr << "Got event " << e << " on Notifyable " << getNotifyable()->getKey() << ", client data " << getClientData() << endl; m_counter++; } void reset() { m_counter = 0; } int32_t getCounter() { return m_counter; } bool meetsCondition(Event e) { return (m_counter == m_targetCounter) ? true : false; } void setTargetCounter(int32_t t) { m_targetCounter = t; } private: /* * Counter for how many times the handler was * called. */ int32_t m_counter; /* * How many calls is the target (expected)? */ int32_t m_targetCounter; }; /* * Health checker. */ class UEHealthChecker : public HealthChecker { public: /* * Constructor. */ UEHealthChecker(Node *np, Client *cp) : HealthChecker(), mp_np(np), mp_cp(cp) {} /* * Check health and return a health report. */ virtual HealthReport checkHealth() { HealthReport hr(HealthReport::HS_HEALTHY, mp_np->getName() + " is healthy!"); return hr; } private: /* * The node for which we're reporting health. */ Node *mp_np; /* * The client for which we're reporting health. */ Client *mp_cp; }; /* * The test class. */ class ClusterlibUserEvents : public MPITestFixture { CPPUNIT_TEST_SUITE(ClusterlibUserEvents); CPPUNIT_TEST(testUserEvents1); CPPUNIT_TEST(testUserEvents2); CPPUNIT_TEST(testUserEvents3); CPPUNIT_TEST(testUserEvents4); CPPUNIT_TEST(testUserEvents5); CPPUNIT_TEST(testUserEvents6); CPPUNIT_TEST_SUITE_END(); public: /* * Constructor. */ ClusterlibUserEvents() : _factory(NULL), _client0(NULL), _app0(NULL), _grp0(NULL), _nod0(NULL), _dist0(NULL), _zk(NULL) { } /* Runs prior to each test */ virtual void setUp() { _factory = new Factory(globalTestParams.getZkServerPortList()); CPPUNIT_ASSERT(_factory != NULL); _zk = _factory->getRepository(); CPPUNIT_ASSERT(_zk != NULL); _client0 = _factory->createClient(); CPPUNIT_ASSERT(_client0 != NULL); _app0 = _client0->getRoot()->getApplication("foo-app", true); CPPUNIT_ASSERT(_app0 != NULL); _grp0 = _app0->getGroup("bar-group", true); CPPUNIT_ASSERT(_grp0 != NULL); _nod0 = _grp0->getNode("nod3", true); CPPUNIT_ASSERT(_nod0 != NULL); _dist0 = _grp0->getDataDistribution("dist1", true); CPPUNIT_ASSERT(_dist0 != NULL); } /* Runs after each test */ virtual void tearDown() { cleanAndBarrierMPITest(_factory, true); /* * Delete only the factory, that automatically deletes * all the other objects. */ if (_factory != NULL) { delete _factory; _factory = NULL; } _client0 = NULL; _app0 = NULL; _grp0 = NULL; _nod0 = NULL; _dist0 = NULL; } /* * The tests. */ void testUserEvents1() { initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents1"); /* * Register & unregister once. */ MyUserEventHandler *uehp = new MyUserEventHandler(_nod0, EN_CONNECTEDCHANGE, (void *) 0x3333); _client0->registerHandler(uehp); bool deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == true); deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == false); /* * Registering the same handler several times also works, * means it will be called several times! */ _client0->registerHandler(uehp); _client0->registerHandler(uehp); _client0->registerHandler(uehp); /* * Cancelling several times also works... */ deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == true); deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == true); deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == true); /* * Cancelling N+1 times does not work... */ deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == false); } void testUserEvents2() { /* * This test checks that all handlers are * called if there are multiple handlers * registered for a user event. */ initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents2"); /* * My handler. */ MyUserEventHandler *uehp = new MyUserEventHandler(_nod0, EN_CONNECTEDCHANGE, (void *) 0x3333); UEHealthChecker *hcp = new UEHealthChecker(_nod0, _client0); /* * Register 3 times. */ uehp->acquireLock(); uehp->setTargetCounter(3); _client0->registerHandler(uehp); _client0->registerHandler(uehp); _client0->registerHandler(uehp); /* * Create a health checker, create the "connected" znode, * and in the process, cause the EN_CONNECTED event * to happen on the node. */ _nod0->registerHealthChecker(hcp); /* * Wait for event propagation. */ bool res = uehp->waitUntilCondition(); CPPUNIT_ASSERT(res == true); /* * Event counter should be 3, since we registered the * handler 3 times. */ CPPUNIT_ASSERT(uehp->getCounter() == 3); uehp->setTargetCounter(6); /* * Unregister the handler, we should get 3 more event * deliveries. */ _nod0->unregisterHealthChecker(); /* * Wait for event propagation. */ res = uehp->waitUntilCondition(); CPPUNIT_ASSERT(res == true); /* * Event counter should now be at 6. */ CPPUNIT_ASSERT(uehp->getCounter() == 6); uehp->releaseLock(); /* * Clean up. */ delete uehp; delete hcp; } void testUserEvents3() { /* * This test checks that all handlers are * called if there are multiple handlers * registered for a user event. */ initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents3"); /* * My handler. */ MyUserEventHandler *uehp = new MyUserEventHandler(_nod0, EN_CONNECTEDCHANGE, (void *) 0x3333); UEHealthChecker *hcp = new UEHealthChecker(_nod0, _client0); /* * Register 3 times. */ uehp->acquireLock(); uehp->setTargetCounter(3); _client0->registerHandler(uehp); _client0->registerHandler(uehp); _client0->registerHandler(uehp); /* * Create a health checker, create the "connected" znode, * and in the process, cause the EN_CONNECTED event * to happen on the node. */ _nod0->registerHealthChecker(hcp); /* * Wait for event propagation. */ bool res = uehp->waitUntilCondition(); CPPUNIT_ASSERT(res == true); /* * Event counter should be 3, since we registered the * handler 3 times. */ CPPUNIT_ASSERT(uehp->getCounter() == 3); /* * Cancel *one* of the handlers. This means that the * connection events should be delivered to only 2 handlers. */ bool cancelled = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(cancelled == true); uehp->setTargetCounter(5); /* * Unregister the handler, we should get 2 more event * deliveries. */ _nod0->unregisterHealthChecker(); /* * Wait for event propagation. */ res = uehp->waitUntilCondition(); CPPUNIT_ASSERT(res == true); /* * Event counter should now be at 5. */ CPPUNIT_ASSERT(uehp->getCounter() == 5); /* * Clean up. */ uehp->releaseLock(); delete uehp; delete hcp; } void testUserEvents4() { initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents4"); /* * See whether an end event gets handled correctly. */ MyUserEventHandler ueh(_client0->getRoot(), EN_ENDEVENT, NULL); _client0->registerHandler(&ueh); /* * Wait for event propagation. The factory deletion should not * return till the EN_ENDEVENT has propagated, so we do not * wait explicitly. */ delete _factory; _factory = NULL; CPPUNIT_ASSERT(ueh.getCounter() == 1); } void testUserEvents5() { initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents5"); } void testUserEvents6() { initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents6"); } private: Factory *_factory; Client *_client0; Application *_app0; Group *_grp0; Node *_nod0; DataDistribution *_dist0; zk::ZooKeeperAdapter *_zk; }; /* Registers the fixture into the 'registry' */ CPPUNIT_TEST_SUITE_REGISTRATION(ClusterlibUserEvents); <commit_msg>[Bug 2801237] - Fix clusterlibUserEvents.cc regression problems.<commit_after>#include "MPITestFixture.h" #include "testparams.h" extern TestParams globalTestParams; using namespace std; using namespace clusterlib; /* * My user event handler. */ class MyUserEventHandler : public UserEventHandler { public: /* * Constructor. */ MyUserEventHandler(Notifyable *ntp, Event mask, ClientData cd) : UserEventHandler(ntp, mask, cd), m_counter(0), m_targetCounter(0) { } virtual void handleUserEvent(Event e) { cerr << "Got event " << e << " on Notifyable " << getNotifyable()->getKey() << ", client data " << getClientData() << endl; m_counter++; } void reset() { m_counter = 0; } int32_t getCounter() { return m_counter; } bool meetsCondition(Event e) { return (m_counter == m_targetCounter) ? true : false; } void setTargetCounter(int32_t t) { m_targetCounter = t; } private: /* * Counter for how many times the handler was * called. */ int32_t m_counter; /* * How many calls is the target (expected)? */ int32_t m_targetCounter; }; /* * Health checker. */ class UEHealthChecker : public HealthChecker { public: /* * Constructor. */ UEHealthChecker(Node *np, Client *cp) : HealthChecker(), mp_np(np), mp_cp(cp) { setMsecsPerCheckIfHealthy(500); setMsecsPerCheckIfUnhealthy(500); } /* * Check health and return a health report. */ virtual HealthReport checkHealth() { HealthReport hr(HealthReport::HS_HEALTHY, mp_np->getName() + " is healthy!"); return hr; } private: /* * The node for which we're reporting health. */ Node *mp_np; /* * The client for which we're reporting health. */ Client *mp_cp; }; /* * The test class. */ class ClusterlibUserEvents : public MPITestFixture { CPPUNIT_TEST_SUITE(ClusterlibUserEvents); CPPUNIT_TEST(testUserEvents1); CPPUNIT_TEST(testUserEvents2); CPPUNIT_TEST(testUserEvents3); CPPUNIT_TEST(testUserEvents4); CPPUNIT_TEST(testUserEvents5); CPPUNIT_TEST(testUserEvents6); CPPUNIT_TEST_SUITE_END(); public: /* * Constructor. */ ClusterlibUserEvents() : _factory(NULL), _client0(NULL), _app0(NULL), _grp0(NULL), _nod0(NULL), _dist0(NULL), _zk(NULL) { } /* Runs prior to each test */ virtual void setUp() { _factory = new Factory(globalTestParams.getZkServerPortList()); CPPUNIT_ASSERT(_factory != NULL); _zk = _factory->getRepository(); CPPUNIT_ASSERT(_zk != NULL); _client0 = _factory->createClient(); CPPUNIT_ASSERT(_client0 != NULL); _app0 = _client0->getRoot()->getApplication("foo-app", true); CPPUNIT_ASSERT(_app0 != NULL); _grp0 = _app0->getGroup("bar-group", true); CPPUNIT_ASSERT(_grp0 != NULL); _nod0 = _grp0->getNode("nod3", true); CPPUNIT_ASSERT(_nod0 != NULL); _dist0 = _grp0->getDataDistribution("dist1", true); CPPUNIT_ASSERT(_dist0 != NULL); } /* Runs after each test */ virtual void tearDown() { cleanAndBarrierMPITest(_factory, true); /* * Delete only the factory, that automatically deletes * all the other objects. */ if (_factory != NULL) { delete _factory; _factory = NULL; } _client0 = NULL; _app0 = NULL; _grp0 = NULL; _nod0 = NULL; _dist0 = NULL; } /* * The tests. */ void testUserEvents1() { initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents1"); /* * Register & unregister once. */ MyUserEventHandler *uehp = new MyUserEventHandler(_nod0, EN_CONNECTEDCHANGE, (void *) 0x3333); _client0->registerHandler(uehp); bool deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == true); deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == false); /* * Registering the same handler several times also works, * means it will be called several times! */ _client0->registerHandler(uehp); _client0->registerHandler(uehp); _client0->registerHandler(uehp); /* * Cancelling several times also works... */ deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == true); deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == true); deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == true); /* * Cancelling N+1 times does not work... */ deregged = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(deregged == false); } void testUserEvents2() { /* * This test checks that all handlers are * called if there are multiple handlers * registered for a user event. */ initializeAndBarrierMPITest(1, true, _factory, true, "testUserEvents2"); if (isMyRank(0)) { /* * My handler. */ MyUserEventHandler *uehp = new MyUserEventHandler(_nod0, EN_CONNECTEDCHANGE, (void *) 0x3333); UEHealthChecker *hcp = new UEHealthChecker(_nod0, _client0); /* * Register 3 times. */ uehp->acquireLock(); uehp->setTargetCounter(3); _client0->registerHandler(uehp); _client0->registerHandler(uehp); _client0->registerHandler(uehp); /* * Create a health checker, create the "connected" znode, * and in the process, cause the EN_CONNECTED event * to happen on the node. */ _nod0->registerHealthChecker(hcp); /* * Wait for event propagation. */ bool res = uehp->waitUntilCondition(); CPPUNIT_ASSERT(res == true); /* * Event counter should be 3, since we registered the * handler 3 times. */ CPPUNIT_ASSERT(uehp->getCounter() == 3); uehp->setTargetCounter(6); /* * Unregister the handler, we should get 3 more event * deliveries. */ _nod0->unregisterHealthChecker(); /* * Wait for event propagation. */ res = uehp->waitUntilCondition(); CPPUNIT_ASSERT(res == true); /* * Event counter should now be at 6. */ CPPUNIT_ASSERT(uehp->getCounter() == 6); uehp->releaseLock(); /* * Clean up. */ delete uehp; delete hcp; } } void testUserEvents3() { /* * This test checks that all handlers are * called if there are multiple handlers * registered for a user event. */ initializeAndBarrierMPITest(1, true, _factory, true, "testUserEvents3"); if (isMyRank(0)) { /* * My handler. */ MyUserEventHandler *uehp = new MyUserEventHandler(_nod0, EN_CONNECTEDCHANGE, (void *) 0x3333); UEHealthChecker *hcp = new UEHealthChecker(_nod0, _client0); /* * Register 3 times. */ uehp->acquireLock(); uehp->setTargetCounter(3); _client0->registerHandler(uehp); _client0->registerHandler(uehp); _client0->registerHandler(uehp); /* * Create a health checker, create the "connected" znode, * and in the process, cause the EN_CONNECTED event * to happen on the node. */ _nod0->registerHealthChecker(hcp); /* * Wait for event propagation. */ bool res = uehp->waitUntilCondition(); CPPUNIT_ASSERT(res == true); /* * Event counter should be 3, since we registered the * handler 3 times. */ CPPUNIT_ASSERT(uehp->getCounter() == 3); /* * Cancel *one* of the handlers. This means that the * connection events should be delivered to only 2 handlers. */ bool cancelled = _client0->cancelHandler(uehp); CPPUNIT_ASSERT(cancelled == true); uehp->setTargetCounter(5); /* * Unregister the handler, we should get 2 more event * deliveries. */ _nod0->unregisterHealthChecker(); /* * Wait for event propagation. */ res = uehp->waitUntilCondition(); CPPUNIT_ASSERT(res == true); /* * Event counter should now be at 5. */ CPPUNIT_ASSERT(uehp->getCounter() == 5); /* * Clean up. */ uehp->releaseLock(); delete uehp; delete hcp; } } void testUserEvents4() { initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents4"); /* * See whether an end event gets handled correctly. */ MyUserEventHandler ueh(_client0->getRoot(), EN_ENDEVENT, NULL); _client0->registerHandler(&ueh); /* * Wait for event propagation. The factory deletion should not * return till the EN_ENDEVENT has propagated, so we do not * wait explicitly. */ delete _factory; _factory = NULL; CPPUNIT_ASSERT(ueh.getCounter() == 1); } void testUserEvents5() { initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents5"); } void testUserEvents6() { initializeAndBarrierMPITest(-1, true, _factory, true, "testUserEvents6"); } private: Factory *_factory; Client *_client0; Application *_app0; Group *_grp0; Node *_nod0; DataDistribution *_dist0; zk::ZooKeeperAdapter *_zk; }; /* Registers the fixture into the 'registry' */ CPPUNIT_TEST_SUITE_REGISTRATION(ClusterlibUserEvents); <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: elementlist.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 10:01:25 $ * * 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 _ELEMENTLIST_HXX #define _ELEMENTLIST_HXX #include <vector> #include <sal/types.h> #include <cppuhelper/implbase1.hxx> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/xml/dom/XNode.hpp> #include <com/sun/star/xml/dom/XNodeList.hpp> #include "element.hxx" #include "document.hxx" #include "libxml/tree.h" using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::xml::dom; namespace DOM { typedef std::vector< xmlNodePtr > nodevector; class CElementList : public cppu::WeakImplHelper1< XNodeList > { private: const CElement* m_pElement; const OUString m_aURI; const OUString m_aName; xmlChar *xName; xmlChar *xURI; void buildlist(nodevector& v, xmlNodePtr pNode, sal_Bool start=sal_True); public: CElementList(const CElement* aDoc, const OUString& aName); CElementList(const CElement* aDoc, const OUString& aName, const OUString& aURI); /** The number of nodes in the list. */ virtual sal_Int32 SAL_CALL getLength() throw (RuntimeException); /** Returns the indexth item in the collection. */ virtual Reference< XNode > SAL_CALL item(sal_Int32 index) throw (RuntimeException); }; } #endif <commit_msg>INTEGRATION: CWS eformspp1 (1.2.10); FILE MERGED 2005/10/17 16:47:43 lo 1.2.10.3: RESYNC: (1.2-1.3); FILE MERGED 2005/07/26 11:08:07 lo 1.2.10.2: #i51843# only update node list if tree is changed 2005/07/26 10:13:47 lo 1.2.10.1: #i51843# only update node list if tree is changed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: elementlist.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-10-24 07:36:41 $ * * 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 _ELEMENTLIST_HXX #define _ELEMENTLIST_HXX #include <vector> #include <sal/types.h> #include <cppuhelper/implbase1.hxx> #include <cppuhelper/implbase2.hxx> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/xml/dom/XNode.hpp> #include <com/sun/star/xml/dom/XNodeList.hpp> #include <com/sun/star/xml/dom/events/XEvent.hpp> #include <com/sun/star/xml/dom/events/XEventListener.hpp> #include "element.hxx" #include "document.hxx" #include "libxml/tree.h" using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::xml::dom; using namespace com::sun::star::xml::dom::events; namespace DOM { typedef std::vector< xmlNodePtr > nodevector; class CElementList : public cppu::WeakImplHelper2< XNodeList, XEventListener > { private: const CElement* m_pElement; const OUString m_aURI; const OUString m_aName; xmlChar *xName; xmlChar *xURI; sal_Bool m_bRebuild; nodevector m_nodevector; void buildlist(xmlNodePtr pNode, sal_Bool start=sal_True); void registerListener(const CElement* pElement); public: CElementList(const CElement* aDoc, const OUString& aName); CElementList(const CElement* aDoc, const OUString& aName, const OUString& aURI); /** The number of nodes in the list. */ virtual sal_Int32 SAL_CALL getLength() throw (RuntimeException); /** Returns the indexth item in the collection. */ virtual Reference< XNode > SAL_CALL item(sal_Int32 index) throw (RuntimeException); // XEventListener virtual void SAL_CALL handleEvent(const Reference< XEvent >& evt) throw (RuntimeException); }; } #endif <|endoftext|>
<commit_before>#include <cstdlib> #include <unistd.h> #include <string> #include <fstream> #include "falco_engine.h" #include "config_falco_engine.h" extern "C" { #include "lpeg.h" #include "lyaml.h" } #include "utils.h" string lua_on_event = "on_event"; string lua_print_stats = "print_stats"; using namespace std; falco_engine::falco_engine(bool seed_rng) : m_rules(NULL), m_sampling_ratio(1), m_sampling_multiplier(0) { luaopen_lpeg(m_ls); luaopen_yaml(m_ls); falco_common::init(m_lua_main_filename.c_str(), FALCO_ENGINE_SOURCE_LUA_DIR); falco_rules::init(m_ls); if(seed_rng) { srandom((unsigned) getpid()); } } falco_engine::~falco_engine() { if (m_rules) { delete m_rules; } } void falco_engine::load_rules(const string &rules_content, bool verbose, bool all_events) { // The engine must have been given an inspector by now. if(! m_inspector) { throw falco_exception("No inspector provided"); } if(!m_rules) { m_rules = new falco_rules(m_inspector, this, m_ls); } m_rules->load_rules(rules_content, verbose, all_events); } void falco_engine::load_rules_file(const string &rules_filename, bool verbose, bool all_events) { ifstream is; is.open(rules_filename); if (!is.is_open()) { throw falco_exception("Could not open rules filename " + rules_filename + " " + "for reading"); } string rules_content((istreambuf_iterator<char>(is)), istreambuf_iterator<char>()); load_rules(rules_content, verbose, all_events); } void falco_engine::enable_rule(string &pattern, bool enabled) { m_evttype_filter.enable(pattern, enabled); } falco_engine::rule_result *falco_engine::process_event(sinsp_evt *ev) { if(should_drop_evt()) { return NULL; } if(!m_evttype_filter.run(ev)) { return NULL; } struct rule_result *res = new rule_result(); lua_getglobal(m_ls, lua_on_event.c_str()); if(lua_isfunction(m_ls, -1)) { lua_pushlightuserdata(m_ls, ev); lua_pushnumber(m_ls, ev->get_check_id()); if(lua_pcall(m_ls, 2, 3, 0) != 0) { const char* lerr = lua_tostring(m_ls, -1); string err = "Error invoking function output: " + string(lerr); throw falco_exception(err); } res->evt = ev; const char *p = lua_tostring(m_ls, -3); res->rule = p; res->priority = lua_tostring(m_ls, -2); res->format = lua_tostring(m_ls, -1); } else { throw falco_exception("No function " + lua_on_event + " found in lua compiler module"); } return res; } void falco_engine::describe_rule(string *rule) { return m_rules->describe_rule(rule); } // Print statistics on the the rules that triggered void falco_engine::print_stats() { lua_getglobal(m_ls, lua_print_stats.c_str()); if(lua_isfunction(m_ls, -1)) { if(lua_pcall(m_ls, 0, 0, 0) != 0) { const char* lerr = lua_tostring(m_ls, -1); string err = "Error invoking function print_stats: " + string(lerr); throw falco_exception(err); } } else { throw falco_exception("No function " + lua_print_stats + " found in lua rule loader module"); } } void falco_engine::add_evttype_filter(string &rule, list<uint32_t> &evttypes, sinsp_filter* filter) { m_evttype_filter.add(rule, evttypes, filter); } void falco_engine::set_sampling_ratio(uint32_t sampling_ratio) { m_sampling_ratio = sampling_ratio; } void falco_engine::set_sampling_multiplier(double sampling_multiplier) { m_sampling_multiplier = sampling_multiplier; } inline bool falco_engine::should_drop_evt() { if(m_sampling_multiplier == 0) { return false; } if(m_sampling_ratio == 1) { return false; } double coin = (random() * (1.0/RAND_MAX)); return (coin >= (1.0/(m_sampling_multiplier * m_sampling_ratio))); } <commit_msg>Fix lua stack leak.<commit_after>#include <cstdlib> #include <unistd.h> #include <string> #include <fstream> #include "falco_engine.h" #include "config_falco_engine.h" extern "C" { #include "lpeg.h" #include "lyaml.h" } #include "utils.h" string lua_on_event = "on_event"; string lua_print_stats = "print_stats"; using namespace std; falco_engine::falco_engine(bool seed_rng) : m_rules(NULL), m_sampling_ratio(1), m_sampling_multiplier(0) { luaopen_lpeg(m_ls); luaopen_yaml(m_ls); falco_common::init(m_lua_main_filename.c_str(), FALCO_ENGINE_SOURCE_LUA_DIR); falco_rules::init(m_ls); if(seed_rng) { srandom((unsigned) getpid()); } } falco_engine::~falco_engine() { if (m_rules) { delete m_rules; } } void falco_engine::load_rules(const string &rules_content, bool verbose, bool all_events) { // The engine must have been given an inspector by now. if(! m_inspector) { throw falco_exception("No inspector provided"); } if(!m_rules) { m_rules = new falco_rules(m_inspector, this, m_ls); } m_rules->load_rules(rules_content, verbose, all_events); } void falco_engine::load_rules_file(const string &rules_filename, bool verbose, bool all_events) { ifstream is; is.open(rules_filename); if (!is.is_open()) { throw falco_exception("Could not open rules filename " + rules_filename + " " + "for reading"); } string rules_content((istreambuf_iterator<char>(is)), istreambuf_iterator<char>()); load_rules(rules_content, verbose, all_events); } void falco_engine::enable_rule(string &pattern, bool enabled) { m_evttype_filter.enable(pattern, enabled); } falco_engine::rule_result *falco_engine::process_event(sinsp_evt *ev) { if(should_drop_evt()) { return NULL; } if(!m_evttype_filter.run(ev)) { return NULL; } struct rule_result *res = new rule_result(); lua_getglobal(m_ls, lua_on_event.c_str()); if(lua_isfunction(m_ls, -1)) { lua_pushlightuserdata(m_ls, ev); lua_pushnumber(m_ls, ev->get_check_id()); if(lua_pcall(m_ls, 2, 3, 0) != 0) { const char* lerr = lua_tostring(m_ls, -1); string err = "Error invoking function output: " + string(lerr); throw falco_exception(err); } res->evt = ev; const char *p = lua_tostring(m_ls, -3); res->rule = p; res->priority = lua_tostring(m_ls, -2); res->format = lua_tostring(m_ls, -1); lua_pop(m_ls, 3); } else { throw falco_exception("No function " + lua_on_event + " found in lua compiler module"); } return res; } void falco_engine::describe_rule(string *rule) { return m_rules->describe_rule(rule); } // Print statistics on the the rules that triggered void falco_engine::print_stats() { lua_getglobal(m_ls, lua_print_stats.c_str()); if(lua_isfunction(m_ls, -1)) { if(lua_pcall(m_ls, 0, 0, 0) != 0) { const char* lerr = lua_tostring(m_ls, -1); string err = "Error invoking function print_stats: " + string(lerr); throw falco_exception(err); } } else { throw falco_exception("No function " + lua_print_stats + " found in lua rule loader module"); } } void falco_engine::add_evttype_filter(string &rule, list<uint32_t> &evttypes, sinsp_filter* filter) { m_evttype_filter.add(rule, evttypes, filter); } void falco_engine::set_sampling_ratio(uint32_t sampling_ratio) { m_sampling_ratio = sampling_ratio; } void falco_engine::set_sampling_multiplier(double sampling_multiplier) { m_sampling_multiplier = sampling_multiplier; } inline bool falco_engine::should_drop_evt() { if(m_sampling_multiplier == 0) { return false; } if(m_sampling_ratio == 1) { return false; } double coin = (random() * (1.0/RAND_MAX)); return (coin >= (1.0/(m_sampling_multiplier * m_sampling_ratio))); } <|endoftext|>
<commit_before>// @(#)root/tree:$Name: $:$Id: TTreeCache.cxx,v 1.13 2007/02/01 15:26:19 brun Exp $ // Author: Rene Brun 04/06/2006 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TTreeCache // // // // A specialized TFileCacheRead object for a TTree // // This class acts as a file cache, registering automatically the // // baskets from the branches being processed (TTree::Draw or // // TTree::Process and TSelectors) when in the learning phase. // // The learning phase is by default 100 entries. // // It can be changed via TTreeCache::SetLearnEntries. // // // // This cache speeds-up considerably the performance, in particular // // when the Tree is accessed remotely via a high latency network. // // // // The default cache size (10 Mbytes) may be changed via the function // // TTreeCache::SetCacheSize // // // // Only the baskets for the requested entry range are put in the cache // // // // For each Tree being processed a TTreeCache object is created. // // This object is automatically deleted when the Tree is deleted or // // when the file is deleted. // // // // -Special case of a TChain // // Once the training is done on the first Tree, the list of branches // // in the cache is kept for the following files. // // // // -Special case of a TEventlist // // if the Tree or TChain has a TEventlist, only the buffers // // referenced by the list are put in the cache. // // // ////////////////////////////////////////////////////////////////////////// #include "TTreeCache.h" #include "TChain.h" #include "TList.h" #include "TBranch.h" #include "TEventList.h" #include "TObjString.h" Int_t TTreeCache::fgLearnEntries = 100; ClassImp(TTreeCache) //______________________________________________________________________________ TTreeCache::TTreeCache() : TFileCacheRead(), fEntryMin(0), fEntryMax(1), fEntryNext(1), fZipBytes(0), fNbranches(0), fNReadOk(0), fNReadMiss(0), fNReadPref(0), fBranches(0), fBrNames(0), fOwner(0), fTree(0), fIsLearning(kTRUE) { // Default Constructor. } //______________________________________________________________________________ TTreeCache::TTreeCache(TTree *tree, Int_t buffersize) : TFileCacheRead(tree->GetCurrentFile(),buffersize), fEntryMin(0), fEntryMax(tree->GetEntriesFast()), fEntryNext(0), fZipBytes(0), fNbranches(0), fNReadOk(0), fNReadMiss(0), fNReadPref(0), fBranches(0), fBrNames(new TList), fOwner(tree), fTree(0), fIsLearning(kTRUE) { // Constructor. fEntryNext = fEntryMin + fgLearnEntries; Int_t nleaves = tree->GetListOfLeaves()->GetEntries(); fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain? } //______________________________________________________________________________ TTreeCache::~TTreeCache() { // destructor. (in general called by the TFile destructor delete [] fBranches; if (fBrNames) {fBrNames->Delete(); delete fBrNames; fBrNames=0;} } //_____________________________________________________________________________ void TTreeCache::AddBranch(TBranch *b) { //add a branch to the list of branches to be stored in the cache //this function is called by TBranch::GetBasket if (!fIsLearning) return; // Reject branch that are not from the cached tree. if (!b || fTree != b->GetTree()) return; //Is branch already in the cache? Bool_t isNew = kTRUE; for (int i=0;i<fNbranches;i++) { if (fBranches[i] == b) {isNew = kFALSE; break;} } if (isNew) { // fTree = b->GetTree(); fBranches[fNbranches] = b; fBrNames->Add(new TObjString(b->GetName())); fZipBytes += b->GetZipBytes(); fNbranches++; if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName()); } } //_____________________________________________________________________________ Bool_t TTreeCache::FillBuffer() { // Fill the cache buffer with the branches in the cache. if (fNbranches <= 0) return kFALSE; TTree *tree = fBranches[0]->GetTree(); Long64_t entry = tree->GetReadEntry(); if (entry < fEntryNext) return kFALSE; // Estimate number of entries that can fit in the cache compare it // to the original value of fBufferSize not to the real one if (fZipBytes==0) { fEntryNext = entry + tree->GetEntries();; } else { fEntryNext = entry + tree->GetEntries()*fBufferSizeMin/fZipBytes; } if (fEntryMax <= 0) fEntryMax = tree->GetEntries(); if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1; // Check if owner has a TEventList set. If yes we optimize for this // Special case reading only the baskets containing entries in the // list. TEventList *elist = fOwner->GetEventList(); Long64_t chainOffset = 0; if (elist) { if (fOwner->IsA() ==TChain::Class()) { TChain *chain = (TChain*)fOwner; Int_t t = chain->GetTreeNumber(); chainOffset = chain->GetTreeOffset()[t]; } } //clear cache buffer TFileCacheRead::Prefetch(0,0); //store baskets Bool_t mustBreak = kFALSE; for (Int_t i=0;i<fNbranches;i++) { if (mustBreak) break; TBranch *b = fBranches[i]; Int_t nb = b->GetMaxBaskets(); Int_t *lbaskets = b->GetBasketBytes(); Long64_t *entries = b->GetBasketEntry(); if (!lbaskets || !entries) continue; //we have found the branch. We now register all its baskets //from the requested offset to the basket below fEntrymax for (Int_t j=0;j<nb;j++) { Long64_t pos = b->GetBasketSeek(j); Int_t len = lbaskets[j]; if (pos <= 0 || len <= 0) continue; if (entries[j] > fEntryNext) continue; if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue; if (elist) { Long64_t emax = fEntryMax; if (j<nb-1) emax = entries[j+1]-1; if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue; } fNReadPref++; TFileCacheRead::Prefetch(pos,len); //we allow up to twice the default buffer size. When using eventlist in particular //it may happen that the evaluation of fEntryNext is bad, hence this protection if (fNtot > 2*fBufferSizeMin) {TFileCacheRead::Prefetch(0,0);mustBreak = kTRUE; break;} } if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot); } fIsLearning = kFALSE; if (mustBreak) return kFALSE; return kTRUE; } //_____________________________________________________________________________ Double_t TTreeCache::GetEfficiency() { // Give the total efficiency of the cache... defined as the ratio // of blocks found in the cache vs. the number of blocks prefetched // ( it could be more than 1 if we read the same block from the cache more // than once ) // Note: This should eb used at the end of the processing or we will // get uncomplete stats if ( !fNReadPref ) return 0; return ((Double_t)fNReadOk / (Double_t)fNReadPref); } //_____________________________________________________________________________ Double_t TTreeCache::GetEfficiencyRel() { // This will indicate a sort of relative efficiency... a ratio of the // reads found in the cache to the number of reads so far if ( !fNReadOk && !fNReadMiss ) return 0; return ((Double_t)fNReadOk / (Double_t)(fNReadOk + fNReadMiss)); } //_____________________________________________________________________________ Int_t TTreeCache::GetLearnEntries() { //static function returning the number of entries used to train the cache //see SetLearnEntries return fgLearnEntries; } //_____________________________________________________________________________ TTree *TTreeCache::GetTree() const { //return Tree in the cache if (fNbranches <= 0) return 0; return fBranches[0]->GetTree(); } //_____________________________________________________________________________ Int_t TTreeCache::ReadBuffer(char *buf, Long64_t pos, Int_t len) { // Read buffer at position pos. // If pos is in the list of prefetched blocks read from fBuffer. // Otherwise try to fill the cache from the list of selected branches, // and recheck if pos is now in the list. // Returns // -1 in case of read failure, // 0 in case not in cache, // 1 in case read from cache. // This function overloads TFileCacheRead::ReadBuffer. //Is request already in the cache? if (TFileCacheRead::ReadBuffer(buf,pos,len) == 1){ fNReadOk++; return 1; } //not found in cache. Do we need to fill the cache? Bool_t bufferFilled = FillBuffer(); if (bufferFilled) { Int_t res = TFileCacheRead::ReadBuffer(buf,pos,len); if (res == 1) fNReadOk++; else if (res == 0) fNReadMiss++; return res; } fNReadMiss++; return 0; } //_____________________________________________________________________________ void TTreeCache::SetEntryRange(Long64_t emin, Long64_t emax) { // Set the minimum and maximum entry number to be processed // this information helps to optimize the number of baskets to read // when prefetching the branch buffers. fEntryMin = emin; fEntryMax = emax; fEntryNext = fEntryMin + fgLearnEntries; if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext); fIsLearning = kTRUE; fNbranches = 0; fZipBytes = 0; if (fBrNames) fBrNames->Delete(); } //_____________________________________________________________________________ void TTreeCache::SetLearnEntries(Int_t n) { // Static function to set the number of entries to be used in learning mode // The default value for n is 10. n must be >= 1 if (n < 1) n = 1; fgLearnEntries = n; } //_____________________________________________________________________________ void TTreeCache::UpdateBranches(TTree *tree) { //update pointer to current Tree and recompute pointers to the branches in the cache fTree = tree; fEntryMin = 0; fEntryMax = fTree->GetEntries(); fEntryNext = fEntryMin + fgLearnEntries; fZipBytes = 0; fNbranches = 0; TIter next(fBrNames); TObjString *os; while ((os = (TObjString*)next())) { TBranch *b = fTree->GetBranch(os->GetName()); if (!b) continue; fBranches[fNbranches] = b; fZipBytes += b->GetZipBytes(); fNbranches++; } } <commit_msg>When testing the incoming branch, test on fOwner->GetTree() rather than fTree<commit_after>// @(#)root/tree:$Name: $:$Id: TTreeCache.cxx,v 1.14 2007/07/16 16:31:57 pcanal Exp $ // Author: Rene Brun 04/06/2006 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TTreeCache // // // // A specialized TFileCacheRead object for a TTree // // This class acts as a file cache, registering automatically the // // baskets from the branches being processed (TTree::Draw or // // TTree::Process and TSelectors) when in the learning phase. // // The learning phase is by default 100 entries. // // It can be changed via TTreeCache::SetLearnEntries. // // // // This cache speeds-up considerably the performance, in particular // // when the Tree is accessed remotely via a high latency network. // // // // The default cache size (10 Mbytes) may be changed via the function // // TTreeCache::SetCacheSize // // // // Only the baskets for the requested entry range are put in the cache // // // // For each Tree being processed a TTreeCache object is created. // // This object is automatically deleted when the Tree is deleted or // // when the file is deleted. // // // // -Special case of a TChain // // Once the training is done on the first Tree, the list of branches // // in the cache is kept for the following files. // // // // -Special case of a TEventlist // // if the Tree or TChain has a TEventlist, only the buffers // // referenced by the list are put in the cache. // // // ////////////////////////////////////////////////////////////////////////// #include "TTreeCache.h" #include "TChain.h" #include "TList.h" #include "TBranch.h" #include "TEventList.h" #include "TObjString.h" Int_t TTreeCache::fgLearnEntries = 100; ClassImp(TTreeCache) //______________________________________________________________________________ TTreeCache::TTreeCache() : TFileCacheRead(), fEntryMin(0), fEntryMax(1), fEntryNext(1), fZipBytes(0), fNbranches(0), fNReadOk(0), fNReadMiss(0), fNReadPref(0), fBranches(0), fBrNames(0), fOwner(0), fTree(0), fIsLearning(kTRUE) { // Default Constructor. } //______________________________________________________________________________ TTreeCache::TTreeCache(TTree *tree, Int_t buffersize) : TFileCacheRead(tree->GetCurrentFile(),buffersize), fEntryMin(0), fEntryMax(tree->GetEntriesFast()), fEntryNext(0), fZipBytes(0), fNbranches(0), fNReadOk(0), fNReadMiss(0), fNReadPref(0), fBranches(0), fBrNames(new TList), fOwner(tree), fTree(0), fIsLearning(kTRUE) { // Constructor. fEntryNext = fEntryMin + fgLearnEntries; Int_t nleaves = tree->GetListOfLeaves()->GetEntries(); fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain? } //______________________________________________________________________________ TTreeCache::~TTreeCache() { // destructor. (in general called by the TFile destructor delete [] fBranches; if (fBrNames) {fBrNames->Delete(); delete fBrNames; fBrNames=0;} } //_____________________________________________________________________________ void TTreeCache::AddBranch(TBranch *b) { //add a branch to the list of branches to be stored in the cache //this function is called by TBranch::GetBasket if (!fIsLearning) return; // Reject branch that are not from the cached tree. if (!b || fOwner->GetTree() != b->GetTree()) return; //Is branch already in the cache? Bool_t isNew = kTRUE; for (int i=0;i<fNbranches;i++) { if (fBranches[i] == b) {isNew = kFALSE; break;} } if (isNew) { fTree = b->GetTree(); fBranches[fNbranches] = b; fBrNames->Add(new TObjString(b->GetName())); fZipBytes += b->GetZipBytes(); fNbranches++; if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName()); } } //_____________________________________________________________________________ Bool_t TTreeCache::FillBuffer() { // Fill the cache buffer with the branches in the cache. if (fNbranches <= 0) return kFALSE; TTree *tree = fBranches[0]->GetTree(); Long64_t entry = tree->GetReadEntry(); if (entry < fEntryNext) return kFALSE; // Estimate number of entries that can fit in the cache compare it // to the original value of fBufferSize not to the real one if (fZipBytes==0) { fEntryNext = entry + tree->GetEntries();; } else { fEntryNext = entry + tree->GetEntries()*fBufferSizeMin/fZipBytes; } if (fEntryMax <= 0) fEntryMax = tree->GetEntries(); if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1; // Check if owner has a TEventList set. If yes we optimize for this // Special case reading only the baskets containing entries in the // list. TEventList *elist = fOwner->GetEventList(); Long64_t chainOffset = 0; if (elist) { if (fOwner->IsA() ==TChain::Class()) { TChain *chain = (TChain*)fOwner; Int_t t = chain->GetTreeNumber(); chainOffset = chain->GetTreeOffset()[t]; } } //clear cache buffer TFileCacheRead::Prefetch(0,0); //store baskets Bool_t mustBreak = kFALSE; for (Int_t i=0;i<fNbranches;i++) { if (mustBreak) break; TBranch *b = fBranches[i]; Int_t nb = b->GetMaxBaskets(); Int_t *lbaskets = b->GetBasketBytes(); Long64_t *entries = b->GetBasketEntry(); if (!lbaskets || !entries) continue; //we have found the branch. We now register all its baskets //from the requested offset to the basket below fEntrymax for (Int_t j=0;j<nb;j++) { Long64_t pos = b->GetBasketSeek(j); Int_t len = lbaskets[j]; if (pos <= 0 || len <= 0) continue; if (entries[j] > fEntryNext) continue; if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue; if (elist) { Long64_t emax = fEntryMax; if (j<nb-1) emax = entries[j+1]-1; if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue; } fNReadPref++; TFileCacheRead::Prefetch(pos,len); //we allow up to twice the default buffer size. When using eventlist in particular //it may happen that the evaluation of fEntryNext is bad, hence this protection if (fNtot > 2*fBufferSizeMin) {TFileCacheRead::Prefetch(0,0);mustBreak = kTRUE; break;} } if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot); } fIsLearning = kFALSE; if (mustBreak) return kFALSE; return kTRUE; } //_____________________________________________________________________________ Double_t TTreeCache::GetEfficiency() { // Give the total efficiency of the cache... defined as the ratio // of blocks found in the cache vs. the number of blocks prefetched // ( it could be more than 1 if we read the same block from the cache more // than once ) // Note: This should eb used at the end of the processing or we will // get uncomplete stats if ( !fNReadPref ) return 0; return ((Double_t)fNReadOk / (Double_t)fNReadPref); } //_____________________________________________________________________________ Double_t TTreeCache::GetEfficiencyRel() { // This will indicate a sort of relative efficiency... a ratio of the // reads found in the cache to the number of reads so far if ( !fNReadOk && !fNReadMiss ) return 0; return ((Double_t)fNReadOk / (Double_t)(fNReadOk + fNReadMiss)); } //_____________________________________________________________________________ Int_t TTreeCache::GetLearnEntries() { //static function returning the number of entries used to train the cache //see SetLearnEntries return fgLearnEntries; } //_____________________________________________________________________________ TTree *TTreeCache::GetTree() const { //return Tree in the cache if (fNbranches <= 0) return 0; return fBranches[0]->GetTree(); } //_____________________________________________________________________________ Int_t TTreeCache::ReadBuffer(char *buf, Long64_t pos, Int_t len) { // Read buffer at position pos. // If pos is in the list of prefetched blocks read from fBuffer. // Otherwise try to fill the cache from the list of selected branches, // and recheck if pos is now in the list. // Returns // -1 in case of read failure, // 0 in case not in cache, // 1 in case read from cache. // This function overloads TFileCacheRead::ReadBuffer. //Is request already in the cache? if (TFileCacheRead::ReadBuffer(buf,pos,len) == 1){ fNReadOk++; return 1; } //not found in cache. Do we need to fill the cache? Bool_t bufferFilled = FillBuffer(); if (bufferFilled) { Int_t res = TFileCacheRead::ReadBuffer(buf,pos,len); if (res == 1) fNReadOk++; else if (res == 0) fNReadMiss++; return res; } fNReadMiss++; return 0; } //_____________________________________________________________________________ void TTreeCache::SetEntryRange(Long64_t emin, Long64_t emax) { // Set the minimum and maximum entry number to be processed // this information helps to optimize the number of baskets to read // when prefetching the branch buffers. fEntryMin = emin; fEntryMax = emax; fEntryNext = fEntryMin + fgLearnEntries; if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext); fIsLearning = kTRUE; fNbranches = 0; fZipBytes = 0; if (fBrNames) fBrNames->Delete(); } //_____________________________________________________________________________ void TTreeCache::SetLearnEntries(Int_t n) { // Static function to set the number of entries to be used in learning mode // The default value for n is 10. n must be >= 1 if (n < 1) n = 1; fgLearnEntries = n; } //_____________________________________________________________________________ void TTreeCache::UpdateBranches(TTree *tree) { //update pointer to current Tree and recompute pointers to the branches in the cache fTree = tree; fEntryMin = 0; fEntryMax = fTree->GetEntries(); fEntryNext = fEntryMin + fgLearnEntries; fZipBytes = 0; fNbranches = 0; TIter next(fBrNames); TObjString *os; while ((os = (TObjString*)next())) { TBranch *b = fTree->GetBranch(os->GetName()); if (!b) continue; fBranches[fNbranches] = b; fZipBytes += b->GetZipBytes(); fNbranches++; } } <|endoftext|>
<commit_before>// @(#)root/tree:$Name: $:$Id: TTreeCache.cxx,v 1.6 2006/08/14 08:55:30 brun Exp $ // Author: Rene Brun 04/06/2006 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TTreeCache // // // // A specialized TFileCacheRead object for a TTree // // This class acts as a file cache, registering automatically the // // baskets from the branches being processed (TTree::Draw or // // TTree::Process and TSelectors) when in the learning phase. // // The learning phase is by default 100 entries. // // It can be changed via TTreeCache::SetLearnEntries. // // // // This cache speeds-up considerably the performance, in particular // // when the Tree is accessed remotely via a high latency network. // // // // The default cache size (10 Mbytes) may be changed via the function // // TTreeCache::SetCacheSize // // // // Only the baskets for the requested entry range are put in the cache // // // // For each Tree being processed a TTreeCache object is created. // // This object is automatically deleted when the Tree is deleted or // // when the file is deleted. // // // // -Special case of a TChain // // Once the training is done on the first Tree, the list of branches // // in the cache is kept for the following files. // // // // -Special case of a TEventlist // // if the Tree or TChain has a TEventlist, only the buffers // // referenced by the list are put in the cache. // // // ////////////////////////////////////////////////////////////////////////// #include "TTreeCache.h" #include "TChain.h" #include "TBranch.h" #include "TEventList.h" #include "TObjString.h" Int_t TTreeCache::fgLearnEntries = 100; ClassImp(TTreeCache) //______________________________________________________________________________ TTreeCache::TTreeCache() : TFileCacheRead(), fEntryMin(0), fEntryMax(1), fEntryNext(1), fZipBytes(0), fNbranches(0), fNReadOk(0), fNReadMiss(0), fNReadPref(0), fBranches(0), fBrNames(0), fOwner(0), fTree(0), fIsLearning(kTRUE) { // Default Constructor. } //______________________________________________________________________________ TTreeCache::TTreeCache(TTree *tree, Int_t buffersize) : TFileCacheRead(tree->GetCurrentFile(),buffersize), fEntryMin(0), fEntryMax(tree->GetEntriesFast()), fEntryNext(0), fZipBytes(0), fNbranches(0), fNReadOk(0), fNReadMiss(0), fNReadPref(0), fBranches(0), fBrNames(new TList), fOwner(tree), fTree(0), fIsLearning(kTRUE) { // Constructor. fEntryNext = fEntryMin + fgLearnEntries; Int_t nleaves = tree->GetListOfLeaves()->GetEntries(); fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain? } //______________________________________________________________________________ TTreeCache::TTreeCache(const TTreeCache &pf) : TFileCacheRead(pf) { // Copy Constructor. } //______________________________________________________________________________ TTreeCache::~TTreeCache() { // destructor. (in general called by the TFile destructor delete [] fBranches; if (fBrNames) {fBrNames->Delete(); delete fBrNames;} } //______________________________________________________________________________ TTreeCache& TTreeCache::operator=(const TTreeCache& pf) { // Assignment. if (this != &pf) TFileCacheRead::operator=(pf); return *this; } //_____________________________________________________________________________ void TTreeCache::AddBranch(TBranch *b) { //add a branch to the list of branches to be stored in the cache //this function is called by TBranch::GetBasket if (!fIsLearning) return; //Is branch already in the cache? Bool_t isNew = kTRUE; for (int i=0;i<fNbranches;i++) { if (fBranches[i] == b) {isNew = kFALSE; break;} } if (isNew) { fTree = b->GetTree(); fBranches[fNbranches] = b; fBrNames->Add(new TObjString(b->GetName())); fZipBytes += b->GetZipBytes(); fNbranches++; if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName()); } } //_____________________________________________________________________________ Bool_t TTreeCache::FillBuffer() { //Fill the cache buffer with the branches in the cache if (fNbranches <= 0) return kFALSE; TTree *tree = fBranches[0]->GetTree(); Long64_t entry = tree->GetReadEntry(); if (entry < fEntryNext) return kFALSE; // estimate number of entries that can fit in the cache // compare it to the original value of fBufferSize not // to the real one fEntryNext = entry + tree->GetEntries()*fBufferSizeMin/fZipBytes; if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1; //check if owner has a TEventList set. If yes we optimize for this special case //reading only the baskets containing entries in the list TEventList *elist = fOwner->GetEventList(); Long64_t chainOffset = 0; if (elist) { fEntryNext = fTree->GetEntries(); if (fOwner->IsA() ==TChain::Class()) { TChain *chain = (TChain*)fOwner; Int_t t = chain->GetTreeNumber(); chainOffset = chain->GetTreeOffset()[t]; } } //clear cache buffer TFileCacheRead::Prefetch(0,0); //store baskets Bool_t mustBreak = kFALSE; for (Int_t i=0;i<fNbranches;i++) { if (mustBreak) break; TBranch *b = fBranches[i]; Int_t nb = b->GetMaxBaskets(); Int_t *lbaskets = b->GetBasketBytes(); Long64_t *entries = b->GetBasketEntry(); if (!lbaskets || !entries) continue; //we have found the branch. We now register all its baskets //from the requested offset to the basket below fEntrymax for (Int_t j=0;j<nb;j++) { Long64_t pos = b->GetBasketSeek(j); Int_t len = lbaskets[j]; if (pos <= 0 || len <= 0) continue; if (entries[j] > fEntryNext) continue; if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue; if (elist) { Long64_t emax = fEntryMax; if (j<nb-1) emax = entries[j+1]-1; if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue; } fNReadPref++; TFileCacheRead::Prefetch(pos,len); //we allow up to twice the default buffer size. When using eventlist in particular //it may happen that the evaluation of fEntryNext is bad, hence this protection if (fNtot > 2*fBufferSizeMin) {TFileCacheRead::Prefetch(0,0);mustBreak = kTRUE; break;} } if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot); } fIsLearning = kFALSE; if (mustBreak) return kFALSE; return kTRUE; } //_____________________________________________________________________________ Double_t TTreeCache::GetEfficiency() { // Give the total efficiency of the cache... defined as the ratio // of blocks found in the cache vs. the number of blocks prefetched // ( it could be more than 1 if we read the same block from the cache more // than once ) // Note: This should eb used at the end of the processing or we will // get uncomplete stats if ( !fNReadPref ) return 0; return ((Double_t)fNReadOk / (Double_t)fNReadPref); } //_____________________________________________________________________________ Double_t TTreeCache::GetEfficiencyRel() { // This will indicate a sort of relative efficiency... a ratio of the // reads found in the cache to the number of reads so far if ( !fNReadOk && !fNReadMiss ) return 0; return ((Double_t)fNReadOk / (Double_t)(fNReadOk + fNReadMiss)); } //_____________________________________________________________________________ Int_t TTreeCache::GetLearnEntries() { //static function returning the number of entries used to train the cache //see SetLearnEntries return fgLearnEntries; } //_____________________________________________________________________________ TTree *TTreeCache::GetTree() const { //return Tree in the cache if (fNbranches <= 0) return 0; return fBranches[0]->GetTree(); } //_____________________________________________________________________________ Int_t TTreeCache::ReadBuffer(char *buf, Long64_t pos, Int_t len) { // Read buffer at position pos. // If pos is in the list of prefetched blocks read from fBuffer, // then try to fill the cache from the list of selected branches, // otherwise normal read from file. Returns -1 in case of read // failure, 0 in case not in cache and 1 in case read from cache. // This function overloads TFileCacheRead::ReadBuffer. //Is request already in the cache? if (TFileCacheRead::ReadBuffer(buf,pos,len) == 1){ fNReadOk++; return 1; } //not found in cache. Do we need to fill the cache? Bool_t bufferFilled = FillBuffer(); if (bufferFilled) { Int_t res = TFileCacheRead::ReadBuffer(buf,pos,len); if (res == 1) fNReadOk++; else if (res == 0) fNReadMiss++; return res; } fNReadMiss++; return 0; } //_____________________________________________________________________________ void TTreeCache::SetEntryRange(Long64_t emin, Long64_t emax) { // Set the minimum and maximum entry number to be processed // this information helps to optimize the number of baskets to read // when prefetching the branch buffers. fEntryMin = emin; fEntryMax = emax; fEntryNext = fEntryMin + fgLearnEntries; fIsLearning = kTRUE; fNbranches = 0; fZipBytes = 0; if (fBrNames) fBrNames->Delete(); if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext); } //_____________________________________________________________________________ void TTreeCache::SetLearnEntries(Int_t n) { // Static function to set the number of entries to be used in learning mode // The default value for n is 10. n must be >= 1 if (n < 1) n = 1; fgLearnEntries = n; } //_____________________________________________________________________________ void TTreeCache::UpdateBranches(TTree *tree) { //update pointer to current Tree and recompute pointers to the branches in the cache fTree = tree; Prefetch(0,0); fEntryMin = 0; fEntryMax = fTree->GetEntries(); fEntryNext = fEntryMin + fgLearnEntries; fZipBytes = 0; fNbranches = 0; TIter next(fBrNames); TObjString *os; while ((os = (TObjString*)next())) { TBranch *b = fTree->GetBranch(os->GetName()); if (!b) continue; fBranches[fNbranches] = b; fZipBytes += b->GetZipBytes(); fNbranches++; } } <commit_msg>I forgot to delete one statement in my previous fix. This prevented the effective use of the cache when using a TEventList.<commit_after>// @(#)root/tree:$Name: $:$Id: TTreeCache.cxx,v 1.7 2006/08/14 10:52:43 brun Exp $ // Author: Rene Brun 04/06/2006 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TTreeCache // // // // A specialized TFileCacheRead object for a TTree // // This class acts as a file cache, registering automatically the // // baskets from the branches being processed (TTree::Draw or // // TTree::Process and TSelectors) when in the learning phase. // // The learning phase is by default 100 entries. // // It can be changed via TTreeCache::SetLearnEntries. // // // // This cache speeds-up considerably the performance, in particular // // when the Tree is accessed remotely via a high latency network. // // // // The default cache size (10 Mbytes) may be changed via the function // // TTreeCache::SetCacheSize // // // // Only the baskets for the requested entry range are put in the cache // // // // For each Tree being processed a TTreeCache object is created. // // This object is automatically deleted when the Tree is deleted or // // when the file is deleted. // // // // -Special case of a TChain // // Once the training is done on the first Tree, the list of branches // // in the cache is kept for the following files. // // // // -Special case of a TEventlist // // if the Tree or TChain has a TEventlist, only the buffers // // referenced by the list are put in the cache. // // // ////////////////////////////////////////////////////////////////////////// #include "TTreeCache.h" #include "TChain.h" #include "TBranch.h" #include "TEventList.h" #include "TObjString.h" Int_t TTreeCache::fgLearnEntries = 100; ClassImp(TTreeCache) //______________________________________________________________________________ TTreeCache::TTreeCache() : TFileCacheRead(), fEntryMin(0), fEntryMax(1), fEntryNext(1), fZipBytes(0), fNbranches(0), fNReadOk(0), fNReadMiss(0), fNReadPref(0), fBranches(0), fBrNames(0), fOwner(0), fTree(0), fIsLearning(kTRUE) { // Default Constructor. } //______________________________________________________________________________ TTreeCache::TTreeCache(TTree *tree, Int_t buffersize) : TFileCacheRead(tree->GetCurrentFile(),buffersize), fEntryMin(0), fEntryMax(tree->GetEntriesFast()), fEntryNext(0), fZipBytes(0), fNbranches(0), fNReadOk(0), fNReadMiss(0), fNReadPref(0), fBranches(0), fBrNames(new TList), fOwner(tree), fTree(0), fIsLearning(kTRUE) { // Constructor. fEntryNext = fEntryMin + fgLearnEntries; Int_t nleaves = tree->GetListOfLeaves()->GetEntries(); fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain? } //______________________________________________________________________________ TTreeCache::TTreeCache(const TTreeCache &pf) : TFileCacheRead(pf) { // Copy Constructor. } //______________________________________________________________________________ TTreeCache::~TTreeCache() { // destructor. (in general called by the TFile destructor delete [] fBranches; if (fBrNames) {fBrNames->Delete(); delete fBrNames;} } //______________________________________________________________________________ TTreeCache& TTreeCache::operator=(const TTreeCache& pf) { // Assignment. if (this != &pf) TFileCacheRead::operator=(pf); return *this; } //_____________________________________________________________________________ void TTreeCache::AddBranch(TBranch *b) { //add a branch to the list of branches to be stored in the cache //this function is called by TBranch::GetBasket if (!fIsLearning) return; //Is branch already in the cache? Bool_t isNew = kTRUE; for (int i=0;i<fNbranches;i++) { if (fBranches[i] == b) {isNew = kFALSE; break;} } if (isNew) { fTree = b->GetTree(); fBranches[fNbranches] = b; fBrNames->Add(new TObjString(b->GetName())); fZipBytes += b->GetZipBytes(); fNbranches++; if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName()); } } //_____________________________________________________________________________ Bool_t TTreeCache::FillBuffer() { //Fill the cache buffer with the branches in the cache if (fNbranches <= 0) return kFALSE; TTree *tree = fBranches[0]->GetTree(); Long64_t entry = tree->GetReadEntry(); if (entry < fEntryNext) return kFALSE; // estimate number of entries that can fit in the cache // compare it to the original value of fBufferSize not // to the real one fEntryNext = entry + tree->GetEntries()*fBufferSizeMin/fZipBytes; if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1; //check if owner has a TEventList set. If yes we optimize for this special case //reading only the baskets containing entries in the list TEventList *elist = fOwner->GetEventList(); Long64_t chainOffset = 0; if (elist) { if (fOwner->IsA() ==TChain::Class()) { TChain *chain = (TChain*)fOwner; Int_t t = chain->GetTreeNumber(); chainOffset = chain->GetTreeOffset()[t]; } } //clear cache buffer TFileCacheRead::Prefetch(0,0); //store baskets Bool_t mustBreak = kFALSE; for (Int_t i=0;i<fNbranches;i++) { if (mustBreak) break; TBranch *b = fBranches[i]; Int_t nb = b->GetMaxBaskets(); Int_t *lbaskets = b->GetBasketBytes(); Long64_t *entries = b->GetBasketEntry(); if (!lbaskets || !entries) continue; //we have found the branch. We now register all its baskets //from the requested offset to the basket below fEntrymax for (Int_t j=0;j<nb;j++) { Long64_t pos = b->GetBasketSeek(j); Int_t len = lbaskets[j]; if (pos <= 0 || len <= 0) continue; if (entries[j] > fEntryNext) continue; if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue; if (elist) { Long64_t emax = fEntryMax; if (j<nb-1) emax = entries[j+1]-1; if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue; } fNReadPref++; TFileCacheRead::Prefetch(pos,len); //we allow up to twice the default buffer size. When using eventlist in particular //it may happen that the evaluation of fEntryNext is bad, hence this protection if (fNtot > 2*fBufferSizeMin) {TFileCacheRead::Prefetch(0,0);mustBreak = kTRUE; break;} } if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot); } fIsLearning = kFALSE; if (mustBreak) return kFALSE; return kTRUE; } //_____________________________________________________________________________ Double_t TTreeCache::GetEfficiency() { // Give the total efficiency of the cache... defined as the ratio // of blocks found in the cache vs. the number of blocks prefetched // ( it could be more than 1 if we read the same block from the cache more // than once ) // Note: This should eb used at the end of the processing or we will // get uncomplete stats if ( !fNReadPref ) return 0; return ((Double_t)fNReadOk / (Double_t)fNReadPref); } //_____________________________________________________________________________ Double_t TTreeCache::GetEfficiencyRel() { // This will indicate a sort of relative efficiency... a ratio of the // reads found in the cache to the number of reads so far if ( !fNReadOk && !fNReadMiss ) return 0; return ((Double_t)fNReadOk / (Double_t)(fNReadOk + fNReadMiss)); } //_____________________________________________________________________________ Int_t TTreeCache::GetLearnEntries() { //static function returning the number of entries used to train the cache //see SetLearnEntries return fgLearnEntries; } //_____________________________________________________________________________ TTree *TTreeCache::GetTree() const { //return Tree in the cache if (fNbranches <= 0) return 0; return fBranches[0]->GetTree(); } //_____________________________________________________________________________ Int_t TTreeCache::ReadBuffer(char *buf, Long64_t pos, Int_t len) { // Read buffer at position pos. // If pos is in the list of prefetched blocks read from fBuffer, // then try to fill the cache from the list of selected branches, // otherwise normal read from file. Returns -1 in case of read // failure, 0 in case not in cache and 1 in case read from cache. // This function overloads TFileCacheRead::ReadBuffer. //Is request already in the cache? if (TFileCacheRead::ReadBuffer(buf,pos,len) == 1){ fNReadOk++; return 1; } //not found in cache. Do we need to fill the cache? Bool_t bufferFilled = FillBuffer(); if (bufferFilled) { Int_t res = TFileCacheRead::ReadBuffer(buf,pos,len); if (res == 1) fNReadOk++; else if (res == 0) fNReadMiss++; return res; } fNReadMiss++; return 0; } //_____________________________________________________________________________ void TTreeCache::SetEntryRange(Long64_t emin, Long64_t emax) { // Set the minimum and maximum entry number to be processed // this information helps to optimize the number of baskets to read // when prefetching the branch buffers. fEntryMin = emin; fEntryMax = emax; fEntryNext = fEntryMin + fgLearnEntries; fIsLearning = kTRUE; fNbranches = 0; fZipBytes = 0; if (fBrNames) fBrNames->Delete(); if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext); } //_____________________________________________________________________________ void TTreeCache::SetLearnEntries(Int_t n) { // Static function to set the number of entries to be used in learning mode // The default value for n is 10. n must be >= 1 if (n < 1) n = 1; fgLearnEntries = n; } //_____________________________________________________________________________ void TTreeCache::UpdateBranches(TTree *tree) { //update pointer to current Tree and recompute pointers to the branches in the cache fTree = tree; Prefetch(0,0); fEntryMin = 0; fEntryMax = fTree->GetEntries(); fEntryNext = fEntryMin + fgLearnEntries; fZipBytes = 0; fNbranches = 0; TIter next(fBrNames); TObjString *os; while ((os = (TObjString*)next())) { TBranch *b = fTree->GetBranch(os->GetName()); if (!b) continue; fBranches[fNbranches] = b; fZipBytes += b->GetZipBytes(); fNbranches++; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2016, imec * All rights reserved. */ #include "error.h" #include "bpmf.h" #include <random> #include <memory> #include <cstdio> #include <iostream> #include <climits> #include <stdexcept> #include "io.h" #if defined(_OPENMP) #include "omp.h" #pragma omp declare reduction (VectorPlus : VectorNd : omp_out += omp_in) initializer(omp_priv = VectorNd::Zero()) #pragma omp declare reduction (MatrixPlus : MatrixNNd : omp_out += omp_in) initializer(omp_priv = MatrixNNd::Zero()) #endif static const bool measure_perf = false; std::ostream *Sys::os; int Sys::procid = -1; int Sys::nprocs = -1; int Sys::nsims; int Sys::burnin; int Sys::update_freq; double Sys::alpha = 2.0; std::string Sys::odirname = ""; bool Sys::permute = true; bool Sys::verbose = false; unsigned Sys::grain_size; void calc_upper_part(MatrixNNd &m, VectorNd v); // function for calcutation of an upper part of a symmetric matrix: m = v * v.transpose(); void copy_lower_part(MatrixNNd &m); // function to copy an upper part of a symmetric matrix to a lower part // verifies that A has the same non-zero structure as B void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B) { assert(A.cols() == B.cols()); assert(A.rows() == B.rows()); for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros()); } // // Does predictions for prediction matrix T // Computes RMSE (Root Means Square Error) // void Sys::predict(Sys& other, bool all) { int n = (iter < burnin) ? 0 : (iter - burnin); double se(0.0); // squared err double se_avg(0.0); // squared avg err unsigned nump(0); // number of predictions int lo = all ? 0 : from(); int hi = all ? num() : to(); #pragma omp parallel for reduction(+:se,se_avg,nump) for(int k = lo; k<hi; k++) { for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it) { auto m = items().col(it.col()); auto u = other.items().col(it.row()); assert(m.norm() > 0.0); assert(u.norm() > 0.0); const double pred = m.dot(u) + mean_rating; se += sqr(it.value() - pred); // update average prediction double &avg = Pavg.coeffRef(it.row(), it.col()); double delta = pred - avg; avg = (n == 0) ? pred : (avg + delta/n); double &m2 = Pm2.coeffRef(it.row(), it.col()); m2 = (n == 0) ? 0 : m2 + delta * (pred - avg); se_avg += sqr(it.value() - avg); nump++; } } rmse = sqrt( se / nump ); rmse_avg = sqrt( se_avg / nump ); } // // Prints sampling progress // void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) { char buf[1024]; std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling"; sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n", Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6); Sys::cout() << buf; } // // Constructor with that reads MTX files // Sys::Sys(std::string name, std::string fname, std::string probename) : name(name), iter(-1), assigned(false), dom(nprocs+1) { read_matrix(fname, M); read_matrix(probename, T); auto rows = std::max(M.rows(), T.rows()); auto cols = std::max(M.cols(), T.cols()); M.conservativeResize(rows,cols); T.conservativeResize(rows,cols); Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); assert(Sys::nprocs <= (int)Sys::max_procs); } // // Constructs Sys as transpose of existing Sys // Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) { M = Mt.transpose(); Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); } Sys::~Sys() { if (measure_perf) { Sys::cout() << " --------------------\n"; Sys::cout() << name << ": sampling times on " << procid << "\n"; for(int i = from(); i<to(); ++i) { Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n"; } Sys::cout() << " --------------------\n\n"; } } bool Sys::has_prop_posterior() const { return propMu.nonZeros() > 0; } void Sys::add_prop_posterior(std::string fnames) { if (fnames.empty()) return; std::size_t pos = fnames.find_first_of(","); std::string mu_name = fnames.substr(0, pos); std::string lambda_name = fnames.substr(pos+1); read_matrix(mu_name, propMu); read_matrix(lambda_name, propLambda); assert(propMu.cols() == num()); assert(propLambda.cols() == num()); assert(propMu.rows() == num_latent); assert(propLambda.rows() == num_latent * num_latent); } // // Intializes internal Matrices and Vectors // void Sys::init() { //-- M assert(M.rows() > 0 && M.cols() > 0); mean_rating = M.sum() / M.nonZeros(); items().setZero(); sum_map().setZero(); cov_map().setZero(); norm_map().setZero(); col_permutation.setIdentity(num()); if (Sys::odirname.size()) { aggrMu = Eigen::MatrixXd::Zero(num_latent, num()); aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); } Sys::cout() << "mean rating = " << mean_rating << std::endl; Sys::cout() << "total number of ratings in train = " << M.nonZeros() << std::endl; Sys::cout() << "total number of ratings in test = " << T.nonZeros() << std::endl; Sys::cout() << "num " << name << ": " << num() << std::endl; if (has_prop_posterior()) { Sys::cout() << "with propagated posterior" << std::endl; } if (measure_perf) sample_time.resize(num(), .0); } class PrecomputedLLT : public Eigen::LLT<MatrixNNd> { public: void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; } }; // // Update ONE movie or one user // VectorNd Sys::sample(long idx, const MapNXd in) { auto start = tick(); VectorNd hp_mu; MatrixNNd hp_LambdaF; MatrixNNd hp_LambdaL; if (has_prop_posterior()) { hp_mu = propMu.col(idx); hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data()); hp_LambdaL = hp_LambdaF.llt().matrixL(); } else { hp_mu = hp.mu; hp_LambdaF = hp.LambdaF; hp_LambdaL = hp.LambdaL; } int breakpoint1 = 24; int breakpoint2 = 10500; const int count = M.innerVector(idx).nonZeros(); // count of nonzeros elements in idx-th row of M matrix // (how many movies watched idx-th user?). VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14) // if this user movie has less than 1K ratings, // we do a serial rank update if( count < breakpoint1 ) { chol = hp_LambdaL; for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) { auto col = in.col(it.row()); chol.rankUpdate(col, alpha); rr.noalias() += col * ((it.value() - mean_rating) * alpha); } // else we do a serial full cholesky decomposition // (not used if breakpoint1 == breakpoint2) } else if (count < breakpoint2) { MatrixNNd MM(MatrixNNd::Zero()); for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) { auto col = in.col(it.row()); //MM.noalias() += col * col.transpose(); calc_upper_part(MM, col); rr.noalias() += col * ((it.value() - mean_rating) * alpha); } // Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric. copy_lower_part(MM); chol.compute(hp_LambdaF + alpha * MM); // for > 1K ratings, we have additional thread-level parallellism } else { auto from = M.outerIndexPtr()[idx]; // "from" belongs to [1..m], m - number of movies in M matrix auto to = M.outerIndexPtr()[idx+1]; // "to" belongs to [1..m], m - number of movies in M matrix MatrixNNd MM(MatrixNNd::Zero()); // matrix num_latent x num_latent // #pragma omp parallel for reduction(VectorPlus:rr) reduction(MatrixPlus:MM) #pragma omp parallel for reduction(VectorPlus:rr) reduction(MatrixPlus:MM) schedule(dynamic,200) for(int j = from; j<to; ++j) { // for each nonzeros elemen in the i-th row of M matrix auto val = M.valuePtr()[j]; // value of the j-th nonzeros element from idx-th row of M matrix auto idx = M.innerIndexPtr()[j]; // index "j" of the element [i,j] from M matrix in compressed M matrix auto col = in.col(idx); // vector num_latent x 1 from V matrix: M[i,j] = U[i,:] x V[idx,:] //MM.noalias() += col * col.transpose(); // outer product calc_upper_part(MM, col); rr.noalias() += col * ((val - mean_rating) * alpha); // vector num_latent x 1 } copy_lower_part(MM); chol.compute(hp_LambdaF + alpha * MM); // matrix num_latent x num_latent // chol="lambda_i with *" from formula (14) // lambda_i with * = LambdaU + alpha * MM } if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed"); // now we should calculate formula (14) from the paper // u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) = // = mu_i with * + s * [U]^-1, // where // s is a random vector with N(0, I), // mu_i with * is a vector num_latent x 1, // mu_i with * = [lambda_i with *]^-1 * rr, // lambda_i with * = L * U // Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like: chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector chol.matrixU().solveInPlace(rr); // u_i=U\rr items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix) auto stop = tick(); register_time(idx, 1e6 * (stop - start)); //Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl; assert(rr.norm() > .0); return rr; } // // update ALL movies / users in parallel // void Sys::sample(Sys &in) { iter++; VectorNd sum(VectorNd::Zero()); // sum double norm(0.0); // squared norm MatrixNNd prod(MatrixNNd::Zero()); // outer prod //#pragma omp parallel for reduction(VectorPlus:sum) reduction(MatrixPlus:prod) reduction(+:norm) schedule(dynamic, 1) #pragma omp parallel for reduction(VectorPlus:sum) reduction(MatrixPlus:prod) reduction(+:norm) schedule(dynamic,1) for(int i = from(); i<to(); ++i) { auto r = sample(i,in.items()); MatrixNNd cov = (r * r.transpose()); prod += cov; sum += r; norm += r.squaredNorm(); if (iter >= burnin && Sys::odirname.size()) { aggrMu.col(i) += r; aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent); } send_items(i, i + 1); } const int N = num(); local_sum() = sum; local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1); local_norm() = norm; } void Sys::register_time(int i, double t) { if (measure_perf) sample_time.at(i) += t; } void calc_upper_part(MatrixNNd &m, VectorNd v) { // we use the formula: m = m + v * v.transpose(), but we calculate only an upper part of m matrix for (int j=0; j<num_latent; j++) // columns { for(int i=0; i<=j; i++) // rows { m(i,j) = m(i,j) + v[j] * v[i]; } } } void copy_lower_part(MatrixNNd &m) { // Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric. for (int j=1; j<num_latent; j++) // columns { for(int i=0; i<=j-1; i++) // rows { m(j,i) = m(i,j); } } } <commit_msg>ENH: omp task + thread_local<commit_after>/* * Copyright (c) 2014-2016, imec * All rights reserved. */ #include "error.h" #include "bpmf.h" #include <random> #include <memory> #include <cstdio> #include <iostream> #include <climits> #include <stdexcept> #include "io.h" static const bool measure_perf = false; std::ostream *Sys::os; int Sys::procid = -1; int Sys::nprocs = -1; int Sys::nsims; int Sys::burnin; int Sys::update_freq; double Sys::alpha = 2.0; std::string Sys::odirname = ""; bool Sys::permute = true; bool Sys::verbose = false; unsigned Sys::grain_size; void calc_upper_part(MatrixNNd &m, VectorNd v); // function for calcutation of an upper part of a symmetric matrix: m = v * v.transpose(); void copy_lower_part(MatrixNNd &m); // function to copy an upper part of a symmetric matrix to a lower part // verifies that A has the same non-zero structure as B void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B) { assert(A.cols() == B.cols()); assert(A.rows() == B.rows()); for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros()); } // // Does predictions for prediction matrix T // Computes RMSE (Root Means Square Error) // void Sys::predict(Sys& other, bool all) { int n = (iter < burnin) ? 0 : (iter - burnin); double se(0.0); // squared err double se_avg(0.0); // squared avg err unsigned nump(0); // number of predictions int lo = all ? 0 : from(); int hi = all ? num() : to(); #pragma omp parallel for reduction(+:se,se_avg,nump) for(int k = lo; k<hi; k++) { for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it) { auto m = items().col(it.col()); auto u = other.items().col(it.row()); assert(m.norm() > 0.0); assert(u.norm() > 0.0); const double pred = m.dot(u) + mean_rating; se += sqr(it.value() - pred); // update average prediction double &avg = Pavg.coeffRef(it.row(), it.col()); double delta = pred - avg; avg = (n == 0) ? pred : (avg + delta/n); double &m2 = Pm2.coeffRef(it.row(), it.col()); m2 = (n == 0) ? 0 : m2 + delta * (pred - avg); se_avg += sqr(it.value() - avg); nump++; } } rmse = sqrt( se / nump ); rmse_avg = sqrt( se_avg / nump ); } // // Prints sampling progress // void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) { char buf[1024]; std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling"; sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n", Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6); Sys::cout() << buf; } // // Constructor with that reads MTX files // Sys::Sys(std::string name, std::string fname, std::string probename) : name(name), iter(-1), assigned(false), dom(nprocs+1) { read_matrix(fname, M); read_matrix(probename, T); auto rows = std::max(M.rows(), T.rows()); auto cols = std::max(M.cols(), T.cols()); M.conservativeResize(rows,cols); T.conservativeResize(rows,cols); Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); assert(Sys::nprocs <= (int)Sys::max_procs); } // // Constructs Sys as transpose of existing Sys // Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) { M = Mt.transpose(); Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); } Sys::~Sys() { if (measure_perf) { Sys::cout() << " --------------------\n"; Sys::cout() << name << ": sampling times on " << procid << "\n"; for(int i = from(); i<to(); ++i) { Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n"; } Sys::cout() << " --------------------\n\n"; } } bool Sys::has_prop_posterior() const { return propMu.nonZeros() > 0; } void Sys::add_prop_posterior(std::string fnames) { if (fnames.empty()) return; std::size_t pos = fnames.find_first_of(","); std::string mu_name = fnames.substr(0, pos); std::string lambda_name = fnames.substr(pos+1); read_matrix(mu_name, propMu); read_matrix(lambda_name, propLambda); assert(propMu.cols() == num()); assert(propLambda.cols() == num()); assert(propMu.rows() == num_latent); assert(propLambda.rows() == num_latent * num_latent); } // // Intializes internal Matrices and Vectors // void Sys::init() { //-- M assert(M.rows() > 0 && M.cols() > 0); mean_rating = M.sum() / M.nonZeros(); items().setZero(); sum_map().setZero(); cov_map().setZero(); norm_map().setZero(); col_permutation.setIdentity(num()); if (Sys::odirname.size()) { aggrMu = Eigen::MatrixXd::Zero(num_latent, num()); aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); } Sys::cout() << "mean rating = " << mean_rating << std::endl; Sys::cout() << "total number of ratings in train = " << M.nonZeros() << std::endl; Sys::cout() << "total number of ratings in test = " << T.nonZeros() << std::endl; Sys::cout() << "num " << name << ": " << num() << std::endl; if (has_prop_posterior()) { Sys::cout() << "with propagated posterior" << std::endl; } if (measure_perf) sample_time.resize(num(), .0); } class PrecomputedLLT : public Eigen::LLT<MatrixNNd> { public: void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; } }; // // Update ONE movie or one user // VectorNd Sys::sample(long idx, const MapNXd in) { auto start = tick(); VectorNd hp_mu; MatrixNNd hp_LambdaF; MatrixNNd hp_LambdaL; if (has_prop_posterior()) { hp_mu = propMu.col(idx); hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data()); hp_LambdaL = hp_LambdaF.llt().matrixL(); } else { hp_mu = hp.mu; hp_LambdaF = hp.LambdaF; hp_LambdaL = hp.LambdaL; } int breakpoint1 = 24; int breakpoint2 = 10500; const int count = M.innerVector(idx).nonZeros(); // count of nonzeros elements in idx-th row of M matrix // (how many movies watched idx-th user?). VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14) // if this user movie has less than 1K ratings, // we do a serial rank update if( count < breakpoint1 ) { chol = hp_LambdaL; for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) { auto col = in.col(it.row()); chol.rankUpdate(col, alpha); rr.noalias() += col * ((it.value() - mean_rating) * alpha); } // else we do a serial full cholesky decomposition // (not used if breakpoint1 == breakpoint2) } else if (count < breakpoint2) { MatrixNNd MM(MatrixNNd::Zero()); for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) { auto col = in.col(it.row()); //MM.noalias() += col * col.transpose(); calc_upper_part(MM, col); rr.noalias() += col * ((it.value() - mean_rating) * alpha); } // Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric. copy_lower_part(MM); chol.compute(hp_LambdaF + alpha * MM); // for > 10K ratings, we have additional thread-level parallellism } else { const int task_size = count / 100; auto from = M.outerIndexPtr()[idx]; // "from" belongs to [1..m], m - number of movies in M matrix auto to = M.outerIndexPtr()[idx+1]; // "to" belongs to [1..m], m - number of movies in M matrix MatrixNNd MM(MatrixNNd::Zero()); // matrix num_latent x num_latent thread_vector<VectorNd> rrs(VectorNd::Zero()); thread_vector<MatrixNNd> MMs(MatrixNNd::Zero()); for(int i = from; i<to; i+=task_size) { #pragma omp task shared(rrs, MMs) for(int j = i; j<std::min(i+task_size, to); j++) { // for each nonzeros elemen in the i-th row of M matrix auto val = M.valuePtr()[j]; // value of the j-th nonzeros element from idx-th row of M matrix auto idx = M.innerIndexPtr()[j]; // index "j" of the element [i,j] from M matrix in compressed M matrix auto col = in.col(idx); // vector num_latent x 1 from V matrix: M[i,j] = U[i,:] x V[idx,:] //MM.noalias() += col * col.transpose(); // outer product calc_upper_part(MMs.local(), col); rrs.local().noalias() += col * ((val - mean_rating) * alpha); // vector num_latent x 1 } } #pragma omp taskwait // accumulate MM += MMs.combine(); rr += rrs.combine(); copy_lower_part(MM); chol.compute(hp_LambdaF + alpha * MM); // matrix num_latent x num_latent // chol="lambda_i with *" from formula (14) // lambda_i with * = LambdaU + alpha * MM } if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed"); // now we should calculate formula (14) from the paper // u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) = // = mu_i with * + s * [U]^-1, // where // s is a random vector with N(0, I), // mu_i with * is a vector num_latent x 1, // mu_i with * = [lambda_i with *]^-1 * rr, // lambda_i with * = L * U // Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like: chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector chol.matrixU().solveInPlace(rr); // u_i=U\rr items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix) auto stop = tick(); register_time(idx, 1e6 * (stop - start)); //Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl; assert(rr.norm() > .0); return rr; } // // update ALL movies / users in parallel // void Sys::sample(Sys &in) { iter++; thread_vector<VectorNd> sums(VectorNd::Zero()); // sum thread_vector<double> norms(0.0); // squared norm thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod #pragma omp parallel for schedule(guided) for (int i = from(); i < to(); ++i) { #pragma omp task { auto r = sample(i, in.items()); MatrixNNd cov = (r * r.transpose()); prods.local() += cov; sums.local() += r; norms.local() += r.squaredNorm(); if (iter >= burnin && Sys::odirname.size()) { aggrMu.col(i) += r; aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent); } send_items(i, i + 1); } } VectorNd sum = sums.combine(); MatrixNNd prod = prods.combine(); double norm = norms.combine(); const int N = num(); local_sum() = sum; local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1); local_norm() = norm; } void Sys::register_time(int i, double t) { if (measure_perf) sample_time.at(i) += t; } void calc_upper_part(MatrixNNd &m, VectorNd v) { // we use the formula: m = m + v * v.transpose(), but we calculate only an upper part of m matrix for (int j=0; j<num_latent; j++) // columns { for(int i=0; i<=j; i++) // rows { m(i,j) = m(i,j) + v[j] * v[i]; } } } void copy_lower_part(MatrixNNd &m) { // Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric. for (int j=1; j<num_latent; j++) // columns { for(int i=0; i<=j-1; i++) // rows { m(j,i) = m(i,j); } } } <|endoftext|>
<commit_before>#include <iostream> #include <interval/jl_basis.h> using namespace std; using namespace WaveletTL; int main() { cout << "Testing wavelet bases from [JL] ..." << endl; typedef JLBasis Basis; typedef Basis::Index Index; Basis basis; cout << "- the default wavelet index: " << Index() << endl; // cout << "- leftmost generator on the coarsest level: " << first_generator(&basis, basis.j0()) << endl; // cout << "- rightmost generator on the coarsest level: " << last_generator(&basis, basis.j0()) << endl; // cout << "- leftmost wavelet on the coarsest level: " << first_wavelet(&basis, basis.j0()) << endl; // cout << "- rightmost wavelet on the coarsest level: " << last_wavelet(&basis, basis.j0()) << endl; return 0; } <commit_msg>basic index functionality of JLBasis<commit_after>#include <iostream> #include <interval/jl_basis.h> using namespace std; using namespace WaveletTL; int main() { cout << "Testing wavelet bases from [JL] ..." << endl; typedef JLBasis Basis; typedef Basis::Index Index; Basis basis; cout << "- the default wavelet index: " << Index() << endl; cout << "- leftmost generator on the coarsest level: " << first_generator(&basis, basis.j0()) << endl; cout << "- rightmost generator on the coarsest level: " << last_generator(&basis, basis.j0()) << endl; cout << "- leftmost wavelet on the coarsest level: " << first_wavelet(&basis, basis.j0()) << endl; cout << "- rightmost wavelet on the coarsest level: " << last_wavelet(&basis, basis.j0()) << endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "ChunkedIstream.hxx" #include "FacadeIstream.hxx" #include "Bucket.hxx" #include "New.hxx" #include "UnusedPtr.hxx" #include "util/ConstBuffer.hxx" #include "util/Cast.hxx" #include "util/DestructObserver.hxx" #include "util/HexFormat.h" #include <algorithm> #include <assert.h> #include <string.h> class ChunkedIstream final : public FacadeIstream, DestructAnchor { /** * This flag is true while writing the buffer inside _Read(). * OnData() will check it, and refuse to accept more data from the * input. This avoids writing the buffer recursively. */ bool writing_buffer = false; char buffer[7]; size_t buffer_sent = sizeof(buffer); size_t missing_from_current_chunk = 0; public: ChunkedIstream(struct pool &p, UnusedIstreamPtr &&_input) noexcept :FacadeIstream(p, std::move(_input)) {} /* virtual methods from class Istream */ void _Read() noexcept override; void _FillBucketList(IstreamBucketList &list) override; size_t _ConsumeBucketList(size_t nbytes) noexcept override; void _Close() noexcept override; /* virtual methods from class IstreamHandler */ bool OnIstreamReady() noexcept override { return InvokeReady(); } size_t OnData(const void *data, size_t length) noexcept override; void OnEof() noexcept override; void OnError(std::exception_ptr ep) noexcept override; private: bool IsBufferEmpty() const noexcept { assert(buffer_sent <= sizeof(buffer)); return buffer_sent == sizeof(buffer); } /** set the buffer length and return a pointer to the first byte */ char *SetBuffer(size_t length) noexcept { assert(IsBufferEmpty()); assert(length <= sizeof(buffer)); buffer_sent = sizeof(buffer) - length; return buffer + buffer_sent; } /** append data to the buffer */ void AppendToBuffer(const void *data, size_t length) noexcept; void StartChunk(size_t length) noexcept; ConstBuffer<void> ReadBuffer() noexcept { return { buffer + buffer_sent, sizeof(buffer) - buffer_sent }; } /** * Returns true if the buffer is consumed. */ bool SendBuffer() noexcept; /** * Wrapper for SendBuffer() that sets and clears the * #writing_buffer flag. This requires acquiring a pool reference * to do that safely. * * @return true if the buffer is consumed. */ bool SendBuffer2() noexcept; size_t Feed(const char *data, size_t length) noexcept; }; void ChunkedIstream::AppendToBuffer(const void *data, size_t length) noexcept { assert(data != nullptr); assert(length > 0); assert(length <= buffer_sent); const auto old = ReadBuffer(); #ifndef NDEBUG /* simulate a buffer reset; if we don't do this, an assertion in SetBuffer() fails (which is invalid for this special case) */ buffer_sent = sizeof(buffer); #endif auto dest = SetBuffer(old.size + length); memmove(dest, old.data, old.size); dest += old.size; memcpy(dest, data, length); } void ChunkedIstream::StartChunk(size_t length) noexcept { assert(length > 0); assert(IsBufferEmpty()); assert(missing_from_current_chunk == 0); if (length > 0x8000) /* maximum chunk size is 32kB for now */ length = 0x8000; missing_from_current_chunk = length; auto p = SetBuffer(6); format_uint16_hex_fixed(p, (uint16_t)length); p[4] = '\r'; p[5] = '\n'; } bool ChunkedIstream::SendBuffer() noexcept { auto r = ReadBuffer(); if (r.empty()) return true; size_t nbytes = InvokeData(r.data, r.size); if (nbytes > 0) buffer_sent += nbytes; return nbytes == r.size; } bool ChunkedIstream::SendBuffer2() noexcept { const DestructObserver destructed(*this); assert(!writing_buffer); writing_buffer = true; const bool result = SendBuffer(); if (!destructed) writing_buffer = false; return result; } inline size_t ChunkedIstream::Feed(const char *data, size_t length) noexcept { const DestructObserver destructed(*this); size_t total = 0, rest, nbytes; assert(input.IsDefined()); do { assert(!writing_buffer); if (IsBufferEmpty() && missing_from_current_chunk == 0) StartChunk(length - total); if (!SendBuffer()) return destructed ? 0 : total; assert(IsBufferEmpty()); if (missing_from_current_chunk == 0) { /* we have just written the previous chunk trailer; re-start this loop to start a new chunk */ nbytes = rest = 0; continue; } rest = length - total; if (rest > missing_from_current_chunk) rest = missing_from_current_chunk; nbytes = InvokeData(data + total, rest); if (nbytes == 0) return destructed ? 0 : total; total += nbytes; missing_from_current_chunk -= nbytes; if (missing_from_current_chunk == 0) { /* a chunk ends with "\r\n" */ char *p = SetBuffer(2); p[0] = '\r'; p[1] = '\n'; } } while ((!IsBufferEmpty() || total < length) && nbytes == rest); return total; } /* * istream handler * */ size_t ChunkedIstream::OnData(const void *data, size_t length) noexcept { if (writing_buffer) /* this is a recursive call from _Read(): bail out */ return 0; return Feed((const char*)data, length); } void ChunkedIstream::OnEof() noexcept { assert(input.IsDefined()); assert(missing_from_current_chunk == 0); input.Clear(); /* write EOF chunk (length 0) */ AppendToBuffer("0\r\n\r\n", 5); /* flush the buffer */ if (SendBuffer()) DestroyEof(); } void ChunkedIstream::OnError(std::exception_ptr ep) noexcept { assert(input.IsDefined()); input.Clear(); DestroyError(ep); } /* * istream implementation * */ void ChunkedIstream::_Read() noexcept { if (!SendBuffer2()) return; if (!input.IsDefined()) { DestroyEof(); return; } if (IsBufferEmpty() && missing_from_current_chunk == 0) { off_t available = input.GetAvailable(true); if (available > 0) { StartChunk(available); if (!SendBuffer2()) return; } } input.Read(); } void ChunkedIstream::_FillBucketList(IstreamBucketList &list) { if (!input.IsDefined()) { // TODO: generate EOF chunk list.SetMore(); return; } auto b = ReadBuffer(); if (b.empty() && missing_from_current_chunk == 0) { off_t available = input.GetAvailable(true); if (available > 0) { StartChunk(available); b = ReadBuffer(); } } if (!b.empty()) list.Push(b); if (missing_from_current_chunk > 0) { assert(input.IsDefined()); IstreamBucketList sub; try { input.FillBucketList(sub); } catch (...) { Destroy(); throw; } list.SpliceBuffersFrom(sub, missing_from_current_chunk); } list.SetMore(); } size_t ChunkedIstream::_ConsumeBucketList(size_t nbytes) noexcept { size_t total = 0; size_t size = ReadBuffer().size; if (size > nbytes) size = nbytes; if (size > 0) { buffer_sent += size; Consumed(size); nbytes -= size; total += size; } size = std::min(nbytes, missing_from_current_chunk); if (size > 0) { assert(input.IsDefined()); size = input.ConsumeBucketList(size); Consumed(size); nbytes -= size; total += size; if (nbytes > 0) input.ClearAndClose(); missing_from_current_chunk -= size; if (missing_from_current_chunk == 0) { /* a chunk ends with "\r\n" */ char *p = SetBuffer(2); p[0] = '\r'; p[1] = '\n'; } } return total; } void ChunkedIstream::_Close() noexcept { if (input.IsDefined()) input.ClearAndClose(); Destroy(); } /* * constructor * */ UnusedIstreamPtr istream_chunked_new(struct pool &pool, UnusedIstreamPtr input) noexcept { return NewIstreamPtr<ChunkedIstream>(pool, std::move(input)); } <commit_msg>istream/chunked: move code to ConsumeBuffer()<commit_after>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "ChunkedIstream.hxx" #include "FacadeIstream.hxx" #include "Bucket.hxx" #include "New.hxx" #include "UnusedPtr.hxx" #include "util/ConstBuffer.hxx" #include "util/Cast.hxx" #include "util/DestructObserver.hxx" #include "util/HexFormat.h" #include <algorithm> #include <assert.h> #include <string.h> class ChunkedIstream final : public FacadeIstream, DestructAnchor { /** * This flag is true while writing the buffer inside _Read(). * OnData() will check it, and refuse to accept more data from the * input. This avoids writing the buffer recursively. */ bool writing_buffer = false; char buffer[7]; size_t buffer_sent = sizeof(buffer); size_t missing_from_current_chunk = 0; public: ChunkedIstream(struct pool &p, UnusedIstreamPtr &&_input) noexcept :FacadeIstream(p, std::move(_input)) {} /* virtual methods from class Istream */ void _Read() noexcept override; void _FillBucketList(IstreamBucketList &list) override; size_t _ConsumeBucketList(size_t nbytes) noexcept override; void _Close() noexcept override; /* virtual methods from class IstreamHandler */ bool OnIstreamReady() noexcept override { return InvokeReady(); } size_t OnData(const void *data, size_t length) noexcept override; void OnEof() noexcept override; void OnError(std::exception_ptr ep) noexcept override; private: bool IsBufferEmpty() const noexcept { assert(buffer_sent <= sizeof(buffer)); return buffer_sent == sizeof(buffer); } /** set the buffer length and return a pointer to the first byte */ char *SetBuffer(size_t length) noexcept { assert(IsBufferEmpty()); assert(length <= sizeof(buffer)); buffer_sent = sizeof(buffer) - length; return buffer + buffer_sent; } /** append data to the buffer */ void AppendToBuffer(const void *data, size_t length) noexcept; void StartChunk(size_t length) noexcept; ConstBuffer<void> ReadBuffer() noexcept { return { buffer + buffer_sent, sizeof(buffer) - buffer_sent }; } size_t ConsumeBuffer(size_t nbytes) noexcept { size_t size = ReadBuffer().size; if (size > nbytes) size = nbytes; if (size > 0) { buffer_sent += size; Consumed(size); } return size; } /** * Returns true if the buffer is consumed. */ bool SendBuffer() noexcept; /** * Wrapper for SendBuffer() that sets and clears the * #writing_buffer flag. This requires acquiring a pool reference * to do that safely. * * @return true if the buffer is consumed. */ bool SendBuffer2() noexcept; size_t Feed(const char *data, size_t length) noexcept; }; void ChunkedIstream::AppendToBuffer(const void *data, size_t length) noexcept { assert(data != nullptr); assert(length > 0); assert(length <= buffer_sent); const auto old = ReadBuffer(); #ifndef NDEBUG /* simulate a buffer reset; if we don't do this, an assertion in SetBuffer() fails (which is invalid for this special case) */ buffer_sent = sizeof(buffer); #endif auto dest = SetBuffer(old.size + length); memmove(dest, old.data, old.size); dest += old.size; memcpy(dest, data, length); } void ChunkedIstream::StartChunk(size_t length) noexcept { assert(length > 0); assert(IsBufferEmpty()); assert(missing_from_current_chunk == 0); if (length > 0x8000) /* maximum chunk size is 32kB for now */ length = 0x8000; missing_from_current_chunk = length; auto p = SetBuffer(6); format_uint16_hex_fixed(p, (uint16_t)length); p[4] = '\r'; p[5] = '\n'; } bool ChunkedIstream::SendBuffer() noexcept { auto r = ReadBuffer(); if (r.empty()) return true; size_t nbytes = InvokeData(r.data, r.size); if (nbytes > 0) buffer_sent += nbytes; return nbytes == r.size; } bool ChunkedIstream::SendBuffer2() noexcept { const DestructObserver destructed(*this); assert(!writing_buffer); writing_buffer = true; const bool result = SendBuffer(); if (!destructed) writing_buffer = false; return result; } inline size_t ChunkedIstream::Feed(const char *data, size_t length) noexcept { const DestructObserver destructed(*this); size_t total = 0, rest, nbytes; assert(input.IsDefined()); do { assert(!writing_buffer); if (IsBufferEmpty() && missing_from_current_chunk == 0) StartChunk(length - total); if (!SendBuffer()) return destructed ? 0 : total; assert(IsBufferEmpty()); if (missing_from_current_chunk == 0) { /* we have just written the previous chunk trailer; re-start this loop to start a new chunk */ nbytes = rest = 0; continue; } rest = length - total; if (rest > missing_from_current_chunk) rest = missing_from_current_chunk; nbytes = InvokeData(data + total, rest); if (nbytes == 0) return destructed ? 0 : total; total += nbytes; missing_from_current_chunk -= nbytes; if (missing_from_current_chunk == 0) { /* a chunk ends with "\r\n" */ char *p = SetBuffer(2); p[0] = '\r'; p[1] = '\n'; } } while ((!IsBufferEmpty() || total < length) && nbytes == rest); return total; } /* * istream handler * */ size_t ChunkedIstream::OnData(const void *data, size_t length) noexcept { if (writing_buffer) /* this is a recursive call from _Read(): bail out */ return 0; return Feed((const char*)data, length); } void ChunkedIstream::OnEof() noexcept { assert(input.IsDefined()); assert(missing_from_current_chunk == 0); input.Clear(); /* write EOF chunk (length 0) */ AppendToBuffer("0\r\n\r\n", 5); /* flush the buffer */ if (SendBuffer()) DestroyEof(); } void ChunkedIstream::OnError(std::exception_ptr ep) noexcept { assert(input.IsDefined()); input.Clear(); DestroyError(ep); } /* * istream implementation * */ void ChunkedIstream::_Read() noexcept { if (!SendBuffer2()) return; if (!input.IsDefined()) { DestroyEof(); return; } if (IsBufferEmpty() && missing_from_current_chunk == 0) { off_t available = input.GetAvailable(true); if (available > 0) { StartChunk(available); if (!SendBuffer2()) return; } } input.Read(); } void ChunkedIstream::_FillBucketList(IstreamBucketList &list) { if (!input.IsDefined()) { // TODO: generate EOF chunk list.SetMore(); return; } auto b = ReadBuffer(); if (b.empty() && missing_from_current_chunk == 0) { off_t available = input.GetAvailable(true); if (available > 0) { StartChunk(available); b = ReadBuffer(); } } if (!b.empty()) list.Push(b); if (missing_from_current_chunk > 0) { assert(input.IsDefined()); IstreamBucketList sub; try { input.FillBucketList(sub); } catch (...) { Destroy(); throw; } list.SpliceBuffersFrom(sub, missing_from_current_chunk); } list.SetMore(); } size_t ChunkedIstream::_ConsumeBucketList(size_t nbytes) noexcept { size_t total = 0; size_t size = ConsumeBuffer(nbytes); nbytes -= size; total += size; size = std::min(nbytes, missing_from_current_chunk); if (size > 0) { assert(input.IsDefined()); size = input.ConsumeBucketList(size); Consumed(size); nbytes -= size; total += size; if (nbytes > 0) input.ClearAndClose(); missing_from_current_chunk -= size; if (missing_from_current_chunk == 0) { /* a chunk ends with "\r\n" */ char *p = SetBuffer(2); p[0] = '\r'; p[1] = '\n'; } } return total; } void ChunkedIstream::_Close() noexcept { if (input.IsDefined()) input.ClearAndClose(); Destroy(); } /* * constructor * */ UnusedIstreamPtr istream_chunked_new(struct pool &pool, UnusedIstreamPtr input) noexcept { return NewIstreamPtr<ChunkedIstream>(pool, std::move(input)); } <|endoftext|>
<commit_before> #include <iostream> #include <cmath> #include <cerrno> #include <cassert> #include <vector> #include <sstream> #include <tbb/parallel_for.h> #include <tbb/parallel_invoke.h> #include <tbb/blocked_range.h> #include <tbb/tick_count.h> #include <tbb/scalable_allocator.h> #include <tbb/concurrent_queue.h> #include <tbb/compat/thread> #include <tbb/task.h> #include <tbb/task_scheduler_init.h> #include <tbb/task_scheduler_observer.h> #include <tbb/atomic.h> #include <zlib.h> #include <openssl/sha.h> #include "cvmfs/fs_traversal.h" using namespace tbb; static const std::string input_path = "../benchmark_repo"; static const std::string output_path = "/Volumes/ramdisk/output"; void Print(const std::string &msg) { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); std::cout << msg << std::endl; pthread_mutex_unlock(&mutex); } template<typename T, class A = std::allocator<T> > class Buffer { public: Buffer() : size_(0), used_bytes_(0), buffer_(nullptr) {} Buffer(const size_t size) : size_(0) { Allocate(size); } Buffer(Buffer &&other) { *this = std::move(other); } Buffer& operator=(Buffer &&other) { size_ = other.size(); buffer_ = (size_ > 0) ? other.buffer_ : nullptr; other.size_ = 0; other.buffer_ = nullptr; return *this; } ~Buffer() { Deallocate(); } void Allocate(const size_t size) { assert (!Initialized()); size_ = size; buffer_ = A().allocate(size_); } bool Initialized() const { return size_ > 0; } typename A::pointer ptr() { assert (Initialized()); return buffer_; } const typename A::pointer ptr() const { assert (Initialized()); return buffer_; } operator T*() { return ptr(); } void SetUsedBytes(const size_t bytes) { used_bytes_ = bytes; } const size_t size() const { return size_; } const size_t used_bytes() const { return used_bytes_; } private: Buffer(const Buffer &other) { assert (false); } // no copy! Buffer& operator=(const Buffer& other) { assert (false); } void Deallocate() { if (size_ == 0) { return; } A().deallocate(buffer_, size_); std::stringstream ss; ss << "freeing: " << size_ << " bytes"; Print(ss.str()); } private: size_t used_bytes_; size_t size_; typename A::pointer buffer_; }; typedef Buffer<unsigned char, scalable_allocator<unsigned char> > CharBuffer; class File; class IoDispatcher; class CruncherTask : public task { public: CruncherTask(File *file, IoDispatcher *io_dispatcher) : file_(file), io_dispatcher_(io_dispatcher) {} task* execute(); private: File *file_; IoDispatcher *io_dispatcher_; }; class File { public: File() : path_(""), uncompressed_buffer_(NULL), compressed_buffer_(NULL) {} explicit File(const std::string &path) : path_(path) {} const std::string& path() const { return path_; } CharBuffer& uncompressed_buffer() { return uncompressed_buffer_; } CharBuffer& compressed_buffer() { return compressed_buffer_; } SHA_CTX& sha1_context() { return sha1_context_; } std::string& sha1() { return sha1_; } bool IsDummy() const { return path_.empty(); } void SpawnTbbTask(IoDispatcher *io_dispatcher) { CruncherTask *t = new(task::allocate_root()) CruncherTask(this, io_dispatcher); task::enqueue(*t); } public: bool Read() { //return ReadOldfashion(); //return ReadMmap(); return ReadFd(); } bool Write() { assert (sha1_.size() > 0); assert (compressed_buffer_.Initialized()); return WriteOldfashion(); //return WriteFd(); } size_t Compress() { assert (uncompressed_buffer_.Initialized()); z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.next_in = Z_NULL; stream.avail_in = 0; const int retval = deflateInit(&stream, Z_DEFAULT_COMPRESSION); if (retval != 0) { return 0; } const size_t output_size = deflateBound(&stream, uncompressed_buffer_.size()); compressed_buffer_.Allocate(output_size); stream.avail_in = uncompressed_buffer_.size(); stream.next_in = uncompressed_buffer_.ptr(); stream.avail_out = output_size; stream.next_out = compressed_buffer_.ptr(); const int result = deflate(&stream, Z_FINISH); if (result != Z_STREAM_END) { return 0; } compressed_buffer_.SetUsedBytes(stream.total_out); return stream.total_out; } void Hash() { assert (uncompressed_buffer_.Initialized()); SHA1_Init(&sha1_context_); SHA1_Update(&sha1_context_, uncompressed_buffer_.ptr(), uncompressed_buffer_.size()); unsigned char sha[20]; char sha_string[41]; SHA1_Final(sha, &sha1_context_); for (unsigned i = 0; i < 20; ++i) { char dgt1 = (unsigned)sha[i] / 16; char dgt2 = (unsigned)sha[i] % 16; dgt1 += (dgt1 <= 9) ? '0' : 'a' - 10; dgt2 += (dgt2 <= 9) ? '0' : 'a' - 10; sha_string[i*2] = dgt1; sha_string[i*2+1] = dgt2; } sha_string[40] = '\0'; sha1_ = static_cast<char*>(sha_string); } protected: bool ReadOldfashion() { // open file FILE *f = fopen(path_.c_str(), "r"); if (f == NULL) { std::cout << "cannot open file: " << path_ << " errno: " << errno << std::endl; return false; } // get file size fseek(f, 0, SEEK_END); const size_t size = ftell(f); rewind(f); // allocate buffer uncompressed_buffer_.Allocate(size); // read the file chunk wise do { const size_t read_bytes = fread(uncompressed_buffer_.ptr(), 1, size, f); } while(!feof(f) && !ferror(f)); // close the file fclose(f); return true; } bool ReadMmap() { // open the file int fd; if ((fd = open(path_.c_str(), O_RDONLY, 0)) == -1) { std::cout << "cannot open file: " << path_ << std::endl; return false; } // get file size struct stat64 filesize; if (fstat64(fd, &filesize) != 0) { std::cout << "failed to fstat file: " << path_ << std::endl; close(fd); return false; } void *mapping = NULL; if (filesize.st_size > 0) { // map the given file into memory mapping = mmap(NULL, filesize.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (mapping == MAP_FAILED) { std::cout << "failed to mmap file: " << path_ << std::endl; close(fd); return false; } } // save results uncompressed_buffer_.Allocate(filesize.st_size); memcpy(uncompressed_buffer_.ptr(), mapping, filesize.st_size); // do unmap if ((munmap(static_cast<void*>(mapping), filesize.st_size) != 0) || (close(fd) != 0)) { std::cout << "failed to unmap file: " << path_ << std::endl; } return true; } bool ReadFd() { // open the file int fd; if ((fd = open(path_.c_str(), O_RDONLY, 0)) == -1) { std::cout << "cannot open file: " << path_ << std::endl; return false; } // get file size struct stat64 filesize; if (fstat64(fd, &filesize) != 0) { std::cout << "failed to fstat file: " << path_ << std::endl; close(fd); return false; } // allocate space uncompressed_buffer_.Allocate(filesize.st_size); if (read(fd, uncompressed_buffer_.ptr(), filesize.st_size) != filesize.st_size) { std::cout << "failed to read file: " << path_ << std::endl; close(fd); return false; } // close the file close(fd); return true; } bool WriteOldfashion() { const std::string path = output_path + "/" + sha1_; // open file FILE *f = fopen(path.c_str(), "w+"); if (f == NULL) { std::cout << "cannot open file: " << path << " errno: " << errno << std::endl; return false; } // write buffer const size_t to_write = compressed_buffer_.used_bytes(); const size_t written = fwrite(compressed_buffer_.ptr(), 1, to_write, f); if (written != to_write) { std::cout << "failed to write " << to_write << " bytes " << "to file: " << path << std::endl; return false; } // close the file fclose(f); return true; } bool WriteFd() { // open the file int fd; if ((fd = open(path_.c_str(), O_WRONLY | O_CREAT, 0)) == -1) { std::cout << "cannot open file: " << path_ << std::endl; return false; } // write to file const size_t bytes = compressed_buffer_.used_bytes(); if (write(fd, compressed_buffer_.ptr(), bytes) != bytes) { std::cout << "failed to read file: " << path_ << std::endl; close(fd); return false; } // close the file close(fd); return true; } private: std::string path_; CruncherTask *cruncher_task_; CharBuffer uncompressed_buffer_; CharBuffer compressed_buffer_; SHA_CTX sha1_context_; std::string sha1_; }; typedef std::vector<File> FileVector; #define MEASURE_IO_TIME class IoDispatcher { public: IoDispatcher() : files_in_flight_(0), file_count_(0), all_enqueued_(false), read_thread_(IoDispatcher::ReadThread, this), write_thread_(IoDispatcher::WriteThread, this) {} ~IoDispatcher() { Wait(); std::cout << "Reads took: " << read_time_ << std::endl << " average: " << (read_time_ / file_count_) << std::endl << "Writes took: " << write_time_ << std::endl << " average: " << (write_time_ / file_count_) << std::endl; } void Wait() { all_enqueued_ = true; read_queue_.push(nullptr); if (read_thread_.joinable()) { read_thread_.join(); } if (write_thread_.joinable()) { write_thread_.join(); } } void Read(File *file) { read_queue_.push(file); ++file_count_; } void Write(File *file) { write_queue_.push(file); } protected: static void ReadThread(IoDispatcher *dispatcher) { task_scheduler_init sched(3); while (true) { File *file; dispatcher->read_queue_.pop(file); if (file == nullptr) { break; } dispatcher->files_in_flight_++; #ifdef MEASURE_IO_TIME tick_count start = tick_count::now(); file->Read(); tick_count end = tick_count::now(); dispatcher->read_time_ += (end - start).seconds(); #else file->Read(); #endif file->SpawnTbbTask(dispatcher); } } static void WriteThread(IoDispatcher *dispatcher) { while (true) { File *file; dispatcher->write_queue_.pop(file); if (file == nullptr) { break; } #ifdef MEASURE_IO_TIME tick_count start = tick_count::now(); file->Write(); tick_count end = tick_count::now(); dispatcher->write_time_ += (end - start).seconds(); #else file->Write(); #endif dispatcher->files_in_flight_--; if (dispatcher->files_in_flight_ == 0 && dispatcher->all_enqueued_) { break; } } } private: atomic<unsigned int> files_in_flight_; atomic<bool> all_enqueued_; unsigned int file_count_; double read_time_; double write_time_; concurrent_bounded_queue<File*> read_queue_; concurrent_bounded_queue<File*> write_queue_; tbb_thread read_thread_; tbb_thread write_thread_; }; task* CruncherTask::execute() { file_->Compress(); file_->Hash(); io_dispatcher_->Write(file_); return NULL; } class TraversalDelegate { public: TraversalDelegate(IoDispatcher *io_dispatcher) : io_dispatcher_(io_dispatcher) {} void FileCb(const std::string &relative_path, const std::string &file_name) { const std::string path = relative_path + "/" + file_name; File *file = new File(path); io_dispatcher_->Read(file); } private: IoDispatcher *io_dispatcher_; }; class Observer : public task_scheduler_observer { void on_scheduler_entry(bool is_worker) { Print("ENTER"); } void on_scheduler_exit(bool is_worker) { Print("EXIT"); } }; int main() { tick_count start, end; tick_count all_start, all_end; Observer observer; observer.observe(); all_start = tick_count::now(); IoDispatcher io_dispatcher; TraversalDelegate delegate(&io_dispatcher); start = tick_count::now(); FileSystemTraversal<TraversalDelegate> t(&delegate, "", true); t.fn_new_file = &TraversalDelegate::FileCb; t.Recurse(input_path); end = tick_count::now(); std::cout << "recursion took: " << (end - start).seconds() << " seconds" << std::endl; Print("going to wait now..."); io_dispatcher.Wait(); Print("waited..."); all_end = tick_count::now(); std::cout << "overall time: " << (all_end - all_start).seconds() << " seconds" << std::endl; return 0; } <commit_msg>find optimal number of threads<commit_after> #include <iostream> #include <cmath> #include <cerrno> #include <cassert> #include <vector> #include <sstream> #include <tbb/parallel_for.h> #include <tbb/parallel_invoke.h> #include <tbb/blocked_range.h> #include <tbb/tick_count.h> #include <tbb/scalable_allocator.h> #include <tbb/concurrent_queue.h> #include <tbb/compat/thread> #include <tbb/task.h> #include <tbb/task_scheduler_init.h> #include <tbb/task_scheduler_observer.h> #include <tbb/atomic.h> #include <zlib.h> #include <openssl/sha.h> #include "cvmfs/fs_traversal.h" using namespace tbb; static const std::string input_path = "../benchmark_repo"; static const std::string output_path = "/Volumes/ramdisk/output"; void Print(const std::string &msg) { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); std::cout << msg << std::endl; pthread_mutex_unlock(&mutex); } template<typename T, class A = std::allocator<T> > class Buffer { public: Buffer() : size_(0), used_bytes_(0), buffer_(nullptr) {} Buffer(const size_t size) : size_(0) { Allocate(size); } Buffer(Buffer &&other) { *this = std::move(other); } Buffer& operator=(Buffer &&other) { size_ = other.size(); buffer_ = (size_ > 0) ? other.buffer_ : nullptr; other.size_ = 0; other.buffer_ = nullptr; return *this; } ~Buffer() { Deallocate(); } void Allocate(const size_t size) { assert (!Initialized()); size_ = size; buffer_ = A().allocate(size_); } bool Initialized() const { return size_ > 0; } typename A::pointer ptr() { assert (Initialized()); return buffer_; } const typename A::pointer ptr() const { assert (Initialized()); return buffer_; } operator T*() { return ptr(); } void SetUsedBytes(const size_t bytes) { used_bytes_ = bytes; } const size_t size() const { return size_; } const size_t used_bytes() const { return used_bytes_; } private: Buffer(const Buffer &other) { assert (false); } // no copy! Buffer& operator=(const Buffer& other) { assert (false); } void Deallocate() { if (size_ == 0) { return; } A().deallocate(buffer_, size_); std::stringstream ss; ss << "freeing: " << size_ << " bytes"; Print(ss.str()); } private: size_t used_bytes_; size_t size_; typename A::pointer buffer_; }; typedef Buffer<unsigned char, scalable_allocator<unsigned char> > CharBuffer; class File; class IoDispatcher; class CruncherTask : public task { public: CruncherTask(File *file, IoDispatcher *io_dispatcher) : file_(file), io_dispatcher_(io_dispatcher) {} task* execute(); private: File *file_; IoDispatcher *io_dispatcher_; }; class File { public: File() : path_(""), uncompressed_buffer_(NULL), compressed_buffer_(NULL) {} explicit File(const std::string &path) : path_(path) {} const std::string& path() const { return path_; } CharBuffer& uncompressed_buffer() { return uncompressed_buffer_; } CharBuffer& compressed_buffer() { return compressed_buffer_; } SHA_CTX& sha1_context() { return sha1_context_; } std::string& sha1() { return sha1_; } bool IsDummy() const { return path_.empty(); } void SpawnTbbTask(IoDispatcher *io_dispatcher) { CruncherTask *t = new(task::allocate_root()) CruncherTask(this, io_dispatcher); task::enqueue(*t); } public: bool Read() { //return ReadOldfashion(); //return ReadMmap(); return ReadFd(); } bool Write() { assert (sha1_.size() > 0); assert (compressed_buffer_.Initialized()); return WriteOldfashion(); //return WriteFd(); } size_t Compress() { assert (uncompressed_buffer_.Initialized()); z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.next_in = Z_NULL; stream.avail_in = 0; const int retval = deflateInit(&stream, Z_DEFAULT_COMPRESSION); if (retval != 0) { return 0; } const size_t output_size = deflateBound(&stream, uncompressed_buffer_.size()); compressed_buffer_.Allocate(output_size); stream.avail_in = uncompressed_buffer_.size(); stream.next_in = uncompressed_buffer_.ptr(); stream.avail_out = output_size; stream.next_out = compressed_buffer_.ptr(); const int result = deflate(&stream, Z_FINISH); if (result != Z_STREAM_END) { return 0; } compressed_buffer_.SetUsedBytes(stream.total_out); return stream.total_out; } void Hash() { assert (uncompressed_buffer_.Initialized()); SHA1_Init(&sha1_context_); SHA1_Update(&sha1_context_, uncompressed_buffer_.ptr(), uncompressed_buffer_.size()); unsigned char sha[20]; char sha_string[41]; SHA1_Final(sha, &sha1_context_); for (unsigned i = 0; i < 20; ++i) { char dgt1 = (unsigned)sha[i] / 16; char dgt2 = (unsigned)sha[i] % 16; dgt1 += (dgt1 <= 9) ? '0' : 'a' - 10; dgt2 += (dgt2 <= 9) ? '0' : 'a' - 10; sha_string[i*2] = dgt1; sha_string[i*2+1] = dgt2; } sha_string[40] = '\0'; sha1_ = static_cast<char*>(sha_string); } protected: bool ReadOldfashion() { // open file FILE *f = fopen(path_.c_str(), "r"); if (f == NULL) { std::cout << "cannot open file: " << path_ << " errno: " << errno << std::endl; return false; } // get file size fseek(f, 0, SEEK_END); const size_t size = ftell(f); rewind(f); // allocate buffer uncompressed_buffer_.Allocate(size); // read the file chunk wise do { const size_t read_bytes = fread(uncompressed_buffer_.ptr(), 1, size, f); } while(!feof(f) && !ferror(f)); // close the file fclose(f); return true; } bool ReadMmap() { // open the file int fd; if ((fd = open(path_.c_str(), O_RDONLY, 0)) == -1) { std::cout << "cannot open file: " << path_ << std::endl; return false; } // get file size struct stat64 filesize; if (fstat64(fd, &filesize) != 0) { std::cout << "failed to fstat file: " << path_ << std::endl; close(fd); return false; } void *mapping = NULL; if (filesize.st_size > 0) { // map the given file into memory mapping = mmap(NULL, filesize.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (mapping == MAP_FAILED) { std::cout << "failed to mmap file: " << path_ << std::endl; close(fd); return false; } } // save results uncompressed_buffer_.Allocate(filesize.st_size); memcpy(uncompressed_buffer_.ptr(), mapping, filesize.st_size); // do unmap if ((munmap(static_cast<void*>(mapping), filesize.st_size) != 0) || (close(fd) != 0)) { std::cout << "failed to unmap file: " << path_ << std::endl; } return true; } bool ReadFd() { // open the file int fd; if ((fd = open(path_.c_str(), O_RDONLY, 0)) == -1) { std::cout << "cannot open file: " << path_ << std::endl; return false; } // get file size struct stat64 filesize; if (fstat64(fd, &filesize) != 0) { std::cout << "failed to fstat file: " << path_ << std::endl; close(fd); return false; } // allocate space uncompressed_buffer_.Allocate(filesize.st_size); if (read(fd, uncompressed_buffer_.ptr(), filesize.st_size) != filesize.st_size) { std::cout << "failed to read file: " << path_ << std::endl; close(fd); return false; } // close the file close(fd); return true; } bool WriteOldfashion() { const std::string path = output_path + "/" + sha1_; // open file FILE *f = fopen(path.c_str(), "w+"); if (f == NULL) { std::cout << "cannot open file: " << path << " errno: " << errno << std::endl; return false; } // write buffer const size_t to_write = compressed_buffer_.used_bytes(); const size_t written = fwrite(compressed_buffer_.ptr(), 1, to_write, f); if (written != to_write) { std::cout << "failed to write " << to_write << " bytes " << "to file: " << path << std::endl; return false; } // close the file fclose(f); return true; } bool WriteFd() { // open the file int fd; if ((fd = open(path_.c_str(), O_WRONLY | O_CREAT, 0)) == -1) { std::cout << "cannot open file: " << path_ << std::endl; return false; } // write to file const size_t bytes = compressed_buffer_.used_bytes(); if (write(fd, compressed_buffer_.ptr(), bytes) != bytes) { std::cout << "failed to read file: " << path_ << std::endl; close(fd); return false; } // close the file close(fd); return true; } private: std::string path_; CruncherTask *cruncher_task_; CharBuffer uncompressed_buffer_; CharBuffer compressed_buffer_; SHA_CTX sha1_context_; std::string sha1_; }; typedef std::vector<File> FileVector; #define MEASURE_IO_TIME class IoDispatcher { public: IoDispatcher() : files_in_flight_(0), file_count_(0), all_enqueued_(false), read_thread_(IoDispatcher::ReadThread, this), write_thread_(IoDispatcher::WriteThread, this) {} ~IoDispatcher() { Wait(); std::cout << "Reads took: " << read_time_ << std::endl << " average: " << (read_time_ / file_count_) << std::endl << "Writes took: " << write_time_ << std::endl << " average: " << (write_time_ / file_count_) << std::endl; } void Wait() { all_enqueued_ = true; read_queue_.push(nullptr); if (read_thread_.joinable()) { read_thread_.join(); } if (write_thread_.joinable()) { write_thread_.join(); } } void Read(File *file) { read_queue_.push(file); ++file_count_; } void Write(File *file) { write_queue_.push(file); } protected: static void ReadThread(IoDispatcher *dispatcher) { task_scheduler_init sched(task_scheduler_init::default_num_threads() + 1); while (true) { File *file; dispatcher->read_queue_.pop(file); if (file == nullptr) { break; } dispatcher->files_in_flight_++; #ifdef MEASURE_IO_TIME tick_count start = tick_count::now(); file->Read(); tick_count end = tick_count::now(); dispatcher->read_time_ += (end - start).seconds(); #else file->Read(); #endif file->SpawnTbbTask(dispatcher); } } static void WriteThread(IoDispatcher *dispatcher) { while (true) { File *file; dispatcher->write_queue_.pop(file); if (file == nullptr) { break; } #ifdef MEASURE_IO_TIME tick_count start = tick_count::now(); file->Write(); tick_count end = tick_count::now(); dispatcher->write_time_ += (end - start).seconds(); #else file->Write(); #endif dispatcher->files_in_flight_--; if (dispatcher->files_in_flight_ == 0 && dispatcher->all_enqueued_) { break; } } } private: atomic<unsigned int> files_in_flight_; atomic<bool> all_enqueued_; unsigned int file_count_; double read_time_; double write_time_; concurrent_bounded_queue<File*> read_queue_; concurrent_bounded_queue<File*> write_queue_; tbb_thread read_thread_; tbb_thread write_thread_; }; task* CruncherTask::execute() { file_->Compress(); file_->Hash(); io_dispatcher_->Write(file_); return NULL; } class TraversalDelegate { public: TraversalDelegate(IoDispatcher *io_dispatcher) : io_dispatcher_(io_dispatcher) {} void FileCb(const std::string &relative_path, const std::string &file_name) { const std::string path = relative_path + "/" + file_name; File *file = new File(path); io_dispatcher_->Read(file); } private: IoDispatcher *io_dispatcher_; }; class Observer : public task_scheduler_observer { void on_scheduler_entry(bool is_worker) { Print("ENTER"); } void on_scheduler_exit(bool is_worker) { Print("EXIT"); } }; int main() { tick_count start, end; tick_count all_start, all_end; Observer observer; observer.observe(); all_start = tick_count::now(); IoDispatcher io_dispatcher; TraversalDelegate delegate(&io_dispatcher); start = tick_count::now(); FileSystemTraversal<TraversalDelegate> t(&delegate, "", true); t.fn_new_file = &TraversalDelegate::FileCb; t.Recurse(input_path); end = tick_count::now(); std::cout << "recursion took: " << (end - start).seconds() << " seconds" << std::endl; Print("going to wait now..."); io_dispatcher.Wait(); Print("waited..."); all_end = tick_count::now(); std::cout << "overall time: " << (all_end - all_start).seconds() << " seconds" << std::endl; return 0; } <|endoftext|>
<commit_before>#include <string.h> #include <math.h> #include "FireLog.h" #include "FireSight.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "jansson.h" #include "jo_util.hpp" #include "MatUtil.hpp" using namespace cv; using namespace std; using namespace firesight; bool Pipeline::apply_calcOffset(json_t *pStage, json_t *pStageModel, Model &model) { validateImage(model.image); string tmpltPath = jo_string(pStage, "template", "", model.argMap); Scalar offsetColor(32,32,255); offsetColor = jo_Scalar(pStage, "offsetColor", offsetColor, model.argMap); int xtol = jo_int(pStage, "xtol", 32, model.argMap); int ytol = jo_int(pStage, "ytol", 32, model.argMap); vector<int> channels = jo_vectori(pStage, "channels", vector<int>(), model.argMap); assert(model.image.cols > 2*xtol); assert(model.image.rows > 2*ytol); Rect roi= jo_Rect(pStage, "roi", Rect(xtol, ytol, model.image.cols-2*xtol, model.image.rows-2*ytol), model.argMap); if (roi.x == -1) { roi.x = (model.image.cols - roi.width)/2; } if (roi.y == -1) { roi.y = (model.image.rows - roi.height)/2; } Rect roiScan = Rect(roi.x-xtol, roi.y-ytol, roi.width+2*xtol, roi.height+2*ytol); float minval = jo_float(pStage, "minval", 0.7f, model.argMap); float corr = jo_float(pStage, "corr", 0.99f); string outputStr = jo_string(pStage, "output", "current", model.argMap); const char *errMsg = NULL; int flags = INTER_LINEAR; int method = CV_TM_CCOEFF_NORMED; Mat tmplt; int borderMode = BORDER_REPLICATE; if (tmpltPath.empty()) { errMsg = "Expected template path for imread"; } else { if (model.image.channels() == 1) { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_GRAYSCALE); } else { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_COLOR); } if (tmplt.data) { LOGTRACE2("apply_calcOffset(%s) %s", tmpltPath.c_str(), matInfo(tmplt).c_str()); if (model.image.rows<tmplt.rows || model.image.cols<tmplt.cols) { errMsg = "Expected template smaller than image to match"; } } else { errMsg = "imread failed"; } } if (!errMsg) { if (model.image.channels() > 3) { errMsg = "Expected at most 3 channels for pipeline image"; } else if (tmplt.channels() != model.image.channels()) { errMsg = "Template and pipeline image must have same number of channels"; } else { for (int iChannel = 0; iChannel < channels.size(); iChannel++) { if (channels[iChannel] < 0 || model.image.channels() <= channels[iChannel]) { errMsg = "Referenced channel is not in image"; } } } } if (!errMsg) { Mat result; Mat imagePlanes[] = { Mat(), Mat(), Mat() }; Mat tmpltPlanes[] = { Mat(), Mat(), Mat() }; if (channels.size() == 0) { channels.push_back(0); if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { cvtColor(model.image, imagePlanes[0], CV_BGR2GRAY); cvtColor(tmplt, tmpltPlanes[0], CV_BGR2GRAY); } } else if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { split(model.image, imagePlanes); split(tmplt, tmpltPlanes); } json_t *pRects = json_array(); json_t *pChannels = json_object(); json_object_set(pStageModel, "channels", pChannels); json_object_set(pStageModel, "rects", pRects); json_t *pRect = json_object(); json_array_append(pRects, pRect); json_object_set(pRect, "x", json_integer(roiScan.x+roiScan.width/2)); json_object_set(pRect, "y", json_integer(roiScan.y+roiScan.height/2)); json_object_set(pRect, "width", json_integer(roiScan.width)); json_object_set(pRect, "height", json_integer(roiScan.height)); json_object_set(pRect, "angle", json_integer(0)); json_t *pOffsetColor = NULL; for (int iChannel=0; iChannel<channels.size(); iChannel++) { int channel = channels[iChannel]; Mat imageSource(imagePlanes[channel], roiScan); Mat tmpltSource(tmpltPlanes[channel], roi); matchTemplate(imageSource, tmpltSource, result, method); LOGTRACE4("apply_calcOffset() matchTemplate(%s,%s,%s,CV_TM_CCOEFF_NORMED) channel:%d", matInfo(imageSource).c_str(), matInfo(tmpltSource).c_str(), matInfo(result).c_str(), channel); vector<Point> matches; float maxVal = *max_element(result.begin<float>(),result.end<float>()); float rangeMin = corr * maxVal; float rangeMax = maxVal; matMaxima(result, matches, rangeMin, rangeMax); if (logLevel >= FIRELOG_TRACE) { for (size_t iMatch=0; iMatch<matches.size(); iMatch++) { int mx = matches[iMatch].x; int my = matches[iMatch].y; float val = result.at<float>(my,mx); if (val < minval) { LOGTRACE4("apply_calcOffset() ignoring (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } else { LOGTRACE4("apply_calcOffset() matched (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } } } json_t *pMatches = json_object(); char key[10]; snprintf(key, sizeof(key), "%d", channel); json_object_set(pChannels, key, pMatches); if (matches.size() == 1) { int mx = matches[0].x; int my = matches[0].y; float val = result.at<float>(my,mx); if (minval <= val) { int dx = xtol - mx; int dy = ytol - my; json_object_set(pMatches, "dx", json_integer(dx)); json_object_set(pMatches, "dy", json_integer(dy)); json_object_set(pMatches, "match", json_float(val)); if (dx || dy) { json_t *pOffsetRect = json_object(); json_array_append(pRects, pOffsetRect); json_object_set(pOffsetRect, "x", json_integer(roi.x+roi.width/2-dx)); json_object_set(pOffsetRect, "y", json_integer(roi.y+roi.height/2-dy)); json_object_set(pOffsetRect, "width", json_integer(roi.width)); json_object_set(pOffsetRect, "height", json_integer(roi.height)); json_object_set(pOffsetRect, "angle", json_integer(0)); if (!pOffsetColor) { pOffsetColor = json_array(); json_array_append(pOffsetColor, json_integer(offsetColor[0])); json_array_append(pOffsetColor, json_integer(offsetColor[1])); json_array_append(pOffsetColor, json_integer(offsetColor[2])); } } } } } json_t *pRoiRect = json_object(); json_array_append(pRects, pRoiRect); json_object_set(pRoiRect, "x", json_integer(roi.x+roi.width/2)); json_object_set(pRoiRect, "y", json_integer(roi.y+roi.height/2)); json_object_set(pRoiRect, "width", json_integer(roi.width)); json_object_set(pRoiRect, "height", json_integer(roi.height)); json_object_set(pRoiRect, "angle", json_integer(0)); if (pOffsetColor) { json_object_set(pRoiRect, "color", pOffsetColor); } normalize(result, result, 0, 255, NORM_MINMAX); result.convertTo(result, CV_8U); Mat corrInset = model.image.colRange(0,result.cols).rowRange(0,result.rows); switch (model.image.channels()) { case 3: cvtColor(result, corrInset, CV_GRAY2BGR); break; case 4: cvtColor(result, corrInset, CV_GRAY2BGRA); break; default: result.copyTo(corrInset); break; } } return stageOK("apply_calcOffset(%s) %s", errMsg, pStage, pStageModel); } <commit_msg>ROI error message<commit_after>#include <string.h> #include <math.h> #include "FireLog.h" #include "FireSight.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "jansson.h" #include "jo_util.hpp" #include "MatUtil.hpp" using namespace cv; using namespace std; using namespace firesight; bool Pipeline::apply_calcOffset(json_t *pStage, json_t *pStageModel, Model &model) { validateImage(model.image); string tmpltPath = jo_string(pStage, "template", "", model.argMap); Scalar offsetColor(32,32,255); offsetColor = jo_Scalar(pStage, "offsetColor", offsetColor, model.argMap); int xtol = jo_int(pStage, "xtol", 32, model.argMap); int ytol = jo_int(pStage, "ytol", 32, model.argMap); vector<int> channels = jo_vectori(pStage, "channels", vector<int>(), model.argMap); assert(model.image.cols > 2*xtol); assert(model.image.rows > 2*ytol); Rect roi= jo_Rect(pStage, "roi", Rect(xtol, ytol, model.image.cols-2*xtol, model.image.rows-2*ytol), model.argMap); if (roi.x == -1) { roi.x = (model.image.cols - roi.width)/2; } if (roi.y == -1) { roi.y = (model.image.rows - roi.height)/2; } Rect roiScan = Rect(roi.x-xtol, roi.y-ytol, roi.width+2*xtol, roi.height+2*ytol); float minval = jo_float(pStage, "minval", 0.7f, model.argMap); float corr = jo_float(pStage, "corr", 0.99f); string outputStr = jo_string(pStage, "output", "current", model.argMap); const char *errMsg = NULL; int flags = INTER_LINEAR; int method = CV_TM_CCOEFF_NORMED; Mat tmplt; int borderMode = BORDER_REPLICATE; if (roi.x < 0 || roi.y < 0 || model.image.cols < roi.x+roi.width || model.image.rows < roi.y+roi.height) { errMsg = "ROI must be within image"; } if (tmpltPath.empty()) { errMsg = "Expected template path for imread"; } else { if (model.image.channels() == 1) { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_GRAYSCALE); } else { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_COLOR); } if (tmplt.data) { LOGTRACE2("apply_calcOffset(%s) %s", tmpltPath.c_str(), matInfo(tmplt).c_str()); if (model.image.rows<tmplt.rows || model.image.cols<tmplt.cols) { errMsg = "Expected template smaller than image to match"; } } else { errMsg = "imread failed"; } } if (!errMsg) { if (model.image.channels() > 3) { errMsg = "Expected at most 3 channels for pipeline image"; } else if (tmplt.channels() != model.image.channels()) { errMsg = "Template and pipeline image must have same number of channels"; } else { for (int iChannel = 0; iChannel < channels.size(); iChannel++) { if (channels[iChannel] < 0 || model.image.channels() <= channels[iChannel]) { errMsg = "Referenced channel is not in image"; } } } } if (!errMsg) { Mat result; Mat imagePlanes[] = { Mat(), Mat(), Mat() }; Mat tmpltPlanes[] = { Mat(), Mat(), Mat() }; if (channels.size() == 0) { channels.push_back(0); if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { cvtColor(model.image, imagePlanes[0], CV_BGR2GRAY); cvtColor(tmplt, tmpltPlanes[0], CV_BGR2GRAY); } } else if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { split(model.image, imagePlanes); split(tmplt, tmpltPlanes); } json_t *pRects = json_array(); json_t *pChannels = json_object(); json_object_set(pStageModel, "channels", pChannels); json_object_set(pStageModel, "rects", pRects); json_t *pRect = json_object(); json_array_append(pRects, pRect); json_object_set(pRect, "x", json_integer(roiScan.x+roiScan.width/2)); json_object_set(pRect, "y", json_integer(roiScan.y+roiScan.height/2)); json_object_set(pRect, "width", json_integer(roiScan.width)); json_object_set(pRect, "height", json_integer(roiScan.height)); json_object_set(pRect, "angle", json_integer(0)); json_t *pOffsetColor = NULL; for (int iChannel=0; iChannel<channels.size(); iChannel++) { int channel = channels[iChannel]; Mat imageSource(imagePlanes[channel], roiScan); Mat tmpltSource(tmpltPlanes[channel], roi); matchTemplate(imageSource, tmpltSource, result, method); LOGTRACE4("apply_calcOffset() matchTemplate(%s,%s,%s,CV_TM_CCOEFF_NORMED) channel:%d", matInfo(imageSource).c_str(), matInfo(tmpltSource).c_str(), matInfo(result).c_str(), channel); vector<Point> matches; float maxVal = *max_element(result.begin<float>(),result.end<float>()); float rangeMin = corr * maxVal; float rangeMax = maxVal; matMaxima(result, matches, rangeMin, rangeMax); if (logLevel >= FIRELOG_TRACE) { for (size_t iMatch=0; iMatch<matches.size(); iMatch++) { int mx = matches[iMatch].x; int my = matches[iMatch].y; float val = result.at<float>(my,mx); if (val < minval) { LOGTRACE4("apply_calcOffset() ignoring (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } else { LOGTRACE4("apply_calcOffset() matched (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } } } json_t *pMatches = json_object(); char key[10]; snprintf(key, sizeof(key), "%d", channel); json_object_set(pChannels, key, pMatches); if (matches.size() == 1) { int mx = matches[0].x; int my = matches[0].y; float val = result.at<float>(my,mx); if (minval <= val) { int dx = xtol - mx; int dy = ytol - my; json_object_set(pMatches, "dx", json_integer(dx)); json_object_set(pMatches, "dy", json_integer(dy)); json_object_set(pMatches, "match", json_float(val)); if (dx || dy) { json_t *pOffsetRect = json_object(); json_array_append(pRects, pOffsetRect); json_object_set(pOffsetRect, "x", json_integer(roi.x+roi.width/2-dx)); json_object_set(pOffsetRect, "y", json_integer(roi.y+roi.height/2-dy)); json_object_set(pOffsetRect, "width", json_integer(roi.width)); json_object_set(pOffsetRect, "height", json_integer(roi.height)); json_object_set(pOffsetRect, "angle", json_integer(0)); if (!pOffsetColor) { pOffsetColor = json_array(); json_array_append(pOffsetColor, json_integer(offsetColor[0])); json_array_append(pOffsetColor, json_integer(offsetColor[1])); json_array_append(pOffsetColor, json_integer(offsetColor[2])); } } } } } json_t *pRoiRect = json_object(); json_array_append(pRects, pRoiRect); json_object_set(pRoiRect, "x", json_integer(roi.x+roi.width/2)); json_object_set(pRoiRect, "y", json_integer(roi.y+roi.height/2)); json_object_set(pRoiRect, "width", json_integer(roi.width)); json_object_set(pRoiRect, "height", json_integer(roi.height)); json_object_set(pRoiRect, "angle", json_integer(0)); if (pOffsetColor) { json_object_set(pRoiRect, "color", pOffsetColor); } normalize(result, result, 0, 255, NORM_MINMAX); result.convertTo(result, CV_8U); Mat corrInset = model.image.colRange(0,result.cols).rowRange(0,result.rows); switch (model.image.channels()) { case 3: cvtColor(result, corrInset, CV_GRAY2BGR); break; case 4: cvtColor(result, corrInset, CV_GRAY2BGRA); break; default: result.copyTo(corrInset); break; } } return stageOK("apply_calcOffset(%s) %s", errMsg, pStage, pStageModel); } <|endoftext|>
<commit_before>#include <string.h> #include <math.h> #include "FireLog.h" #include "FireSight.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "jansson.h" #include "jo_util.hpp" #include "MatUtil.hpp" using namespace cv; using namespace std; using namespace firesight; bool Pipeline::apply_calcOffset(json_t *pStage, json_t *pStageModel, Model &model) { validateImage(model.image); string tmpltPath = jo_string(pStage, "template", "", model.argMap); int xtol = jo_int(pStage, "xtol", 32, model.argMap); int ytol = jo_int(pStage, "ytol", 32, model.argMap); vector<int> channels = jo_vectori(pStage, "channels", vector<int>(), model.argMap); assert(model.image.cols > 2*xtol); assert(model.image.rows > 2*ytol); Rect roi= jo_Rect(pStage, "roi", Rect(xtol, ytol, model.image.cols-2*xtol, model.image.rows-2*ytol), model.argMap); Rect roiScan = Rect(roi.x-xtol, roi.y-ytol, roi.width+2*xtol, roi.height+2*ytol); float minval = jo_float(pStage, "minval", 0.7f, model.argMap); float corr = jo_float(pStage, "corr", 0.99f); string outputStr = jo_string(pStage, "output", "current", model.argMap); const char *errMsg = NULL; int flags = INTER_LINEAR; int method = CV_TM_CCOEFF_NORMED; Mat tmplt; int borderMode = BORDER_REPLICATE; if (tmpltPath.empty()) { errMsg = "Expected template path for imread"; } else { if (model.image.channels() == 1) { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_GRAYSCALE); } else { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_COLOR); } if (tmplt.data) { LOGTRACE2("apply_calcOffset(%s) %s", tmpltPath.c_str(), matInfo(tmplt).c_str()); if (model.image.rows<tmplt.rows || model.image.cols<tmplt.cols) { errMsg = "Expected template smaller than image to match"; } } else { errMsg = "imread failed"; } } if (!errMsg) { if (model.image.channels() > 3) { errMsg = "Expected at most 3 channels for pipeline image"; } else if (tmplt.channels() != model.image.channels()) { errMsg = "Template and pipeline image must have same number of channels"; } else { for (int iChannel = 0; iChannel < channels.size(); iChannel++) { if (channels[iChannel] < 0 || model.image.channels() <= channels[iChannel]) { errMsg = "Referenced channel is not in image"; } } } } if (!errMsg) { Mat result; Mat imagePlanes[] = { Mat(), Mat(), Mat() }; Mat tmpltPlanes[] = { Mat(), Mat(), Mat() }; if (channels.size() == 0) { channels.push_back(0); if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { cvtColor(model.image, imagePlanes[0], CV_BGR2GRAY); cvtColor(tmplt, tmpltPlanes[0], CV_BGR2GRAY); } } else if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { split(model.image, imagePlanes); split(tmplt, tmpltPlanes); } json_t *pChannels = json_object(); json_object_set(pStageModel, "channels", pChannels); for (int iChannel=0; iChannel<channels.size(); iChannel++) { int channel = channels[iChannel]; Mat imageSource(imagePlanes[channel], roiScan); Mat tmpltSource(tmpltPlanes[channel], roi); matchTemplate(imageSource, tmpltSource, result, method); LOGTRACE4("apply_calcOffset() matchTemplate(%s,%s,%s,CV_TM_CCOEFF_NORMED) channel:%d", matInfo(imageSource).c_str(), matInfo(tmpltSource).c_str(), matInfo(result).c_str(), channel); vector<Point> matches; float maxVal = *max_element(result.begin<float>(),result.end<float>()); float rangeMin = corr * maxVal; float rangeMax = maxVal; matMaxima(result, matches, rangeMin, rangeMax); if (logLevel >= FIRELOG_TRACE) { for (size_t iMatch=0; iMatch<matches.size(); iMatch++) { int mx = matches[iMatch].x; int my = matches[iMatch].y; float val = result.at<float>(my,mx); if (val < minval) { LOGTRACE4("apply_calcOffset() ignoring (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } else { LOGTRACE4("apply_calcOffset() matched (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } } } json_t *pMatches = json_object(); char key[10]; snprintf(key, sizeof(key), "%d", channel); json_object_set(pChannels, key, pMatches); if (matches.size() == 1) { int mx = matches[0].x; int my = matches[0].y; float val = result.at<float>(my,mx); if (minval <= val) { int dx = xtol - mx; int dy = ytol - my; json_object_set(pMatches, "dx", json_integer(dx)); json_object_set(pMatches, "dy", json_integer(dy)); json_object_set(pMatches, "match", json_float(val)); } } } json_t *pRects = json_array(); json_object_set(pStageModel, "rects", pRects); json_t *pRect = json_object(); json_array_append(pRects, pRect); json_object_set(pRect, "x", json_integer(roi.x+roi.width/2)); json_object_set(pRect, "y", json_integer(roi.y+roi.height/2)); json_object_set(pRect, "width", json_integer(roi.width)); json_object_set(pRect, "height", json_integer(roi.height)); json_object_set(pRect, "angle", json_integer(0)); pRect = json_object(); json_array_append(pRects, pRect); json_object_set(pRect, "x", json_integer(roiScan.x+roiScan.width/2)); json_object_set(pRect, "y", json_integer(roiScan.y+roiScan.height/2)); json_object_set(pRect, "width", json_integer(roiScan.width)); json_object_set(pRect, "height", json_integer(roiScan.height)); json_object_set(pRect, "angle", json_integer(0)); normalize(result, result, 0, 255, NORM_MINMAX); result.convertTo(result, CV_8U); Mat corrInset = model.image.colRange(0,result.cols).rowRange(0,result.rows); switch (model.image.channels()) { case 3: cvtColor(result, corrInset, CV_GRAY2BGR); break; case 4: cvtColor(result, corrInset, CV_GRAY2BGRA); break; default: result.copyTo(corrInset); break; } } return stageOK("apply_calcOffset(%s) %s", errMsg, pStage, pStageModel); } <commit_msg>offset-color for calcOffset<commit_after>#include <string.h> #include <math.h> #include "FireLog.h" #include "FireSight.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "jansson.h" #include "jo_util.hpp" #include "MatUtil.hpp" using namespace cv; using namespace std; using namespace firesight; bool Pipeline::apply_calcOffset(json_t *pStage, json_t *pStageModel, Model &model) { validateImage(model.image); string tmpltPath = jo_string(pStage, "template", "", model.argMap); Scalar offsetColor = jo_Scalar(pStage, "offset-color", Scalar::all(-1), model.argMap); int xtol = jo_int(pStage, "xtol", 32, model.argMap); int ytol = jo_int(pStage, "ytol", 32, model.argMap); vector<int> channels = jo_vectori(pStage, "channels", vector<int>(), model.argMap); assert(model.image.cols > 2*xtol); assert(model.image.rows > 2*ytol); Rect roi= jo_Rect(pStage, "roi", Rect(xtol, ytol, model.image.cols-2*xtol, model.image.rows-2*ytol), model.argMap); Rect roiScan = Rect(roi.x-xtol, roi.y-ytol, roi.width+2*xtol, roi.height+2*ytol); float minval = jo_float(pStage, "minval", 0.7f, model.argMap); float corr = jo_float(pStage, "corr", 0.99f); string outputStr = jo_string(pStage, "output", "current", model.argMap); const char *errMsg = NULL; int flags = INTER_LINEAR; int method = CV_TM_CCOEFF_NORMED; Mat tmplt; int borderMode = BORDER_REPLICATE; if (tmpltPath.empty()) { errMsg = "Expected template path for imread"; } else { if (model.image.channels() == 1) { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_GRAYSCALE); } else { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_COLOR); } if (tmplt.data) { LOGTRACE2("apply_calcOffset(%s) %s", tmpltPath.c_str(), matInfo(tmplt).c_str()); if (model.image.rows<tmplt.rows || model.image.cols<tmplt.cols) { errMsg = "Expected template smaller than image to match"; } } else { errMsg = "imread failed"; } } if (!errMsg) { if (model.image.channels() > 3) { errMsg = "Expected at most 3 channels for pipeline image"; } else if (tmplt.channels() != model.image.channels()) { errMsg = "Template and pipeline image must have same number of channels"; } else { for (int iChannel = 0; iChannel < channels.size(); iChannel++) { if (channels[iChannel] < 0 || model.image.channels() <= channels[iChannel]) { errMsg = "Referenced channel is not in image"; } } } } if (!errMsg) { Mat result; Mat imagePlanes[] = { Mat(), Mat(), Mat() }; Mat tmpltPlanes[] = { Mat(), Mat(), Mat() }; if (channels.size() == 0) { channels.push_back(0); if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { cvtColor(model.image, imagePlanes[0], CV_BGR2GRAY); cvtColor(tmplt, tmpltPlanes[0], CV_BGR2GRAY); } } else if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { split(model.image, imagePlanes); split(tmplt, tmpltPlanes); } json_t *pRects = json_array(); json_t *pChannels = json_object(); json_object_set(pStageModel, "channels", pChannels); json_object_set(pStageModel, "rects", pRects); for (int iChannel=0; iChannel<channels.size(); iChannel++) { int channel = channels[iChannel]; Mat imageSource(imagePlanes[channel], roiScan); Mat tmpltSource(tmpltPlanes[channel], roi); matchTemplate(imageSource, tmpltSource, result, method); LOGTRACE4("apply_calcOffset() matchTemplate(%s,%s,%s,CV_TM_CCOEFF_NORMED) channel:%d", matInfo(imageSource).c_str(), matInfo(tmpltSource).c_str(), matInfo(result).c_str(), channel); vector<Point> matches; float maxVal = *max_element(result.begin<float>(),result.end<float>()); float rangeMin = corr * maxVal; float rangeMax = maxVal; matMaxima(result, matches, rangeMin, rangeMax); if (logLevel >= FIRELOG_TRACE) { for (size_t iMatch=0; iMatch<matches.size(); iMatch++) { int mx = matches[iMatch].x; int my = matches[iMatch].y; float val = result.at<float>(my,mx); if (val < minval) { LOGTRACE4("apply_calcOffset() ignoring (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } else { LOGTRACE4("apply_calcOffset() matched (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } } } json_t *pMatches = json_object(); char key[10]; snprintf(key, sizeof(key), "%d", channel); json_object_set(pChannels, key, pMatches); if (matches.size() == 1) { int mx = matches[0].x; int my = matches[0].y; float val = result.at<float>(my,mx); if (minval <= val) { int dx = xtol - mx; int dy = ytol - my; json_object_set(pMatches, "dx", json_integer(dx)); json_object_set(pMatches, "dy", json_integer(dy)); json_object_set(pMatches, "match", json_float(val)); if (offsetColor[0] >= 0) { json_t *pOffsetRect = json_object(); json_array_append(pRects, pOffsetRect); json_object_set(pOffsetRect, "x", json_integer(roiScan.x+roiScan.width/2 + dx)); json_object_set(pOffsetRect, "y", json_integer(roiScan.y+roiScan.height/2 + dx)); json_object_set(pOffsetRect, "width", json_integer(roiScan.width)); json_object_set(pOffsetRect, "height", json_integer(roiScan.height)); json_object_set(pOffsetRect, "angle", json_integer(0)); json_t *pColor = json_array(); json_array_append(pColor, json_integer(offsetColor[0])); json_array_append(pColor, json_integer(offsetColor[1])); json_array_append(pColor, json_integer(offsetColor[2])); json_object_set(pOffsetRect, "color", pColor); } } } } json_t *pRect = json_object(); json_array_append(pRects, pRect); json_object_set(pRect, "x", json_integer(roi.x+roi.width/2)); json_object_set(pRect, "y", json_integer(roi.y+roi.height/2)); json_object_set(pRect, "width", json_integer(roi.width)); json_object_set(pRect, "height", json_integer(roi.height)); json_object_set(pRect, "angle", json_integer(0)); pRect = json_object(); json_array_append(pRects, pRect); json_object_set(pRect, "x", json_integer(roiScan.x+roiScan.width/2)); json_object_set(pRect, "y", json_integer(roiScan.y+roiScan.height/2)); json_object_set(pRect, "width", json_integer(roiScan.width)); json_object_set(pRect, "height", json_integer(roiScan.height)); json_object_set(pRect, "angle", json_integer(0)); normalize(result, result, 0, 255, NORM_MINMAX); result.convertTo(result, CV_8U); Mat corrInset = model.image.colRange(0,result.cols).rowRange(0,result.rows); switch (model.image.channels()) { case 3: cvtColor(result, corrInset, CV_GRAY2BGR); break; case 4: cvtColor(result, corrInset, CV_GRAY2BGRA); break; default: result.copyTo(corrInset); break; } } return stageOK("apply_calcOffset(%s) %s", errMsg, pStage, pStageModel); } <|endoftext|>
<commit_before>/* Copyright 2013 - 2015 Yurii Litvinov and CyberTech Labs 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 <QtCore/qglobal.h> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QApplication> #else #include <QtWidgets/QApplication> #endif #include <QtCore/QTimer> #include <QtCore/QCoreApplication> #include <QtCore/QEventLoop> #include <trikKernel/configurer.h> #include <trikKernel/deinitializationHelper.h> #include <trikKernel/fileUtils.h> #include <trikKernel/applicationInitHelper.h> #include <trikKernel/paths.h> #include <trikControl/brickFactory.h> #include <trikControl/brickInterface.h> #include <trikScriptRunner/trikScriptRunner.h> #include <trikNetwork/mailboxFactory.h> #include <trikNetwork/mailboxInterface.h> #include <QsLog.h> int main(int argc, char *argv[]) { QStringList params; for (int i = 1; i < argc; ++i) { params << QString(argv[i]); } QScopedPointer<QCoreApplication> app; if (params.contains("--no-display") || params.contains("-no-display")) { app.reset(new QCoreApplication(argc, argv)); } else { app.reset(new QApplication(argc, argv)); } app->setApplicationName("TrikRun"); // RAII-style code to ensure that after brick gets destroyed there will be an event loop that cleans it up. trikKernel::DeinitializationHelper helper; Q_UNUSED(helper); trikKernel::ApplicationInitHelper initHelper(*app); initHelper.commandLineParser().addPositionalArgument("file", QObject::tr("File with script to execute") + " " + QObject::tr("(optional of -s option is specified)")); initHelper.commandLineParser().addOption("s", "script" , QObject::tr("Script to be executed directly from command line.") + "\n" + QObject::tr("\tExample: ./trikRun -qws -s \"brick.smile(); script.wait(2000);\"")); initHelper.commandLineParser().addFlag("no-display", "no-display" , QObject::tr("Disable display support. When this flag is active, trikRun can work without QWS or even " "physical display")); initHelper.commandLineParser().addApplicationDescription(QObject::tr("Runner of JavaScript files.")); if (!initHelper.parseCommandLine()) { return 0; } initHelper.init(); QLOG_INFO() << "TrikRun started"; const auto run = [&](const QString &script) { QScopedPointer<trikControl::BrickInterface> brick( trikControl::BrickFactory::create(initHelper.configPath(), trikKernel::Paths::mediaPath()) ); trikKernel::Configurer configurer(initHelper.configPath() + "/system-config.xml" , initHelper.configPath() + "/model-config.xml"); QScopedPointer<trikNetwork::MailboxInterface> mailbox(trikNetwork::MailboxFactory::create(configurer)); trikScriptRunner::TrikScriptRunner result(*brick, mailbox.data()); QObject::connect(&result, SIGNAL(completed(QString, int)), app.data(), SLOT(quit())); result.run(script); return app->exec(); }; if (initHelper.commandLineParser().isSet("s")) { return run(initHelper.commandLineParser().value("s")); } else { const QStringList positionalArgs = initHelper.commandLineParser().positionalArgs(); if (positionalArgs.size() == 1) { return run(trikKernel::FileUtils::readFromFile(positionalArgs[0])); } else { initHelper.commandLineParser().showHelp(); return 1; } } } <commit_msg>Making script launcher more portable<commit_after>/* Copyright 2013 - 2015 Yurii Litvinov and CyberTech Labs 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 <QtCore/qglobal.h> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QApplication> #else #include <QtWidgets/QApplication> #endif #include <QtCore/QTimer> #include <QtCore/QCoreApplication> #include <QtCore/QEventLoop> #include <QtCore/QFileInfo> #include <trikKernel/configurer.h> #include <trikKernel/deinitializationHelper.h> #include <trikKernel/fileUtils.h> #include <trikKernel/applicationInitHelper.h> #include <trikKernel/paths.h> #include <trikControl/brickFactory.h> #include <trikControl/brickInterface.h> #include <trikScriptRunner/trikScriptRunner.h> #include <trikNetwork/mailboxFactory.h> #include <trikNetwork/mailboxInterface.h> #include <QsLog.h> int main(int argc, char *argv[]) { QStringList params; for (int i = 1; i < argc; ++i) { params << QString(argv[i]); } QScopedPointer<QCoreApplication> app; if (params.contains("--no-display") || params.contains("-no-display")) { app.reset(new QCoreApplication(argc, argv)); } else { app.reset(new QApplication(argc, argv)); } app->setApplicationName("TrikRun"); // RAII-style code to ensure that after brick gets destroyed there will be an event loop that cleans it up. trikKernel::DeinitializationHelper helper; Q_UNUSED(helper); trikKernel::ApplicationInitHelper initHelper(*app); initHelper.commandLineParser().addPositionalArgument("file", QObject::tr("File with script to execute") + " " + QObject::tr("(optional of -s option is specified)")); initHelper.commandLineParser().addOption("js", "js-script" , QObject::tr("JavaScript Script to be executed directly from command line.") + "\n" + QObject::tr("\tExample: ./trikRun -js \"brick.smile(); script.wait(2000);\"")); initHelper.commandLineParser().addFlag("no-display", "no-display" , QObject::tr("Disable display support. When this flag is active, trikRun can work without QWS or even " "physical display")); initHelper.commandLineParser().addApplicationDescription(QObject::tr("Runner of JavaScript files.")); if (!initHelper.parseCommandLine()) { return 0; } initHelper.init(); QLOG_INFO() << "TrikRun started"; enum ScriptType { JAVASCRIPT, }; const auto run = [&](const QString &script, ScriptType stype) { QScopedPointer<trikControl::BrickInterface> brick( trikControl::BrickFactory::create(initHelper.configPath(), trikKernel::Paths::mediaPath()) ); trikKernel::Configurer configurer(initHelper.configPath() + "/system-config.xml" , initHelper.configPath() + "/model-config.xml"); QScopedPointer<trikNetwork::MailboxInterface> mailbox(trikNetwork::MailboxFactory::create(configurer)); trikScriptRunner::TrikScriptRunnerInterface * result; switch (stype) { case JAVASCRIPT: result = new trikScriptRunner::TrikScriptRunner(*brick, mailbox.data()); break; default: QLOG_ERROR() << "No such script engine"; return 1; } QObject::connect(result, SIGNAL(completed(QString, int)), app.data(), SLOT(quit())); result->run(script); return app->exec(); }; if (initHelper.commandLineParser().isSet("js")) { return run(initHelper.commandLineParser().value("js"), JAVASCRIPT); } else { const QStringList positionalArgs = initHelper.commandLineParser().positionalArgs(); if (positionalArgs.size() == 1) { const QFileInfo fileInfo(positionalArgs[0]); ScriptType stype; if (fileInfo.suffix() == "js" || fileInfo.suffix() == "qts") { stype = JAVASCRIPT; } else { QLOG_ERROR() << "No such script engine"; return 1; } return run(trikKernel::FileUtils::readFromFile(positionalArgs[0]), stype); } else { initHelper.commandLineParser().showHelp(); return 1; } } } <|endoftext|>
<commit_before>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "\n*Unknown command" << std::endl; } return result; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; // std::string input; // struct timeval timeout; fd_set read_set; // int file_desc = 0; int result; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); char stdin_buffer[kBufferSize]; memset(&stdin_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(client_socket, &read_set)) { // Socket has data int read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { // TODO capture user input, store, clean input, then print buffer, afterward replace input struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } std::cout << ">"; if (FD_ISSET(STDIN_FILENO, &read_set)) { int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize); if (read_stdin_size != 0) { if (stdin_buffer[0] == '/') { ProcessInput(stdin_buffer); } else { // Send chat messages StripChar(stdin_buffer, '\n'); RequestSay(stdin_buffer); } } memset(&stdin_buffer, 0, kBufferSize); } // end of if STDIN } // end of if result } // end of while return 0; }<commit_msg>test move initial prompt outside while<commit_after>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "\n*Unknown command" << std::endl; } return result; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; // std::string input; // struct timeval timeout; fd_set read_set; // int file_desc = 0; int result; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); char stdin_buffer[kBufferSize]; memset(&stdin_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send std::cout << ">"; while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(client_socket, &read_set)) { // Socket has data int read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { // TODO capture user input, store, clean input, then print buffer, afterward replace input struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } std::cout << ">"; if (FD_ISSET(STDIN_FILENO, &read_set)) { int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize); if (read_stdin_size != 0) { if (stdin_buffer[0] == '/') { ProcessInput(stdin_buffer); } else { // Send chat messages StripChar(stdin_buffer, '\n'); RequestSay(stdin_buffer); } } memset(&stdin_buffer, 0, kBufferSize); } // end of if STDIN } // end of if result } // end of while return 0; }<|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> typedef float dataType; std::string typeName("float"); void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size); int main(int argc, char * argv[]) { bool localMem = false; bool reInit = false; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; unsigned int maxRows = 0; unsigned int maxColumns = 0; unsigned int threadUnit = 0; unsigned int threadIncrement = 0; unsigned int maxItems = 0; unsigned int maxUnroll = 0; unsigned int maxLoopBodySize = 0; AstroData::Observation observation; cl::Event event; try { isa::utils::ArgumentList args(argc, argv); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); localMem = args.getSwitch("-local"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit"); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); maxColumns = args.getSwitchArgument< unsigned int >("-max_columns"); threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll"); maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize"); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step")); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Allocate host memory std::vector< float > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))); // Initialize OpenCL cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); // Allocate device memory cl::Buffer shifts_d; cl::Buffer dispersedData_d; cl::Buffer dedispersedData_d; try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); } catch ( cl::Error & err ) { return -1; } // Find the parameters std::vector< unsigned int > samplesPerBlock; for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) { if ( (observation.getNrSamplesPerSecond() % samples) == 0 ) { samplesPerBlock.push_back(samples); } else if ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) { samplesPerBlock.push_back(samples); } } std::vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } std::cout << std::fixed << std::endl; std::cout << "# nrDMs nrChannels nrSamples local samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread unroll GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl; for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) { for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) { if ( ((*samples) * (*DMs)) > maxThreads ) { break; } else if ( ((*samples) * (*DMs)) % threadUnit != 0 ) { continue; } for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) { if ( (observation.getNrSamplesPerSecond() % ((*samples) * samplesPerThread)) != 0 && (observation.getNrSamplesPerPaddedSecond() % (*samples * samplesPerThread)) != 0 ) { continue; } for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) { if ( (observation.getNrDMs() % ((*DMs) * DMsPerThread)) != 0 ) { continue; } else if ( (samplesPerThread * DMsPerThread) + DMsPerThread > maxItems ) { break; } for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) { if ( (observation.getNrChannels() - 1) % unroll != 0 ) { continue; } else if ( (samplesPerThread * DMsPerThread * unroll) > maxLoopBodySize ) { break; } // Generate kernel double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond()); double gbs = isa::utils::giga(((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * (observation.getNrChannels() + 1)) * sizeof(dataType)) + ((observation.getNrDMs() * observation.getNrChannels()) * sizeof(unsigned int))); isa::utils::Timer timer; cl::Kernel * kernel; std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, *samples, *DMs, samplesPerThread, DMsPerThread, unroll, typeName, observation, *shifts); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; unsigned int nrThreads = 0; if ( observation.getNrSamplesPerSecond() % (*samples * samplesPerThread) == 0 ) { nrThreads = observation.getNrSamplesPerSecond() / samplesPerThread; } else { nrThreads = observation.getNrSamplesPerPaddedSecond() / samplesPerThread; } cl::NDRange global(nrThreads, observation.getNrDMs() / DMsPerThread); cl::NDRange local(*samples, *DMs); kernel->setArg(0, dispersedData_d); kernel->setArg(1, dedispersedData_d); kernel->setArg(2, shifts_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); timer.stop(); } } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution ("; std::cerr << localMem << ", " << *samples << ", " << *DMs << ", " << samplesPerThread << ", " << DMsPerThread << ", " << unroll << "): "; std::cerr << isa::utils::toString(err.err()) << "." << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } reInit = true; break; } delete kernel; std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " " << localMem << " " << *samples << " " << *DMs << " " << samplesPerThread << " " << DMsPerThread << " " << unroll << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << gbs / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " "; std::cout << timer.getCoefficientOfVariation() << std::endl; } } } } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) { try { *shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts_size * sizeof(float), 0, 0); *dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(dataType), 0, 0); *dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(dataType), 0, 0); clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts_size * sizeof(float), reinterpret_cast< void * >(shifts->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <commit_msg>Simplified a condition.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> typedef float dataType; std::string typeName("float"); void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size); int main(int argc, char * argv[]) { bool localMem = false; bool reInit = false; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; unsigned int maxRows = 0; unsigned int maxColumns = 0; unsigned int threadUnit = 0; unsigned int threadIncrement = 0; unsigned int maxItems = 0; unsigned int maxUnroll = 0; unsigned int maxLoopBodySize = 0; AstroData::Observation observation; cl::Event event; try { isa::utils::ArgumentList args(argc, argv); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); localMem = args.getSwitch("-local"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit"); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); maxColumns = args.getSwitchArgument< unsigned int >("-max_columns"); threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll"); maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize"); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step")); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Allocate host memory std::vector< float > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))); // Initialize OpenCL cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); // Allocate device memory cl::Buffer shifts_d; cl::Buffer dispersedData_d; cl::Buffer dedispersedData_d; try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); } catch ( cl::Error & err ) { return -1; } // Find the parameters std::vector< unsigned int > samplesPerBlock; for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) { if ( (observation.getNrSamplesPerSecond() % samples) == 0 || (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) { samplesPerBlock.push_back(samples); } } std::vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } std::cout << std::fixed << std::endl; std::cout << "# nrDMs nrChannels nrSamples local samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread unroll GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl; for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) { for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) { if ( ((*samples) * (*DMs)) > maxThreads ) { break; } else if ( ((*samples) * (*DMs)) % threadUnit != 0 ) { continue; } for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) { if ( (observation.getNrSamplesPerSecond() % ((*samples) * samplesPerThread)) != 0 && (observation.getNrSamplesPerPaddedSecond() % (*samples * samplesPerThread)) != 0 ) { continue; } for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) { if ( (observation.getNrDMs() % ((*DMs) * DMsPerThread)) != 0 ) { continue; } else if ( (samplesPerThread * DMsPerThread) + DMsPerThread > maxItems ) { break; } for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) { if ( (observation.getNrChannels() - 1) % unroll != 0 ) { continue; } else if ( (samplesPerThread * DMsPerThread * unroll) > maxLoopBodySize ) { break; } // Generate kernel double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond()); double gbs = isa::utils::giga(((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * (observation.getNrChannels() + 1)) * sizeof(dataType)) + ((observation.getNrDMs() * observation.getNrChannels()) * sizeof(unsigned int))); isa::utils::Timer timer; cl::Kernel * kernel; std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, *samples, *DMs, samplesPerThread, DMsPerThread, unroll, typeName, observation, *shifts); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; unsigned int nrThreads = 0; if ( observation.getNrSamplesPerSecond() % (*samples * samplesPerThread) == 0 ) { nrThreads = observation.getNrSamplesPerSecond() / samplesPerThread; } else { nrThreads = observation.getNrSamplesPerPaddedSecond() / samplesPerThread; } cl::NDRange global(nrThreads, observation.getNrDMs() / DMsPerThread); cl::NDRange local(*samples, *DMs); kernel->setArg(0, dispersedData_d); kernel->setArg(1, dedispersedData_d); kernel->setArg(2, shifts_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); timer.stop(); } } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution ("; std::cerr << localMem << ", " << *samples << ", " << *DMs << ", " << samplesPerThread << ", " << DMsPerThread << ", " << unroll << "): "; std::cerr << isa::utils::toString(err.err()) << "." << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } reInit = true; break; } delete kernel; std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " " << localMem << " " << *samples << " " << *DMs << " " << samplesPerThread << " " << DMsPerThread << " " << unroll << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << gbs / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " "; std::cout << timer.getCoefficientOfVariation() << std::endl; } } } } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) { try { *shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts_size * sizeof(float), 0, 0); *dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(dataType), 0, 0); *dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(dataType), 0, 0); clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts_size * sizeof(float), reinterpret_cast< void * >(shifts->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <|endoftext|>
<commit_before>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" #include "raw.h" // Client connects, logs in, and joins “Common”. // Client reads lines from the user and parses commands. // Client correctly sends Say message. // Client uses select() to wait for input from the user and the server. // Client correctly sends Join, Leave, Login, and Logout and TODO handles Switch. // TODO Client correctly sends List and Who. // TODO Server can accept connections. // TODO Server handles Login and Logout from users, and keeps records of which users are logged in. // TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to, // and keeps records of which users are in a channel. // TODO Server handles the Say message. // TODO Server correctly handles List and Who. // TODO Create copies of your client and server source. Modify them to send invalid packets to your good client // and server, to see if you can make your client or server crash. Fix any bugs you find. // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; std::string current_channel; std::vector<std::string> channels; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } void PrintPrompt() { std::cout << "> " << std::flush; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Gets the address info of the server at a the given port and creates the client's socket. void CreateSocket(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Tries each address until a successful connect(). // If socket() (or connect()) fails, closes the socket and tries the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int SendSay(std::string message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message.c_str(), SAY_MAX); strncpy(say.req_channel, current_channel.c_str(), CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int SendLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int SendLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } int SendList(){ struct request_list list; list.req_type = REQ_LIST; size_t list_size = sizeof(struct request_list); if (sendto(client_socket, &list, list_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request list \n"); } return 0; } int SendLeave(std::string channel) { bool contains_channel = false; std::vector<std::string>::iterator it; for (it = channels.begin(); it != channels.end(); ++it) { std::cout << "checking channel: " << *it << std::endl; std::cout << "trying to leave channel: " << channel << std::endl; if (*it == channel) { contains_channel = true; break; } } if (contains_channel) { channels.erase(it); struct request_leave leave; memset((char *) &leave, 0, sizeof(leave)); leave.req_type = REQ_LEAVE; strncpy(leave.req_channel, channel.c_str(), CHANNEL_MAX); size_t leave_size = sizeof(struct request_leave); if (sendto(client_socket, &leave, leave_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request leave\n"); } for (it = channels.begin(); it != channels.end(); ++it) { std::cout << *it << std::endl; } } return 0; } // Sends join requests to the server. int SendJoin(std::string channel) { bool contains_channel = false; for (std::vector<std::string>::iterator it = channels.begin(); it != channels.end(); ++it) { if (*it == channel) { contains_channel = true; break; } } if (!contains_channel) { channels.push_back(channel); struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel.c_str(), CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } } return 0; } // Switches to a channel the user has already joined. int SwitchChannel(std::string channel) { bool isSubscribed = false; if (channels.size() > 0) { for (auto c: channels) { if (channel == c) { current_channel = channel; isSubscribed = true; } } } if (!isSubscribed) { std::cout << "You have not subscribed to channel " << channel << std::endl; } return 0; } void HandleTextList(char *receive_buffer, char *output) { struct text_list list; memcpy(&list, receive_buffer, sizeof(struct text_list)); std::string backspaces = ""; for (int i = 0; i < SAY_MAX; i++) { backspaces.append("\b"); } std::cout << backspaces; std::cout << "Existing channels:" << std::endl; for(int i = 2; i < list.txt_nchannels + 2; i++){ std::cout << " " << list.txt_channels[i].ch_channel << std::endl; } PrintPrompt(); std::cout << output << std::flush; } // Handles TXT-SAY server messages. void HandleTextSay(char *receive_buffer, char *output) { struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::string backspaces = ""; for (int i = 0; i < SAY_MAX; i++) { backspaces.append("\b"); } std::cout << backspaces; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; PrintPrompt(); std::cout << output << std::flush; } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); if (inputs[0] == "/exit") { SendLogout(); cooked_mode(); return false; } else if (inputs[0] == "/list") { SendList(); } else if (inputs[0] == "/join" && inputs.size() > 1) { SendJoin(inputs[1]); } else if (inputs[0] == "/leave" && inputs.size() > 1) { if (inputs[1] == current_channel){ SendLeave(inputs[1]); } else { std::cout << "*Unknown command" << std::endl; } } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch" && inputs.size() > 1) { SwitchChannel(inputs[1]); } else { std::cout << "*Unknown command" << std::endl; } PrintPrompt(); return true; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; std::string input; char *output = (char *) ""; fd_set read_set; int result; char stdin_buffer[SAY_MAX + 1]; char *stdin_buffer_pointer = stdin_buffer; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } CreateSocket(domain, port_str); SendLogin(username); current_channel = "Common"; SendJoin(current_channel); if (raw_mode() != 0){ Error("client: error using raw mode"); } PrintPrompt(); while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(STDIN_FILENO, &read_set)) { // User entered a char. char c = (char) getchar(); if (c == '\n') { // Increments pointer and adds NULL char. *stdin_buffer_pointer++ = '\0'; // Resets stdin_buffer_pointer to the start of stdin_buffer. stdin_buffer_pointer = stdin_buffer; std::cout << "\n" << std::flush; // Prevents output from printing on the new prompt after a newline char. output = (char *) ""; input.assign(stdin_buffer, stdin_buffer + strlen(stdin_buffer)); if (input[0] == '/') { if (!ProcessInput(input)) { break; } } else { // Sends chat messages. SendSay(input); } } else if (stdin_buffer_pointer != stdin_buffer + SAY_MAX) { // Increments pointer and adds char c. *stdin_buffer_pointer++ = c; std::cout << c << std::flush; // Copies pointer into output. output = stdin_buffer_pointer; // Increments and sets NULL char. *output++ = '\0'; // Copies stdin_buffer into part of output before NULL char. output = stdin_buffer; } } else if (FD_ISSET(client_socket, &read_set)) { // Socket has data. ssize_t read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: HandleTextSay(receive_buffer, output); break; case TXT_LIST: HandleTextList(receive_buffer, output); break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } // end of if client_socket } // end of if result } // end of while return 0; }<commit_msg>Logic for leaving current channel<commit_after>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" #include "raw.h" // Client connects, logs in, and joins “Common”. // Client reads lines from the user and parses commands. // Client correctly sends Say message. // Client uses select() to wait for input from the user and the server. // Client correctly sends Join, Leave, Login, and Logout and TODO handles Switch. // TODO Client correctly sends List and Who. // TODO Server can accept connections. // TODO Server handles Login and Logout from users, and keeps records of which users are logged in. // TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to, // and keeps records of which users are in a channel. // TODO Server handles the Say message. // TODO Server correctly handles List and Who. // TODO Create copies of your client and server source. Modify them to send invalid packets to your good client // and server, to see if you can make your client or server crash. Fix any bugs you find. // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; std::string current_channel; std::vector<std::string> channels; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } void PrintPrompt() { std::cout << "> " << std::flush; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Gets the address info of the server at a the given port and creates the client's socket. void CreateSocket(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Tries each address until a successful connect(). // If socket() (or connect()) fails, closes the socket and tries the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int SendSay(std::string message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message.c_str(), SAY_MAX); strncpy(say.req_channel, current_channel.c_str(), CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int SendLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int SendLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } int SendList(){ struct request_list list; list.req_type = REQ_LIST; size_t list_size = sizeof(struct request_list); if (sendto(client_socket, &list, list_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request list \n"); } return 0; } int SendLeave(std::string channel) { bool contains_channel = false; std::vector<std::string>::iterator it; for (it = channels.begin(); it != channels.end(); ++it) { if (*it == channel) { contains_channel = true; break; } } if (contains_channel) { if(channel == current_channel){ current_channel = ""; } channels.erase(it); struct request_leave leave; memset((char *) &leave, 0, sizeof(leave)); leave.req_type = REQ_LEAVE; strncpy(leave.req_channel, channel.c_str(), CHANNEL_MAX); size_t leave_size = sizeof(struct request_leave); if (sendto(client_socket, &leave, leave_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request leave\n"); } for (it = channels.begin(); it != channels.end(); ++it) { std::cout << *it << std::endl; } } return 0; } // Sends join requests to the server. int SendJoin(std::string channel) { bool contains_channel = false; for (std::vector<std::string>::iterator it = channels.begin(); it != channels.end(); ++it) { if (*it == channel) { contains_channel = true; break; } } if (!contains_channel) { channels.push_back(channel); struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel.c_str(), CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } } return 0; } // Switches to a channel the user has already joined. int SwitchChannel(std::string channel) { bool isSubscribed = false; if (channels.size() > 0) { for (auto c: channels) { if (channel == c) { current_channel = channel; isSubscribed = true; } } } if (!isSubscribed) { std::cout << "You have not subscribed to channel " << channel << std::endl; } return 0; } void HandleTextList(char *receive_buffer, char *output) { struct text_list list; memcpy(&list, receive_buffer, sizeof(struct text_list)); std::string backspaces = ""; for (int i = 0; i < SAY_MAX; i++) { backspaces.append("\b"); } std::cout << backspaces; std::cout << "Existing channels:" << std::endl; for(int i = 2; i < list.txt_nchannels + 2; i++){ std::cout << " " << list.txt_channels[i].ch_channel << std::endl; } PrintPrompt(); std::cout << output << std::flush; } // Handles TXT-SAY server messages. void HandleTextSay(char *receive_buffer, char *output) { if (current_channel == ""){ PrintPrompt(); } else { struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::string backspaces = ""; for (int i = 0; i < SAY_MAX; i++) { backspaces.append("\b"); } std::cout << backspaces; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; PrintPrompt(); std::cout << output << std::flush; } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); if (inputs[0] == "/exit") { SendLogout(); cooked_mode(); return false; } else if (inputs[0] == "/list") { SendList(); } else if (inputs[0] == "/join" && inputs.size() > 1) { SendJoin(inputs[1]); } else if (inputs[0] == "/leave" && inputs.size() > 1) { SendLeave(inputs[1]); } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch" && inputs.size() > 1) { SwitchChannel(inputs[1]); } else { std::cout << "*Unknown command" << std::endl; } PrintPrompt(); return true; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; std::string input; char *output = (char *) ""; fd_set read_set; int result; char stdin_buffer[SAY_MAX + 1]; char *stdin_buffer_pointer = stdin_buffer; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } CreateSocket(domain, port_str); SendLogin(username); current_channel = "Common"; SendJoin(current_channel); if (raw_mode() != 0){ Error("client: error using raw mode"); } PrintPrompt(); while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(STDIN_FILENO, &read_set)) { // User entered a char. char c = (char) getchar(); if (c == '\n') { // Increments pointer and adds NULL char. *stdin_buffer_pointer++ = '\0'; // Resets stdin_buffer_pointer to the start of stdin_buffer. stdin_buffer_pointer = stdin_buffer; std::cout << "\n" << std::flush; // Prevents output from printing on the new prompt after a newline char. output = (char *) ""; input.assign(stdin_buffer, stdin_buffer + strlen(stdin_buffer)); if (input[0] == '/') { if (!ProcessInput(input)) { break; } } else { // Sends chat messages. SendSay(input); } } else if (stdin_buffer_pointer != stdin_buffer + SAY_MAX) { // Increments pointer and adds char c. *stdin_buffer_pointer++ = c; std::cout << c << std::flush; // Copies pointer into output. output = stdin_buffer_pointer; // Increments and sets NULL char. *output++ = '\0'; // Copies stdin_buffer into part of output before NULL char. output = stdin_buffer; } } else if (FD_ISSET(client_socket, &read_set)) { // Socket has data. ssize_t read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: HandleTextSay(receive_buffer, output); break; case TXT_LIST: HandleTextList(receive_buffer, output); break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } // end of if client_socket } // end of if result } // end of while return 0; }<|endoftext|>
<commit_before>// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include <nanoHAL.h> #include <nanoCLR_Application.h> #include <nanoCLR_Runtime.h> #include <nanoCLR_Types.h> #include <CLRStartup.h> // FIXME // these are dummy data, we'll have to figure out how to fill these after the build happens char nanoCLR_Dat_Start[100 ]; char nanoCLR_Dat_End [1 ]; struct Settings { CLR_SETTINGS m_clrOptions; bool m_fInitialized; //--// HRESULT Initialize(CLR_SETTINGS params) { NANOCLR_HEADER(); m_clrOptions = params; NANOCLR_CHECK_HRESULT(CLR_RT_ExecutionEngine::CreateInstance()); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Created EE.\r\n" ); #endif #if !defined(BUILD_RTM) if(params.WaitForDebugger) { CLR_EE_DBG_SET( Stopped ); } #endif NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.StartHardware()); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Started Hardware.\r\n" ); #endif // UNDONE: FIXME: CLR_DBG_Debugger::Debugger_Discovery(); m_fInitialized = true; NANOCLR_NOCLEANUP(); } HRESULT LoadAssembly( const CLR_RECORD_ASSEMBLY* header, CLR_RT_Assembly*& assm ) { NANOCLR_HEADER(); const CLR_RT_NativeAssemblyData *pNativeAssmData; NANOCLR_CHECK_HRESULT(CLR_RT_Assembly::CreateInstance( header, assm )); // Get handlers for native functions in assembly pNativeAssmData = GetAssemblyNativeData( assm->m_szName ); // If pNativeAssmData not NULL- means this assembly has native calls and there is pointer to table with native calls. if ( pNativeAssmData != NULL ) { // First verify that check sum in assembly object matches hardcoded check sum. if ( assm->m_header->nativeMethodsChecksum != pNativeAssmData->m_checkSum ) { CLR_Debug::Printf("***********************************************************************\r\n"); CLR_Debug::Printf("* *\r\n"); CLR_Debug::Printf("* ERROR!!!! Firmware version does not match managed code version!!!! *\r\n"); CLR_Debug::Printf("* *\r\n"); CLR_Debug::Printf("* *\r\n"); CLR_Debug::Printf("* Invalid native checksum: %s 0x%08X!=0x%08X *\r\n", assm->m_szName, assm->m_header->nativeMethodsChecksum, pNativeAssmData->m_checkSum ); CLR_Debug::Printf("* *\r\n"); CLR_Debug::Printf("***********************************************************************\r\n"); NANOCLR_SET_AND_LEAVE(CLR_E_ASSM_WRONG_CHECKSUM); } // Assembly has valid pointer to table with native methods. Save it. assm->m_nativeCode = (const CLR_RT_MethodHandler *)pNativeAssmData->m_pNativeMethods; } g_CLR_RT_TypeSystem.Link( assm ); NANOCLR_NOCLEANUP(); } HRESULT Load() { NANOCLR_HEADER(); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Create TS.\r\n" ); #endif //NANOCLR_CHECK_HRESULT(LoadKnownAssemblies( (char*)&__deployment_start__, (char*)&__deployment_end__ )); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Loading Deployment Assemblies.\r\n" ); #endif LoadDeploymentAssemblies(); //--// #if !defined(BUILD_RTM) CLR_Debug::Printf( "Resolving.\r\n" ); #endif NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.ResolveAll()); g_CLR_RT_Persistence_Manager.Initialize(); NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.PrepareForExecution()); #if defined(NANOCLR_PROFILE_HANDLER) CLR_PROF_Handler::Calibrate(); #endif NANOCLR_CLEANUP(); #if !defined(BUILD_RTM) if(FAILED(hr)) CLR_Debug::Printf( "Error: %08x\r\n", hr ); #endif NANOCLR_CLEANUP_END(); } HRESULT LoadKnownAssemblies( char* start, char* end ) { //--// NANOCLR_HEADER(); char *assStart = start; char *assEnd = end; const CLR_RECORD_ASSEMBLY* header; #if !defined(BUILD_RTM) CLR_Debug::Printf(" Loading start at %x, end %x\r\n", (unsigned int)assStart, (unsigned int)assEnd); #endif g_buildCRC = SUPPORT_ComputeCRC( assStart, (unsigned int)assEnd -(unsigned int) assStart, 0 ); header = (const CLR_RECORD_ASSEMBLY*)assStart; while((char*)header + sizeof(CLR_RECORD_ASSEMBLY) < assEnd && header->GoodAssembly()) { CLR_RT_Assembly* assm; // Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem NANOCLR_CHECK_HRESULT(LoadAssembly( header, assm )); header = (const CLR_RECORD_ASSEMBLY*)ROUNDTOMULTIPLE((size_t)header + header->TotalSize(), CLR_UINT32); } NANOCLR_NOCLEANUP(); } HRESULT ContiguousBlockAssemblies(BlockStorageStream stream) { NANOCLR_HEADER(); const CLR_RECORD_ASSEMBLY* header; unsigned char * assembliesBuffer ; signed int headerInBytes = sizeof(CLR_RECORD_ASSEMBLY); unsigned char * headerBuffer = NULL; while(TRUE) { if(!BlockStorageStream_Read(&stream, &headerBuffer, headerInBytes )) break; header = (const CLR_RECORD_ASSEMBLY*)headerBuffer; // check header first before read if(!header->GoodHeader()) { // check failed, try to continue to the next continue; } unsigned int assemblySizeInByte = ROUNDTOMULTIPLE(header->TotalSize(), CLR_UINT32); // advance stream beyond header BlockStorageStream_Seek(&stream, -headerInBytes, BlockStorageStream_SeekCurrent); // read the assembly if(!BlockStorageStream_Read(&stream, &assembliesBuffer, assemblySizeInByte)) break; header = (const CLR_RECORD_ASSEMBLY*)assembliesBuffer; if(!header->GoodAssembly()) { // check failed, try to continue to the next continue; } // we have good Assembly CLR_RT_Assembly* assm; CLR_Debug::Printf( "Attaching deployed file.\r\n" ); // Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem if (FAILED(LoadAssembly(header, assm))) { // load failed, try to continue to the next continue; } // load successfull, mark as deployed assm->m_flags |= CLR_RT_Assembly::Deployed; } NANOCLR_NOCLEANUP(); } HRESULT LoadDeploymentAssemblies() { NANOCLR_HEADER(); // perform initialization of BlockStorageStream structure BlockStorageStream stream; // init the stream for deployment storage if (!BlockStorageStream_Initialize(&stream, StorageUsage_DEPLOYMENT)) { #if !defined(BUILD_RTM) CLR_Debug::Printf( "ERROR: failed to initialize DEPLOYMENT storage\r\n" ); #endif NANOCLR_SET_AND_LEAVE(CLR_E_NOT_SUPPORTED); } ContiguousBlockAssemblies(stream); NANOCLR_NOCLEANUP(); } void Cleanup() { g_CLR_RT_Persistence_Manager.Uninitialize(); // UNDONE: FIXME: CLR_RT_ExecutionEngine::DeleteInstance(); m_fInitialized = false; } Settings() { m_fInitialized = false; } }; static Settings s_ClrSettings; void ClrStartup(CLR_SETTINGS params) { NATIVE_PROFILE_CLR_STARTUP(); Settings settings; ASSERT(sizeof(CLR_RT_HeapBlock_Raw) == sizeof(CLR_RT_HeapBlock)); bool softReboot; do { softReboot = false; CLR_RT_Assembly::InitString(); #if !defined(BUILD_RTM) CLR_Debug::Printf( "\r\nnanoCLR (Build %d.%d.%d.%d)\r\n\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD, VERSION_REVISION ); #endif CLR_RT_Memory::Reset(); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Starting...\r\n" ); #endif HRESULT hr; if(SUCCEEDED(hr = s_ClrSettings.Initialize(params))) { if(SUCCEEDED(hr = s_ClrSettings.Load())) { #if !defined(BUILD_RTM) CLR_Debug::Printf( "Ready.\r\n" ); #endif (void)g_CLR_RT_ExecutionEngine.Execute( NULL, params.MaxContextSwitches ); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Done.\r\n" ); #endif } } if( CLR_EE_DBG_IS_NOT( RebootPending )) { #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) CLR_EE_DBG_SET_MASK(State_ProgramExited, State_Mask); CLR_EE_DBG_EVENT_BROADCAST(CLR_DBG_Commands::c_Monitor_ProgramExit, 0, NULL, WP_Flags_c_NonCritical); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(params.EnterDebuggerLoopAfterExit) { // UNDONE: FIXME: CLR_DBG_Debugger::Debugger_WaitForCommands(); } } // DO NOT USE 'ELSE IF' here because the state can change in Debugger_WaitForCommands() call if( CLR_EE_DBG_IS( RebootPending )) { if(CLR_EE_REBOOT_IS( ClrOnly )) { softReboot = true; params.WaitForDebugger = CLR_EE_REBOOT_IS(ClrOnlyStopDebugger); s_ClrSettings.Cleanup(); // UNDONE: FIXME: HAL_Uninitialize(); // UNDONE: FIXME: SmartPtr_IRQ::ForceDisabled(); //re-init the hal for the reboot (initially it is called in bootentry) // UNDONE: FIXME: HAL_Initialize(); // make sure interrupts are back on // UNDONE: FIXME: SmartPtr_IRQ::ForceEnabled(); } else { CPU_Reset(); } } } while( softReboot ); } <commit_msg>Fix ContiguousBlockAssemblies (#372)<commit_after>// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include <nanoHAL.h> #include <nanoCLR_Application.h> #include <nanoCLR_Runtime.h> #include <nanoCLR_Types.h> #include <CLRStartup.h> // FIXME // these are dummy data, we'll have to figure out how to fill these after the build happens char nanoCLR_Dat_Start[100 ]; char nanoCLR_Dat_End [1 ]; struct Settings { CLR_SETTINGS m_clrOptions; bool m_fInitialized; //--// HRESULT Initialize(CLR_SETTINGS params) { NANOCLR_HEADER(); m_clrOptions = params; NANOCLR_CHECK_HRESULT(CLR_RT_ExecutionEngine::CreateInstance()); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Created EE.\r\n" ); #endif #if !defined(BUILD_RTM) if(params.WaitForDebugger) { CLR_EE_DBG_SET( Stopped ); } #endif NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.StartHardware()); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Started Hardware.\r\n" ); #endif // UNDONE: FIXME: CLR_DBG_Debugger::Debugger_Discovery(); m_fInitialized = true; NANOCLR_NOCLEANUP(); } HRESULT LoadAssembly( const CLR_RECORD_ASSEMBLY* header, CLR_RT_Assembly*& assm ) { NANOCLR_HEADER(); const CLR_RT_NativeAssemblyData *pNativeAssmData; NANOCLR_CHECK_HRESULT(CLR_RT_Assembly::CreateInstance( header, assm )); // Get handlers for native functions in assembly pNativeAssmData = GetAssemblyNativeData( assm->m_szName ); // If pNativeAssmData not NULL- means this assembly has native calls and there is pointer to table with native calls. if ( pNativeAssmData != NULL ) { // First verify that check sum in assembly object matches hardcoded check sum. if ( assm->m_header->nativeMethodsChecksum != pNativeAssmData->m_checkSum ) { CLR_Debug::Printf("***********************************************************************\r\n"); CLR_Debug::Printf("* *\r\n"); CLR_Debug::Printf("* ERROR!!!! Firmware version does not match managed code version!!!! *\r\n"); CLR_Debug::Printf("* *\r\n"); CLR_Debug::Printf("* *\r\n"); CLR_Debug::Printf("* Invalid native checksum: %s 0x%08X!=0x%08X *\r\n", assm->m_szName, assm->m_header->nativeMethodsChecksum, pNativeAssmData->m_checkSum ); CLR_Debug::Printf("* *\r\n"); CLR_Debug::Printf("***********************************************************************\r\n"); NANOCLR_SET_AND_LEAVE(CLR_E_ASSM_WRONG_CHECKSUM); } // Assembly has valid pointer to table with native methods. Save it. assm->m_nativeCode = (const CLR_RT_MethodHandler *)pNativeAssmData->m_pNativeMethods; } g_CLR_RT_TypeSystem.Link( assm ); NANOCLR_NOCLEANUP(); } HRESULT Load() { NANOCLR_HEADER(); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Create TS.\r\n" ); #endif //NANOCLR_CHECK_HRESULT(LoadKnownAssemblies( (char*)&__deployment_start__, (char*)&__deployment_end__ )); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Loading Deployment Assemblies.\r\n" ); #endif LoadDeploymentAssemblies(); //--// #if !defined(BUILD_RTM) CLR_Debug::Printf( "Resolving.\r\n" ); #endif NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.ResolveAll()); g_CLR_RT_Persistence_Manager.Initialize(); NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.PrepareForExecution()); #if defined(NANOCLR_PROFILE_HANDLER) CLR_PROF_Handler::Calibrate(); #endif NANOCLR_CLEANUP(); #if !defined(BUILD_RTM) if(FAILED(hr)) CLR_Debug::Printf( "Error: %08x\r\n", hr ); #endif NANOCLR_CLEANUP_END(); } HRESULT LoadKnownAssemblies( char* start, char* end ) { //--// NANOCLR_HEADER(); char *assStart = start; char *assEnd = end; const CLR_RECORD_ASSEMBLY* header; #if !defined(BUILD_RTM) CLR_Debug::Printf(" Loading start at %x, end %x\r\n", (unsigned int)assStart, (unsigned int)assEnd); #endif g_buildCRC = SUPPORT_ComputeCRC( assStart, (unsigned int)assEnd -(unsigned int) assStart, 0 ); header = (const CLR_RECORD_ASSEMBLY*)assStart; while((char*)header + sizeof(CLR_RECORD_ASSEMBLY) < assEnd && header->GoodAssembly()) { CLR_RT_Assembly* assm; // Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem NANOCLR_CHECK_HRESULT(LoadAssembly( header, assm )); header = (const CLR_RECORD_ASSEMBLY*)ROUNDTOMULTIPLE((size_t)header + header->TotalSize(), CLR_UINT32); } NANOCLR_NOCLEANUP(); } HRESULT ContiguousBlockAssemblies(BlockStorageStream stream) { NANOCLR_HEADER(); const CLR_RECORD_ASSEMBLY* header; unsigned char * assembliesBuffer ; signed int headerInBytes = sizeof(CLR_RECORD_ASSEMBLY); unsigned char * headerBuffer = NULL; while(stream.CurrentIndex < stream.Length) { // check if there is enough stream length to continue if((stream.Length - stream.CurrentIndex ) < headerInBytes) { // not enough stream to read, leave now break; } if(!BlockStorageStream_Read(&stream, &headerBuffer, headerInBytes )) break; header = (const CLR_RECORD_ASSEMBLY*)headerBuffer; // check header first before read if(!header->GoodHeader()) { // check failed, try to continue to the next continue; } unsigned int assemblySizeInByte = ROUNDTOMULTIPLE(header->TotalSize(), CLR_UINT32); // advance stream beyond header BlockStorageStream_Seek(&stream, -headerInBytes, BlockStorageStream_SeekCurrent); // read the assembly if(!BlockStorageStream_Read(&stream, &assembliesBuffer, assemblySizeInByte)) break; header = (const CLR_RECORD_ASSEMBLY*)assembliesBuffer; if(!header->GoodAssembly()) { // check failed, try to continue to the next continue; } // we have good Assembly CLR_RT_Assembly* assm; CLR_Debug::Printf( "Attaching deployed file.\r\n" ); // Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem if (FAILED(LoadAssembly(header, assm))) { // load failed, try to continue to the next continue; } // load successfull, mark as deployed assm->m_flags |= CLR_RT_Assembly::Deployed; } NANOCLR_NOCLEANUP(); } HRESULT LoadDeploymentAssemblies() { NANOCLR_HEADER(); // perform initialization of BlockStorageStream structure BlockStorageStream stream; // init the stream for deployment storage if (!BlockStorageStream_Initialize(&stream, StorageUsage_DEPLOYMENT)) { #if !defined(BUILD_RTM) CLR_Debug::Printf( "ERROR: failed to initialize DEPLOYMENT storage\r\n" ); #endif NANOCLR_SET_AND_LEAVE(CLR_E_NOT_SUPPORTED); } ContiguousBlockAssemblies(stream); NANOCLR_NOCLEANUP(); } void Cleanup() { g_CLR_RT_Persistence_Manager.Uninitialize(); // UNDONE: FIXME: CLR_RT_ExecutionEngine::DeleteInstance(); m_fInitialized = false; } Settings() { m_fInitialized = false; } }; static Settings s_ClrSettings; void ClrStartup(CLR_SETTINGS params) { NATIVE_PROFILE_CLR_STARTUP(); Settings settings; ASSERT(sizeof(CLR_RT_HeapBlock_Raw) == sizeof(CLR_RT_HeapBlock)); bool softReboot; do { softReboot = false; CLR_RT_Assembly::InitString(); #if !defined(BUILD_RTM) CLR_Debug::Printf( "\r\nnanoCLR (Build %d.%d.%d.%d)\r\n\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD, VERSION_REVISION ); #endif CLR_RT_Memory::Reset(); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Starting...\r\n" ); #endif HRESULT hr; if(SUCCEEDED(hr = s_ClrSettings.Initialize(params))) { if(SUCCEEDED(hr = s_ClrSettings.Load())) { #if !defined(BUILD_RTM) CLR_Debug::Printf( "Ready.\r\n" ); #endif (void)g_CLR_RT_ExecutionEngine.Execute( NULL, params.MaxContextSwitches ); #if !defined(BUILD_RTM) CLR_Debug::Printf( "Done.\r\n" ); #endif } } if( CLR_EE_DBG_IS_NOT( RebootPending )) { #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) CLR_EE_DBG_SET_MASK(State_ProgramExited, State_Mask); CLR_EE_DBG_EVENT_BROADCAST(CLR_DBG_Commands::c_Monitor_ProgramExit, 0, NULL, WP_Flags_c_NonCritical); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(params.EnterDebuggerLoopAfterExit) { // UNDONE: FIXME: CLR_DBG_Debugger::Debugger_WaitForCommands(); } } // DO NOT USE 'ELSE IF' here because the state can change in Debugger_WaitForCommands() call if( CLR_EE_DBG_IS( RebootPending )) { if(CLR_EE_REBOOT_IS( ClrOnly )) { softReboot = true; params.WaitForDebugger = CLR_EE_REBOOT_IS(ClrOnlyStopDebugger); s_ClrSettings.Cleanup(); // UNDONE: FIXME: HAL_Uninitialize(); // UNDONE: FIXME: SmartPtr_IRQ::ForceDisabled(); //re-init the hal for the reboot (initially it is called in bootentry) // UNDONE: FIXME: HAL_Initialize(); // make sure interrupts are back on // UNDONE: FIXME: SmartPtr_IRQ::ForceEnabled(); } else { CPU_Reset(); } } } while( softReboot ); } <|endoftext|>
<commit_before>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "\n*Unknown command" << std::endl; } return result; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; // std::string input; // struct timeval timeout; fd_set read_set; // int file_desc = 0; int result; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); char stdin_buffer[kBufferSize]; memset(&stdin_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send std::cout << ">" << std::flush; while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(client_socket, &read_set)) { // Socket has data int read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { // TODO capture user input, store, clean input, then print buffer, afterward replace input struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; std::cout << ">" << std::flush; size_t buffer_size = strlen(stdin_buffer); for (size_t i = 0; i < buffer_size; i++) { std::cout << stdin_buffer[i] << std::flush; } break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } if (FD_ISSET(STDIN_FILENO, &read_set)) { int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize); if (read_stdin_size != 0) { if (stdin_buffer[0] == '/') { ProcessInput(stdin_buffer); } else { // Send chat messages StripChar(stdin_buffer, '\n'); RequestSay(stdin_buffer); } } memset(&stdin_buffer, 0, kBufferSize); } // end of if STDIN } // end of if result } // end of while return 0; }<commit_msg>print first char of buffer<commit_after>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "\n*Unknown command" << std::endl; } return result; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; // std::string input; // struct timeval timeout; fd_set read_set; // int file_desc = 0; int result; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); char stdin_buffer[kBufferSize]; memset(&stdin_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send std::cout << ">" << std::flush; while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(client_socket, &read_set)) { // Socket has data int read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { // TODO capture user input, store, clean input, then print buffer, afterward replace input struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; std::cout << ">" << std::flush; std::cout << stdin_buffer[0] << std::flush; break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } if (FD_ISSET(STDIN_FILENO, &read_set)) { int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize); if (read_stdin_size != 0) { if (stdin_buffer[0] == '/') { ProcessInput(stdin_buffer); } else { // Send chat messages StripChar(stdin_buffer, '\n'); RequestSay(stdin_buffer); } } memset(&stdin_buffer, 0, kBufferSize); } // end of if STDIN } // end of if result } // end of while return 0; }<|endoftext|>