text
stringlengths
54
60.6k
<commit_before>/* kpilotConfig.cc KPilot ** ** Copyright (C) 1998-2001 by Dan Pilone ** ** This is all of KPilot's config-handling stuff. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to kde-pim@kde.org */ #include "options.h" #include <stdlib.h> #include <qlineedit.h> #include <qcombobox.h> #include <qcheckbox.h> #include <kstddirs.h> #include <kconfig.h> #include <ksimpleconfig.h> #include <kcmdlineargs.h> #include <kmessagebox.h> #include <kglobalsettings.h> #include "kpilotSettings.h" #include "kpilotConfig.h" static const char kpilotconfig_id[] = "$Id$"; // This is a number indicating what configuration version // we're dealing with. Whenever new configuration options are // added that make it imperative for the user to take a // look at the configuration of KPilot (for example the // skipDB setting really needs user attention) we can change // (increase) this number. // // /* static */ const uint KPilotConfig::ConfigurationVersion = 443; /* static */ int KPilotConfig::getConfigVersion() { FUNCTIONSETUP; uint version = KPilotSettings::configVersion(); if (version < ConfigurationVersion) { kdWarning() << k_funcinfo << ": Config file has old version " << version << endl; } else { #ifdef DEBUG DEBUGDB << fname << ": Config file has version " << version << endl; #endif } return version; } /* static */ void KPilotConfig::updateConfigVersion() { FUNCTIONSETUP; KPilotSettings::setConfigVersion( ConfigurationVersion ); } /* static */ QString KPilotConfig::getDefaultDBPath() { FUNCTIONSETUP; QString lastUser = KPilotSettings::userName(); QString dbsubpath = CSL1("kpilot/DBBackup/"); QString defaultDBPath = KGlobal::dirs()-> saveLocation("data", dbsubpath + lastUser + CSL1("/")); return defaultDBPath; } /* static */ int KPilotConfig::getDebugLevel(KCmdLineArgs *p) { FUNCTIONSETUP; if (p) { if (p->isSet("debug")) { debug_level = p->getOption("debug").toInt(); } } return debug_level; } static QFont *thefont = 0L; /* static */ const QFont & KPilotConfig::fixed() { FUNCTIONSETUP; if (!thefont) thefont = new QFont(KGlobalSettings::fixedFont()); return *thefont; } void KPilotConfig::addDirtyDatabase(QString db) { FUNCTIONSETUP; QStringList l(KPilotSettings::dirtyDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setDirtyDatabases(l); } } void KPilotConfig::addAppBlockChangedDatabase(QString db) { QStringList l(KPilotSettings::appBlockChangedDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setAppBlockChangedDatabases(l); } } void KPilotConfig::addFlagsChangedDatabase(QString db) { QStringList l(KPilotSettings::flagsChangedDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setFlagsChangedDatabases(l); } } /* static */ QString KPilotConfig::versionDetails(int fileversion, bool run) { FUNCTIONSETUP; QString s = CSL1("<qt><p>"); s += i18n("The configuration file is outdated."); s += ' '; s += i18n("The configuration file has version %1, while KPilot " "needs version %2.").arg(fileversion).arg(ConfigurationVersion); if (run) { s += ' '; s += i18n("Please run KPilot and check the configuration carefully " "to update the file."); } s += CSL1("</p><p>"); s += i18n("Important changes to watch for are:"); s += ' '; if (fileversion < 440) { s += i18n("Renamed conduits, Kroupware and file installer have " "been made conduits as well."); s += ' '; s += i18n("Conflict resolution is now a global setting."); s += ' '; } if (fileversion < 443) { s += i18n("Changed format of no-backup databases."); s += ' '; } // Insert more recent additions here return s; } /* static */ void KPilotConfig::sorryVersionOutdated(int fileversion) { FUNCTIONSETUP; KMessageBox::detailedSorry(0L, i18n("The configuration file for KPilot is out-of " "date. Please run KPilot to update it."), KPilotConfig::versionDetails(fileversion,true), i18n("Configuration File Out-of Date")); } static void update440() { // Try to update conduit list { QStringList conduits( KPilotSettings::installedConduits() ); KConfig*c = KPilotSettings::self()->config(); /// c->resetGroup(); c->setGroup( QString::null ); bool useKroupware = c->readBoolEntry("SyncWithKMail",false); bool installFiles = c->readBoolEntry("SyncFiles",true); if (useKroupware) conduits.append( CSL1("internal_kroupware") ); if (installFiles) conduits.append( CSL1("internal_fileinstall") ); c->deleteEntry("SyncWithKMail"); c->deleteEntry("SyncFiles"); KPilotSettings::setInstalledConduits(conduits); c->sync(); if (useKroupware || installFiles) KMessageBox::information(0L, i18n("The settings for Kroupware syncing with KMail " "and the file installer have been moved to the " "conduits configuration. Check the installed " "conduits list."), i18n("Settings Updated")); } // Check if individual conduits have conflict settings? // Search for old conduit libraries. { QStringList foundlibs ; static const char *oldconduits[] = { "null", "address", "doc", "knotes", "sysinfo", "time", "todo", "vcal", 0L } ; const char **s = oldconduits; while (*s) { QString libname = CSL1("kde3/lib%1conduit.so").arg(*s); QString foundlib = ::locate("lib",libname); if (!foundlib.isEmpty()) { foundlibs.append(foundlib); } s++; } if (!foundlibs.isEmpty()) KMessageBox::informationList(0L, i18n("<qt>The following old conduits were found on " "your system. It is a good idea to remove " "them and the associated <tt>.la</tt> " "and <tt>.so.0</tt> files.</qt>"), foundlibs, i18n("Old Conduits Found")); } } static void update443() { FUNCTIONSETUP; QStringList skip = KPilotSettings::skipBackupDB(); QStringList fixSkip; bool fixedSome = false; #ifdef DEBUG DEBUGKPILOT << fname << ": Skip databases are: " << skip.join(",") << endl; #endif for (QStringList::const_iterator i = skip.begin(); i!=skip.end(); ++i) { if ((*i).length()==4) { fixSkip.append(CSL1("[%1]").arg(*i)); fixedSome = true; } else { fixSkip.append(*i); } } if (fixedSome) { KMessageBox::informationList(0L, i18n("<qt>The no backup databases listed in your configuration file " "have been adjusted to the new format. Database creator IDs " "have been changed to use square brackets []."), fixSkip, i18n("No Backup Databases Updated")); } } /* static */ KPilotConfig::RunMode KPilotConfig::interactiveUpdate() { FUNCTIONSETUP; int res = 0; unsigned int fileVersion = KPilotSettings::configVersion(); // FIXME better config handling -> Move the config entries using kconf_update // It's OK if we're already at the required level. if (fileVersion >= KPilotConfig::ConfigurationVersion) { return Normal; } if (0 == fileVersion) // No config file at all { res = KMessageBox::questionYesNoCancel(0L, i18n("KPilot is not configured for use. You may use " "the configuration wizard or the normal configure dialog " "to configure KPilot."), i18n("Not Configured"), i18n("Use &Wizard"), i18n("Use &Dialog")); if (res == KMessageBox::Yes) return WizardAndContinue; if (res == KMessageBox::No) return ConfigureAndContinue; return Cancel; } res = KMessageBox::warningContinueCancel(0L, i18n("The configuration file for KPilot is out-of " "date. KPilot can update some parts of the " "configuration automatically. Do you wish to " "continue?"), i18n("Configuration File Out-of Date")); if (res!=KMessageBox::Continue) return Cancel; #ifdef DEBUG DEBUGKPILOT << fname << ": Updating from " << fileVersion << " to " << ConfigurationVersion << endl; #endif if (fileVersion < 440) update440(); if (fileVersion < 443) update443(); KPilotConfig::updateConfigVersion(); KPilotSettings::writeConfig(); return ConfigureAndContinue; } void KPilotConfig::sync() { KPilotSettings::self()->config()->sync(); }<commit_msg>CVS_SILENT: Fix compiler warning about missing newline at end of file<commit_after>/* kpilotConfig.cc KPilot ** ** Copyright (C) 1998-2001 by Dan Pilone ** ** This is all of KPilot's config-handling stuff. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to kde-pim@kde.org */ #include "options.h" #include <stdlib.h> #include <qlineedit.h> #include <qcombobox.h> #include <qcheckbox.h> #include <kstddirs.h> #include <kconfig.h> #include <ksimpleconfig.h> #include <kcmdlineargs.h> #include <kmessagebox.h> #include <kglobalsettings.h> #include "kpilotSettings.h" #include "kpilotConfig.h" static const char kpilotconfig_id[] = "$Id$"; // This is a number indicating what configuration version // we're dealing with. Whenever new configuration options are // added that make it imperative for the user to take a // look at the configuration of KPilot (for example the // skipDB setting really needs user attention) we can change // (increase) this number. // // /* static */ const uint KPilotConfig::ConfigurationVersion = 443; /* static */ int KPilotConfig::getConfigVersion() { FUNCTIONSETUP; uint version = KPilotSettings::configVersion(); if (version < ConfigurationVersion) { kdWarning() << k_funcinfo << ": Config file has old version " << version << endl; } else { #ifdef DEBUG DEBUGDB << fname << ": Config file has version " << version << endl; #endif } return version; } /* static */ void KPilotConfig::updateConfigVersion() { FUNCTIONSETUP; KPilotSettings::setConfigVersion( ConfigurationVersion ); } /* static */ QString KPilotConfig::getDefaultDBPath() { FUNCTIONSETUP; QString lastUser = KPilotSettings::userName(); QString dbsubpath = CSL1("kpilot/DBBackup/"); QString defaultDBPath = KGlobal::dirs()-> saveLocation("data", dbsubpath + lastUser + CSL1("/")); return defaultDBPath; } /* static */ int KPilotConfig::getDebugLevel(KCmdLineArgs *p) { FUNCTIONSETUP; if (p) { if (p->isSet("debug")) { debug_level = p->getOption("debug").toInt(); } } return debug_level; } static QFont *thefont = 0L; /* static */ const QFont & KPilotConfig::fixed() { FUNCTIONSETUP; if (!thefont) thefont = new QFont(KGlobalSettings::fixedFont()); return *thefont; } void KPilotConfig::addDirtyDatabase(QString db) { FUNCTIONSETUP; QStringList l(KPilotSettings::dirtyDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setDirtyDatabases(l); } } void KPilotConfig::addAppBlockChangedDatabase(QString db) { QStringList l(KPilotSettings::appBlockChangedDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setAppBlockChangedDatabases(l); } } void KPilotConfig::addFlagsChangedDatabase(QString db) { QStringList l(KPilotSettings::flagsChangedDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setFlagsChangedDatabases(l); } } /* static */ QString KPilotConfig::versionDetails(int fileversion, bool run) { FUNCTIONSETUP; QString s = CSL1("<qt><p>"); s += i18n("The configuration file is outdated."); s += ' '; s += i18n("The configuration file has version %1, while KPilot " "needs version %2.").arg(fileversion).arg(ConfigurationVersion); if (run) { s += ' '; s += i18n("Please run KPilot and check the configuration carefully " "to update the file."); } s += CSL1("</p><p>"); s += i18n("Important changes to watch for are:"); s += ' '; if (fileversion < 440) { s += i18n("Renamed conduits, Kroupware and file installer have " "been made conduits as well."); s += ' '; s += i18n("Conflict resolution is now a global setting."); s += ' '; } if (fileversion < 443) { s += i18n("Changed format of no-backup databases."); s += ' '; } // Insert more recent additions here return s; } /* static */ void KPilotConfig::sorryVersionOutdated(int fileversion) { FUNCTIONSETUP; KMessageBox::detailedSorry(0L, i18n("The configuration file for KPilot is out-of " "date. Please run KPilot to update it."), KPilotConfig::versionDetails(fileversion,true), i18n("Configuration File Out-of Date")); } static void update440() { // Try to update conduit list { QStringList conduits( KPilotSettings::installedConduits() ); KConfig*c = KPilotSettings::self()->config(); /// c->resetGroup(); c->setGroup( QString::null ); bool useKroupware = c->readBoolEntry("SyncWithKMail",false); bool installFiles = c->readBoolEntry("SyncFiles",true); if (useKroupware) conduits.append( CSL1("internal_kroupware") ); if (installFiles) conduits.append( CSL1("internal_fileinstall") ); c->deleteEntry("SyncWithKMail"); c->deleteEntry("SyncFiles"); KPilotSettings::setInstalledConduits(conduits); c->sync(); if (useKroupware || installFiles) KMessageBox::information(0L, i18n("The settings for Kroupware syncing with KMail " "and the file installer have been moved to the " "conduits configuration. Check the installed " "conduits list."), i18n("Settings Updated")); } // Check if individual conduits have conflict settings? // Search for old conduit libraries. { QStringList foundlibs ; static const char *oldconduits[] = { "null", "address", "doc", "knotes", "sysinfo", "time", "todo", "vcal", 0L } ; const char **s = oldconduits; while (*s) { QString libname = CSL1("kde3/lib%1conduit.so").arg(*s); QString foundlib = ::locate("lib",libname); if (!foundlib.isEmpty()) { foundlibs.append(foundlib); } s++; } if (!foundlibs.isEmpty()) KMessageBox::informationList(0L, i18n("<qt>The following old conduits were found on " "your system. It is a good idea to remove " "them and the associated <tt>.la</tt> " "and <tt>.so.0</tt> files.</qt>"), foundlibs, i18n("Old Conduits Found")); } } static void update443() { FUNCTIONSETUP; QStringList skip = KPilotSettings::skipBackupDB(); QStringList fixSkip; bool fixedSome = false; #ifdef DEBUG DEBUGKPILOT << fname << ": Skip databases are: " << skip.join(",") << endl; #endif for (QStringList::const_iterator i = skip.begin(); i!=skip.end(); ++i) { if ((*i).length()==4) { fixSkip.append(CSL1("[%1]").arg(*i)); fixedSome = true; } else { fixSkip.append(*i); } } if (fixedSome) { KMessageBox::informationList(0L, i18n("<qt>The no backup databases listed in your configuration file " "have been adjusted to the new format. Database creator IDs " "have been changed to use square brackets []."), fixSkip, i18n("No Backup Databases Updated")); } } /* static */ KPilotConfig::RunMode KPilotConfig::interactiveUpdate() { FUNCTIONSETUP; int res = 0; unsigned int fileVersion = KPilotSettings::configVersion(); // FIXME better config handling -> Move the config entries using kconf_update // It's OK if we're already at the required level. if (fileVersion >= KPilotConfig::ConfigurationVersion) { return Normal; } if (0 == fileVersion) // No config file at all { res = KMessageBox::questionYesNoCancel(0L, i18n("KPilot is not configured for use. You may use " "the configuration wizard or the normal configure dialog " "to configure KPilot."), i18n("Not Configured"), i18n("Use &Wizard"), i18n("Use &Dialog")); if (res == KMessageBox::Yes) return WizardAndContinue; if (res == KMessageBox::No) return ConfigureAndContinue; return Cancel; } res = KMessageBox::warningContinueCancel(0L, i18n("The configuration file for KPilot is out-of " "date. KPilot can update some parts of the " "configuration automatically. Do you wish to " "continue?"), i18n("Configuration File Out-of Date")); if (res!=KMessageBox::Continue) return Cancel; #ifdef DEBUG DEBUGKPILOT << fname << ": Updating from " << fileVersion << " to " << ConfigurationVersion << endl; #endif if (fileVersion < 440) update440(); if (fileVersion < 443) update443(); KPilotConfig::updateConfigVersion(); KPilotSettings::writeConfig(); return ConfigureAndContinue; } void KPilotConfig::sync() { KPilotSettings::self()->config()->sync(); } <|endoftext|>
<commit_before>// Copyright (C) 2010 - 2015 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQRDFTreeView.h" #include "CQRDFTreeViewItem.h" #include "UI/CQMessageBox.h" #include "UI/qtUtilities.h" #include "MIRIAM/CRDFGraph.h" #include "MIRIAM/CRDFParser.h" // #include "MIRIAM/CRDFWriter.h" #include "MIRIAM/CRDFSubject.h" // #include "CopasiDataModel/CCopasiDataModel.h" // #include "report/CKeyFactory.h" // #include "model/CModel.h" #include "model/CModelValue.h" #include "model/CEvent.h" #include "model/CReaction.h" #include "function/CFunction.h" // #include "utilities/CCopasiMessage.h" #include "copasi/report/CCopasiRootContainer.h" #define COL_SUBJECT 0 #define COL_PREDICATE 1 #define COL_OBJECT 2 CQRDFTreeView::CQRDFTreeView(QWidget* parent, const char* name) : CopasiWidget(parent, name), mNode2Item(), mpGraph(NULL) { setupUi(this); } CQRDFTreeView::~CQRDFTreeView() { clear(); } bool CQRDFTreeView::update(ListViews::ObjectType /* objectType */, ListViews::Action /* action */, const std::string & /* key */) { return true; } bool CQRDFTreeView::enterProtected() { clear(); CCopasiObject *pObject = dynamic_cast< CCopasiObject * >(CCopasiRootContainer::getKeyFactory()->get(mKey)); if (pObject != NULL) { CModelEntity * pEntity = NULL; CEvent * pEvent = NULL; CReaction * pReaction = NULL; CFunction * pFunction = NULL; const std::string * pMiriamAnnotation = NULL; if ((pEntity = dynamic_cast< CModelEntity * >(pObject)) != NULL) pMiriamAnnotation = &pEntity->getMiriamAnnotation(); else if ((pEvent = dynamic_cast< CEvent * >(pObject)) != NULL) pMiriamAnnotation = &pEvent->getMiriamAnnotation(); else if ((pReaction = dynamic_cast< CReaction * >(pObject)) != NULL) pMiriamAnnotation = &pReaction->getMiriamAnnotation(); else if ((pFunction = dynamic_cast< CFunction * >(pObject)) != NULL) pMiriamAnnotation = &pFunction->getMiriamAnnotation(); if (pMiriamAnnotation && *pMiriamAnnotation != "") mpGraph = CRDFParser::graphFromXml(*pMiriamAnnotation); } CCopasiMessage::clearDeque(); if (CCopasiMessage::size() != 0) { QString Message = FROM_UTF8(CCopasiMessage::getAllMessageText()); CQMessageBox::warning(this, QString("RDF Warning"), Message, QMessageBox::Ok, QMessageBox::Ok); } if (mpGraph == NULL) mpGraph = new CRDFGraph; // We make sure that we always have an about node. mpGraph->createAboutNode(mKey); // We iterate of all triplets std::set< CRDFTriplet >::const_iterator it = mpGraph->getTriplets().begin(); std::set< CRDFTriplet >::const_iterator end = mpGraph->getTriplets().end(); for (; it != end; ++it) { CQRDFTreeViewItem * pSubjectItem = find(it->pSubject); if (pSubjectItem == NULL) { pSubjectItem = new CQRDFTreeViewItem(mpTreeWidget, NULL); insert(it->pSubject, pSubjectItem); // Display the subject information const CRDFSubject & Subject = it->pSubject->getSubject(); switch (Subject.getType()) { case CRDFSubject::RESOURCE: pSubjectItem->setText(COL_SUBJECT, FROM_UTF8(Subject.getResource())); break; case CRDFSubject::BLANK_NODE: pSubjectItem->setText(COL_SUBJECT, FROM_UTF8(Subject.getBlankNodeID())); break; } } CQRDFTreeViewItem * pObjectItem = NULL; if (it->Predicate.getURI() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject") { pObjectItem = new CQRDFTreeViewItem(pSubjectItem, NULL); insert(it->pObject, pObjectItem); } else pObjectItem = find(it->pObject); if (pObjectItem == NULL) { pObjectItem = new CQRDFTreeViewItem(pSubjectItem, NULL); insert(it->pObject, pObjectItem); } else { QTreeWidgetItem * pParent = pObjectItem->parent(); if (pParent == NULL) { mpTreeWidget->invisibleRootItem()->removeChild(pObjectItem); pSubjectItem->addChild(pObjectItem); } else { pParent->removeChild(pObjectItem); pSubjectItem->addChild(pObjectItem); } } pObjectItem->setTriplet(*it); } mpTreeWidget->setFocus(); return true; } void CQRDFTreeView::clear() { mNode2Item.clear(); pdelete(mpGraph); mpTreeWidget->clear(); } CQRDFTreeViewItem * CQRDFTreeView::find(const CRDFNode * pNode) { std::map< const CRDFNode *, CQRDFTreeViewItem * >::iterator it = mNode2Item.find(pNode); if (it != mNode2Item.end()) return it->second; return NULL; } void CQRDFTreeView::insert(const CRDFNode * pNode, CQRDFTreeViewItem * pItem) { mNode2Item[pNode] = pItem; } <commit_msg>- issue 2456: found the focus stealing code<commit_after>// Copyright (C) 2010 - 2015 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQRDFTreeView.h" #include "CQRDFTreeViewItem.h" #include "UI/CQMessageBox.h" #include "UI/qtUtilities.h" #include "MIRIAM/CRDFGraph.h" #include "MIRIAM/CRDFParser.h" // #include "MIRIAM/CRDFWriter.h" #include "MIRIAM/CRDFSubject.h" // #include "CopasiDataModel/CCopasiDataModel.h" // #include "report/CKeyFactory.h" // #include "model/CModel.h" #include "model/CModelValue.h" #include "model/CEvent.h" #include "model/CReaction.h" #include "function/CFunction.h" // #include "utilities/CCopasiMessage.h" #include "copasi/report/CCopasiRootContainer.h" #define COL_SUBJECT 0 #define COL_PREDICATE 1 #define COL_OBJECT 2 CQRDFTreeView::CQRDFTreeView(QWidget* parent, const char* name) : CopasiWidget(parent, name), mNode2Item(), mpGraph(NULL) { setupUi(this); } CQRDFTreeView::~CQRDFTreeView() { clear(); } bool CQRDFTreeView::update(ListViews::ObjectType /* objectType */, ListViews::Action /* action */, const std::string & /* key */) { return true; } bool CQRDFTreeView::enterProtected() { clear(); CCopasiObject *pObject = dynamic_cast< CCopasiObject * >(CCopasiRootContainer::getKeyFactory()->get(mKey)); if (pObject != NULL) { CModelEntity * pEntity = NULL; CEvent * pEvent = NULL; CReaction * pReaction = NULL; CFunction * pFunction = NULL; const std::string * pMiriamAnnotation = NULL; if ((pEntity = dynamic_cast< CModelEntity * >(pObject)) != NULL) pMiriamAnnotation = &pEntity->getMiriamAnnotation(); else if ((pEvent = dynamic_cast< CEvent * >(pObject)) != NULL) pMiriamAnnotation = &pEvent->getMiriamAnnotation(); else if ((pReaction = dynamic_cast< CReaction * >(pObject)) != NULL) pMiriamAnnotation = &pReaction->getMiriamAnnotation(); else if ((pFunction = dynamic_cast< CFunction * >(pObject)) != NULL) pMiriamAnnotation = &pFunction->getMiriamAnnotation(); if (pMiriamAnnotation && *pMiriamAnnotation != "") mpGraph = CRDFParser::graphFromXml(*pMiriamAnnotation); } CCopasiMessage::clearDeque(); if (CCopasiMessage::size() != 0) { QString Message = FROM_UTF8(CCopasiMessage::getAllMessageText()); CQMessageBox::warning(this, QString("RDF Warning"), Message, QMessageBox::Ok, QMessageBox::Ok); } if (mpGraph == NULL) mpGraph = new CRDFGraph; // We make sure that we always have an about node. mpGraph->createAboutNode(mKey); // We iterate of all triplets std::set< CRDFTriplet >::const_iterator it = mpGraph->getTriplets().begin(); std::set< CRDFTriplet >::const_iterator end = mpGraph->getTriplets().end(); for (; it != end; ++it) { CQRDFTreeViewItem * pSubjectItem = find(it->pSubject); if (pSubjectItem == NULL) { pSubjectItem = new CQRDFTreeViewItem(mpTreeWidget, NULL); insert(it->pSubject, pSubjectItem); // Display the subject information const CRDFSubject & Subject = it->pSubject->getSubject(); switch (Subject.getType()) { case CRDFSubject::RESOURCE: pSubjectItem->setText(COL_SUBJECT, FROM_UTF8(Subject.getResource())); break; case CRDFSubject::BLANK_NODE: pSubjectItem->setText(COL_SUBJECT, FROM_UTF8(Subject.getBlankNodeID())); break; } } CQRDFTreeViewItem * pObjectItem = NULL; if (it->Predicate.getURI() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject") { pObjectItem = new CQRDFTreeViewItem(pSubjectItem, NULL); insert(it->pObject, pObjectItem); } else pObjectItem = find(it->pObject); if (pObjectItem == NULL) { pObjectItem = new CQRDFTreeViewItem(pSubjectItem, NULL); insert(it->pObject, pObjectItem); } else { QTreeWidgetItem * pParent = pObjectItem->parent(); if (pParent == NULL) { mpTreeWidget->invisibleRootItem()->removeChild(pObjectItem); pSubjectItem->addChild(pObjectItem); } else { pParent->removeChild(pObjectItem); pSubjectItem->addChild(pObjectItem); } } pObjectItem->setTriplet(*it); } //mpTreeWidget->setFocus(); return true; } void CQRDFTreeView::clear() { mNode2Item.clear(); pdelete(mpGraph); mpTreeWidget->clear(); } CQRDFTreeViewItem * CQRDFTreeView::find(const CRDFNode * pNode) { std::map< const CRDFNode *, CQRDFTreeViewItem * >::iterator it = mNode2Item.find(pNode); if (it != mNode2Item.end()) return it->second; return NULL; } void CQRDFTreeView::insert(const CRDFNode * pNode, CQRDFTreeViewItem * pItem) { mNode2Item[pNode] = pItem; } <|endoftext|>
<commit_before>/// \file ROOT/TLogger.h /// \ingroup Base ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2015-03-29 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, 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 ROOT7_TLog #define ROOT7_TLog #include <array> #include <memory> #include <sstream> #include "RStringView.h" #include <vector> namespace ROOT { namespace Experimental { /** Kinds of diagnostics. */ enum class ELogLevel { kDebug, ///< Debug information; only useful for developers kInfo, ///< Informational messages; used for instance for tracing kWarning, ///< Warnings about likely unexpected behavior kError, kFatal }; class TLogEntry; /** Abstract TLogHandler base class. ROOT logs everything from info to error to entities of this class. */ class TLogHandler { public: virtual ~TLogHandler(); // Returns false if further emission of this Log should be suppressed. virtual bool Emit(const TLogEntry &entry) = 0; }; class TLogManager: public TLogHandler { private: std::vector<std::unique_ptr<TLogHandler>> fHandlers; /// Initialize taking a TLogHandlerDefault. TLogManager(std::unique_ptr<TLogHandler> &&lh) { fHandlers.emplace_back(std::move(lh)); } public: static TLogManager &Get(); /// Add a TLogHandler in the front - to be called before all others. void PushFront(std::unique_ptr<TLogHandler> handler) { fHandlers.insert(fHandlers.begin(), std::move(handler)); } /// Add a TLogHandler in the back - to be called after all others. void PushBack(std::unique_ptr<TLogHandler> handler) { fHandlers.emplace_back(std::move(handler)); } // Emit a `TLogEntry` to the TLogHandlers. // Returns false if further emission of this Log should be suppressed. bool Emit(const TLogEntry &entry) override { for (auto &&handler: fHandlers) if (!handler->Emit(entry)) return false; return true; } }; class TLogEntry: public std::ostringstream { public: std::string fGroup; std::string fFile; std::string fFuncName; int fLine = 0; ELogLevel fLevel; public: TLogEntry() = default; TLogEntry(ELogLevel level, std::string_view group): fGroup(group), fLevel(level) {} TLogEntry(ELogLevel level, std::string_view group, std::string_view filename, int line, std::string_view funcname) : fGroup(group), fFile(filename), fFuncName(funcname), fLine(line), fLevel(level) {} TLogEntry &SetFile(const std::string &file) { fFile = file; return *this; } TLogEntry &SetFunction(const std::string &func) { fFuncName = func; return *this; } TLogEntry &SetLine(int line) { fLine = line; return *this; } ~TLogEntry() { TLogManager::Get().Emit(*this); } }; } // namespace Experimental } // namespace ROOT #if defined(_MSC_VER) #define LOG_PRETTY_FUNCTION __FUNCSIG__ #elif defined(__GNUC__) || defined(__clang__) #define LOG_PRETTY_FUNCTION __PRETTY_FUNCTION__ #else #define LOG_PRETTY_FUNCTION __func__ #endif #define R__LOG_HERE(LEVEL, GROUP) \ ROOT::Experimental::TLogEntry(LEVEL, GROUP).SetFile(__FILE__).SetLine(__LINE__).SetFunction(__PRETTY_FUNCTION__) #define R__FATAL_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kFatal, GROUP) #define R__ERROR_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kError, GROUP) #define R__WARNING_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kWarning, GROUP) #define R__INFO_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kInfo, GROUP) #define R__DEBUG_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kDebug, GROUP) #endif <commit_msg>Add forgotten variable<commit_after>/// \file ROOT/TLogger.h /// \ingroup Base ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2015-03-29 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, 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 ROOT7_TLog #define ROOT7_TLog #include <array> #include <memory> #include <sstream> #include "RStringView.h" #include <vector> namespace ROOT { namespace Experimental { /** Kinds of diagnostics. */ enum class ELogLevel { kDebug, ///< Debug information; only useful for developers kInfo, ///< Informational messages; used for instance for tracing kWarning, ///< Warnings about likely unexpected behavior kError, kFatal }; class TLogEntry; /** Abstract TLogHandler base class. ROOT logs everything from info to error to entities of this class. */ class TLogHandler { public: virtual ~TLogHandler(); // Returns false if further emission of this Log should be suppressed. virtual bool Emit(const TLogEntry &entry) = 0; }; class TLogManager: public TLogHandler { private: std::vector<std::unique_ptr<TLogHandler>> fHandlers; /// Initialize taking a TLogHandlerDefault. TLogManager(std::unique_ptr<TLogHandler> &&lh) { fHandlers.emplace_back(std::move(lh)); } public: static TLogManager &Get(); /// Add a TLogHandler in the front - to be called before all others. void PushFront(std::unique_ptr<TLogHandler> handler) { fHandlers.insert(fHandlers.begin(), std::move(handler)); } /// Add a TLogHandler in the back - to be called after all others. void PushBack(std::unique_ptr<TLogHandler> handler) { fHandlers.emplace_back(std::move(handler)); } // Emit a `TLogEntry` to the TLogHandlers. // Returns false if further emission of this Log should be suppressed. bool Emit(const TLogEntry &entry) override { for (auto &&handler: fHandlers) if (!handler->Emit(entry)) return false; return true; } }; class TLogEntry: public std::ostringstream { public: std::string fGroup; std::string fFile; std::string fFuncName; int fLine = 0; ELogLevel fLevel; public: TLogEntry() = default; TLogEntry(ELogLevel level, std::string_view group): fGroup(group), fLevel(level) {} TLogEntry(ELogLevel level, std::string_view group, std::string_view filename, int line, std::string_view funcname) : fGroup(group), fFile(filename), fFuncName(funcname), fLine(line), fLevel(level) {} TLogEntry &SetFile(const std::string &file) { fFile = file; return *this; } TLogEntry &SetFunction(const std::string &func) { fFuncName = func; return *this; } TLogEntry &SetLine(int line) { fLine = line; return *this; } ~TLogEntry() { TLogManager::Get().Emit(*this); } }; } // namespace Experimental } // namespace ROOT #if defined(_MSC_VER) #define LOG_PRETTY_FUNCTION __FUNCSIG__ #elif defined(__GNUC__) || defined(__clang__) #define LOG_PRETTY_FUNCTION __PRETTY_FUNCTION__ #else #define LOG_PRETTY_FUNCTION __func__ #endif #define R__LOG_HERE(LEVEL, GROUP) \ ROOT::Experimental::TLogEntry(LEVEL, GROUP).SetFile(__FILE__).SetLine(__LINE__).SetFunction(LOG_PRETTY_FUNCTION) #define R__FATAL_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kFatal, GROUP) #define R__ERROR_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kError, GROUP) #define R__WARNING_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kWarning, GROUP) #define R__INFO_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kInfo, GROUP) #define R__DEBUG_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kDebug, GROUP) #endif <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNodeFunction.cpp,v $ $Revision: 1.1 $ $Name: $ $Author: shoops $ $Date: 2005/05/27 21:00:58 $ End CVS Header */ #include "copasi.h" #include "mathematics.h" #include "CEvaluationNode.h" CEvaluationNodeFunction::CEvaluationNodeFunction(): CEvaluationNode(CEvaluationNode::INVALID, "") {} CEvaluationNodeFunction::CEvaluationNodeFunction(const SubType & subType, const Data & data): CEvaluationNode((Type) (CEvaluationNode::NUMBER | subType), data), mpFunction(NULL), mpLeft(NULL) { switch (subType) { case LOG: mpFunction = log; break; case LOG10: mpFunction = log10; break; case EXP: mpFunction = exp; break; case SIN: mpFunction = sin; break; case COS: mpFunction = cos; break; case TAN: mpFunction = sec; break; case SEC: mpFunction = NULL; break; case CSC: mpFunction = NULL; break; case COT: mpFunction = NULL; break; case SINH: mpFunction = sinh; break; case COSH: mpFunction = cosh; break; case TANH: mpFunction = tanh; break; case SECH: mpFunction = NULL; break; case CSCH: mpFunction = NULL; break; case COTH: mpFunction = NULL; break; case ARCSIN: mpFunction = asin; break; case ARCCOS: mpFunction = acos; break; case ARCTAN: mpFunction = atan; break; case ARCSEC: mpFunction = NULL; break; case ARCCSC: mpFunction = NULL; break; case ARCCOT: mpFunction = NULL; break; case ARCSINH: mpFunction = NULL; break; case ARCCOSH: mpFunction = NULL; break; case ARCTANH: mpFunction = NULL; break; case ARCSECH: mpFunction = NULL; break; case ARCCSCH: mpFunction = NULL; break; case ARCCOTH: mpFunction = NULL; break; case SQRT: mpFunction = sqrt; break; case ABS: mpFunction = fabs; break; default: mpFunction = NULL; fatalError(); break; } } CEvaluationNodeFunction::CEvaluationNodeFunction(const CEvaluationNodeFunction & src): CEvaluationNode(src), mpFunction(src.mpFunction) {} CEvaluationNodeFunction::~CEvaluationNodeFunction() {} bool CEvaluationNodeFunction::compile() { mpLeft = static_cast<CEvaluationNode *>(getChild()); if (mpLeft == NULL) return false; return (mpLeft->getSibling() == NULL); // We must have only one child } <commit_msg>Implementation completed.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNodeFunction.cpp,v $ $Revision: 1.2 $ $Name: $ $Author: shoops $ $Date: 2005/05/27 21:14:54 $ End CVS Header */ #include "copasi.h" #include "mathematics.h" #include "CEvaluationNode.h" CEvaluationNodeFunction::CEvaluationNodeFunction(): CEvaluationNode(CEvaluationNode::INVALID, "") {} CEvaluationNodeFunction::CEvaluationNodeFunction(const SubType & subType, const Data & data): CEvaluationNode((Type) (CEvaluationNode::NUMBER | subType), data), mpFunction(NULL), mpLeft(NULL) { switch (subType) { case LOG: mpFunction = log; break; case LOG10: mpFunction = log10; break; case EXP: mpFunction = exp; break; case SIN: mpFunction = sin; break; case COS: mpFunction = cos; break; case TAN: mpFunction = sec; break; case SEC: mpFunction = csc; break; case CSC: mpFunction = cot; break; case COT: mpFunction = NULL; break; case SINH: mpFunction = sinh; break; case COSH: mpFunction = cosh; break; case TANH: mpFunction = tanh; break; case SECH: mpFunction = sech; break; case CSCH: mpFunction = csch; break; case COTH: mpFunction = coth; break; case ARCSIN: mpFunction = asin; break; case ARCCOS: mpFunction = acos; break; case ARCTAN: mpFunction = atan; break; case ARCSEC: mpFunction = arcsec; break; case ARCCSC: mpFunction = arccsc; break; case ARCCOT: mpFunction = arccot; break; case ARCSINH: mpFunction = asinh; break; case ARCCOSH: mpFunction = acosh; break; case ARCTANH: mpFunction = atanh; break; case ARCSECH: mpFunction = asech; break; case ARCCSCH: mpFunction = acsch; break; case ARCCOTH: mpFunction = acoth; break; case SQRT: mpFunction = sqrt; break; case ABS: mpFunction = fabs; break; default: mpFunction = NULL; fatalError(); break; } } CEvaluationNodeFunction::CEvaluationNodeFunction(const CEvaluationNodeFunction & src): CEvaluationNode(src), mpFunction(src.mpFunction) {} CEvaluationNodeFunction::~CEvaluationNodeFunction() {} bool CEvaluationNodeFunction::compile() { mpLeft = static_cast<CEvaluationNode *>(getChild()); if (mpLeft == NULL) return false; return (mpLeft->getSibling() == NULL); // We must have only one child } <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- // csved_exec.cpp // // execute external command against each CSV input record // // Copyright (C) 2009 Neil Butterworth //--------------------------------------------------------------------------- #include "a_exec.h" #include "a_collect.h" #include "csved_cli.h" #include "csved_exec.h" #include "csved_strings.h" using std::string; using std::vector; namespace CSVED { //--------------------------------------------------------------------------- // Register exec command //--------------------------------------------------------------------------- static RegisterCommand <ExecCommand> rc1_( CMD_EXEC, "execute external command" ); //---------------------------------------------------------------------------- // Help text //---------------------------------------------------------------------------- const char * const EXEC_HELP = { "execute external command with CSV as parameters\n" "usage: csvfix exec [flags] [file ...]\n" "where flags are:\n" " -c cmd\tcommand line to execute\n" " -r\t\treplace CSV input with command output\n" "#ALL,SKIP,PASS" }; //------------------------------------------------------------------------ // Standard command ctor //--------------------------------------------------------------------------- ExecCommand ::ExecCommand( const string & name, const string & desc ) : Command( name, desc, EXEC_HELP ) { AddFlag( ALib::CommandLineFlag( FLAG_CMD, true, 1 ) ); AddFlag( ALib::CommandLineFlag( FLAG_REPLACE, false, 0 ) ); AddFlag( ALib::CommandLineFlag( FLAG_IGNOREX, false, 1 ) ); } //--------------------------------------------------------------------------- // Execute commands against CSV input. If the -r flag is used, output result // only else append result to input CSV. //--------------------------------------------------------------------------- int ExecCommand :: Execute( ALib::CommandLine & cmd ) { GetSkipOptions( cmd ); mCmdLine = cmd.GetValue( FLAG_CMD, "" ); if ( ALib::IsEmpty( mCmdLine ) ) { CSVTHROW( "Empty command" ); } bool csv = ! cmd.HasFlag( FLAG_REPLACE ); string ix = cmd.GetValue( FLAG_IGNOREX, "0" ); if ( ! ALib::IsInteger( ix ) ) { CSVTHROW( "Invalid value for " << FLAG_IGNOREX << ": " << ix ); } int nix = ALib::ToInteger( ix ); IOManager io( cmd ); CSVRow row; ALib::Executor ex; while( io.ReadCSV( row ) ) { if ( Skip( io, row ) ) { continue; } string cmd = MakeCmd( row ); std::istream & is = ex.Exec( cmd, nix ); if ( ! is ) { CSVTHROW( "Command execution error" ); } string line; ALib::CSVLineParser clp; while( std::getline( is, line ) ) { if ( csv ) { CSVRow tmp( row ), cmdout; if ( ! Pass( io, tmp ) ) { clp.Parse( line, cmdout ); ALib::operator+=( tmp, cmdout ); io.WriteRow( tmp ); } } else { io.Out() << line << "\n"; } } } return 0; } //---------------------------------------------------------------------------- // Helpers to make the command string from the -c flag value and the CSV // input data. //---------------------------------------------------------------------------- const char PARAMC = '%'; // param intro character string ExecCommand :: MakeCmd( const CSVRow & row ) { string cmd; unsigned int pos = 0; while( char c = ALib::Peek( mCmdLine, pos ) ) { if ( c == PARAMC ) { cmd += MakeParam( row, ++pos ); } else { cmd += c; pos++; } } return cmd; } //---------------------------------------------------------------------------- // Called with pos set to first charcter of parameter after '%' intro char. // We allow MAX_PARAM parameters - actual number is not significant. //---------------------------------------------------------------------------- string ExecCommand :: MakeParam( const CSVRow & row, unsigned int & pos ) { const int MAX_PARAM = 100; char c = ALib::Peek( mCmdLine, pos ); if ( c == PARAMC ) { pos++; return ALib::Str( PARAMC ); } else if ( std::isdigit( c ) ) { string p; while ( std::isdigit( c ) ) { pos++; p += c; c = ALib::Peek( mCmdLine, pos ); } int n = ALib::ToInteger( p ) - 1; if ( n < 0 || n > MAX_PARAM ) { CSVTHROW( "Invalid parameter: %" << p ); } // different quoting rules for windows and unix #ifdef _WIN32 return (unsigned int) n < row.size() ? row[n] : ""; #else return (unsigned int) n < row.size() ? ALib::Escape( row[n], "\\'\"", "\\" ) : ""; #endif } else { ATHROW( "Invalid parameter" ); } } //------------------------------------------------------------------------ } // end namespace // end <commit_msg>updated inline help for -ix option<commit_after>//--------------------------------------------------------------------------- // csved_exec.cpp // // execute external command against each CSV input record // // Copyright (C) 2009 Neil Butterworth //--------------------------------------------------------------------------- #include "a_exec.h" #include "a_collect.h" #include "csved_cli.h" #include "csved_exec.h" #include "csved_strings.h" using std::string; using std::vector; namespace CSVED { //--------------------------------------------------------------------------- // Register exec command //--------------------------------------------------------------------------- static RegisterCommand <ExecCommand> rc1_( CMD_EXEC, "execute external command" ); //---------------------------------------------------------------------------- // Help text //---------------------------------------------------------------------------- const char * const EXEC_HELP = { "execute external command with CSV as parameters\n" "usage: csvfix exec [flags] [file ...]\n" "where flags are:\n" " -c cmd\tcommand line to execute\n" " -r\t\treplace CSV input with command output\n" " -ix ecode\tignore exit codes from cmd with values less than or equal to ecode\n" "#ALL,SKIP,PASS" }; //------------------------------------------------------------------------ // Standard command ctor //--------------------------------------------------------------------------- ExecCommand ::ExecCommand( const string & name, const string & desc ) : Command( name, desc, EXEC_HELP ) { AddFlag( ALib::CommandLineFlag( FLAG_CMD, true, 1 ) ); AddFlag( ALib::CommandLineFlag( FLAG_REPLACE, false, 0 ) ); AddFlag( ALib::CommandLineFlag( FLAG_IGNOREX, false, 1 ) ); } //--------------------------------------------------------------------------- // Execute commands against CSV input. If the -r flag is used, output result // only else append result to input CSV. //--------------------------------------------------------------------------- int ExecCommand :: Execute( ALib::CommandLine & cmd ) { GetSkipOptions( cmd ); mCmdLine = cmd.GetValue( FLAG_CMD, "" ); if ( ALib::IsEmpty( mCmdLine ) ) { CSVTHROW( "Empty command" ); } bool csv = ! cmd.HasFlag( FLAG_REPLACE ); string ix = cmd.GetValue( FLAG_IGNOREX, "0" ); if ( ! ALib::IsInteger( ix ) ) { CSVTHROW( "Invalid value for " << FLAG_IGNOREX << ": " << ix ); } int nix = ALib::ToInteger( ix ); IOManager io( cmd ); CSVRow row; ALib::Executor ex; while( io.ReadCSV( row ) ) { if ( Skip( io, row ) ) { continue; } string cmd = MakeCmd( row ); std::istream & is = ex.Exec( cmd, nix ); if ( ! is ) { CSVTHROW( "Command execution error" ); } string line; ALib::CSVLineParser clp; while( std::getline( is, line ) ) { if ( csv ) { CSVRow tmp( row ), cmdout; if ( ! Pass( io, tmp ) ) { clp.Parse( line, cmdout ); ALib::operator+=( tmp, cmdout ); io.WriteRow( tmp ); } } else { io.Out() << line << "\n"; } } } return 0; } //---------------------------------------------------------------------------- // Helpers to make the command string from the -c flag value and the CSV // input data. //---------------------------------------------------------------------------- const char PARAMC = '%'; // param intro character string ExecCommand :: MakeCmd( const CSVRow & row ) { string cmd; unsigned int pos = 0; while( char c = ALib::Peek( mCmdLine, pos ) ) { if ( c == PARAMC ) { cmd += MakeParam( row, ++pos ); } else { cmd += c; pos++; } } return cmd; } //---------------------------------------------------------------------------- // Called with pos set to first charcter of parameter after '%' intro char. // We allow MAX_PARAM parameters - actual number is not significant. //---------------------------------------------------------------------------- string ExecCommand :: MakeParam( const CSVRow & row, unsigned int & pos ) { const int MAX_PARAM = 100; char c = ALib::Peek( mCmdLine, pos ); if ( c == PARAMC ) { pos++; return ALib::Str( PARAMC ); } else if ( std::isdigit( c ) ) { string p; while ( std::isdigit( c ) ) { pos++; p += c; c = ALib::Peek( mCmdLine, pos ); } int n = ALib::ToInteger( p ) - 1; if ( n < 0 || n > MAX_PARAM ) { CSVTHROW( "Invalid parameter: %" << p ); } // different quoting rules for windows and unix #ifdef _WIN32 return (unsigned int) n < row.size() ? row[n] : ""; #else return (unsigned int) n < row.size() ? ALib::Escape( row[n], "\\'\"", "\\" ) : ""; #endif } else { ATHROW( "Invalid parameter" ); } } //------------------------------------------------------------------------ } // end namespace // end <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/usr/hwpf/hwp/chip_accessors/getOscswitchCtlAttr.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* COPYRIGHT International Business Machines Corp. 2013,2014 */ /* */ /* 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 */ // $Id: getOscswitchCtlAttr.H,v 1.1 2014/05/23 01:23:14 whs Exp $ /** * @file getOscswitchCtlAttr.H * * @brief Accessor for providing the ATTR_OSCSWITCH_CTLx attributes */ #ifndef _HWP_GETOSCSWITCHCNTL #define _HWP_GETOSCSWITCHCNTL #include <fapi.H> namespace fapi { namespace getOscswitchCtl { // Attributes supported enum Attr { CTL0 = 0x00, // ATTR_OSCSWITCH_CTL0 CTL1 = 0x01, // ATTR_OSCSWITCH_CTL1 CTL2 = 0x02, // ATTR_OSCSWITCH_CTL2 }; // Oscswitch control data struct OSCSWITCH_CTL_DATA { ATTR_NAME_Enum l_CHIP_TYPE; // uint8_t l_CHIP_EC; // can be added if needed uint32_t l_CTL0; uint8_t l_CTL1; uint32_t l_CTL2; }; // This structure could be generated from engineering data as // there are more systems with redundant clocks or if values // become EC specific const OSCSWITCH_CTL_DATA OSCSWITCH_CTL_DATA_array []= { { // Entry if there are no redundant clocks ENUM_ATTR_NAME_NONE, 0x0080, 0x00, 0x00, }, { // Entry for Brazos ENUM_ATTR_NAME_VENICE, 0x0A02, 0x2E, 0x00, } }; } } // function pointer typedef definition for HWP call support typedef fapi::ReturnCode (*getOscswitchCtlAttr_FP_t) (const fapi::Target &, const fapi::getOscswitchCtl::Attr, void *, const size_t); extern "C" { /** * @brief This function is called by the FAPI_ATTR_GET macro when getting the * ATTR_OSCSWITCH_CNTL0,1,2 attributes. It should not be called * directly. * * @param[in] i_pProcTarget Processor Chip Target pointer * @param[in] i_attr Attribute selection * @param[out] o_pVal Pointer to output variable * @param[in] i_len Size of o_pVal */ fapi::ReturnCode getOscswitchCtlAttr (const fapi::Target & i_pProcTarget, const fapi::getOscswitchCtl::Attr i_attr, void * o_pVal, const size_t i_len); } #endif <commit_msg>Change oscillator tweak register bit<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/usr/hwpf/hwp/chip_accessors/getOscswitchCtlAttr.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* COPYRIGHT International Business Machines Corp. 2013,2014 */ /* */ /* 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 */ // $Id: getOscswitchCtlAttr.H,v 1.2 2014/06/19 14:35:43 whs Exp $ /** * @file getOscswitchCtlAttr.H * * @brief Accessor for providing the ATTR_OSCSWITCH_CTLx attributes */ #ifndef _HWP_GETOSCSWITCHCNTL #define _HWP_GETOSCSWITCHCNTL #include <fapi.H> namespace fapi { namespace getOscswitchCtl { // Attributes supported enum Attr { CTL0 = 0x00, // ATTR_OSCSWITCH_CTL0 CTL1 = 0x01, // ATTR_OSCSWITCH_CTL1 CTL2 = 0x02, // ATTR_OSCSWITCH_CTL2 }; // Oscswitch control data struct OSCSWITCH_CTL_DATA { ATTR_NAME_Enum l_CHIP_TYPE; // uint8_t l_CHIP_EC; // can be added if needed uint32_t l_CTL0; uint8_t l_CTL1; uint32_t l_CTL2; }; // This structure could be generated from engineering data as // there are more systems with redundant clocks or if values // become EC specific const OSCSWITCH_CTL_DATA OSCSWITCH_CTL_DATA_array []= { { // Entry if there are no redundant clocks ENUM_ATTR_NAME_NONE, 0x0080, 0x00, 0x00, }, { // Entry for Brazos ENUM_ATTR_NAME_VENICE, 0x0A02, 0x2E, 0x00400000, } }; } } // function pointer typedef definition for HWP call support typedef fapi::ReturnCode (*getOscswitchCtlAttr_FP_t) (const fapi::Target &, const fapi::getOscswitchCtl::Attr, void *, const size_t); extern "C" { /** * @brief This function is called by the FAPI_ATTR_GET macro when getting the * ATTR_OSCSWITCH_CNTL0,1,2 attributes. It should not be called * directly. * * @param[in] i_pProcTarget Processor Chip Target pointer * @param[in] i_attr Attribute selection * @param[out] o_pVal Pointer to output variable * @param[in] i_len Size of o_pVal */ fapi::ReturnCode getOscswitchCtlAttr (const fapi::Target & i_pProcTarget, const fapi::getOscswitchCtl::Attr i_attr, void * o_pVal, const size_t i_len); } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2009, Willow Garage, Inc. * * 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 names 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. */ #include "ros/master.h" #include "ros/xmlrpc_manager.h" #include "ros/this_node.h" #include "ros/init.h" #include "ros/network.h" #include <ros/console.h> #include <ros/assert.h> #include "XmlRpc.h" namespace ros { namespace master { uint32_t g_port = 0; std::string g_host; std::string g_uri; ros::WallDuration g_retry_timeout; void init(const M_string& remappings) { M_string::const_iterator it = remappings.find("__master"); if (it != remappings.end()) { g_uri = it->second; } if (g_uri.empty()) { char *master_uri_env = getenv("ROS_MASTER_URI"); if (!master_uri_env) { ROS_FATAL( "ROS_MASTER_URI is not defined in the environment. Either " \ "type the following or (preferrably) add this to your " \ "~/.bashrc file in order set up your " \ "local machine as a ROS master:\n\n" \ "export ROS_MASTER_URI=http://localhost:11311\n\n" \ "then, type 'roscore' in another shell to actually launch " \ "the master program."); ROS_BREAK(); } g_uri = master_uri_env; } // Split URI into if (!network::splitURI(g_uri, g_host, g_port)) { ROS_FATAL( "Couldn't parse the master URI [%s] into a host:port pair.", g_uri.c_str()); ROS_BREAK(); } } const std::string& getHost() { return g_host; } uint32_t getPort() { return g_port; } const std::string& getURI() { return g_uri; } void setRetryTimeout(ros::WallDuration timeout) { g_retry_timeout = timeout; } bool check() { XmlRpc::XmlRpcValue args, result, payload; args[0] = this_node::getName(); return execute("getPid", args, result, payload, false); } bool getTopics(V_TopicInfo& topics) { XmlRpc::XmlRpcValue args, result, payload; args[0] = this_node::getName(); args[1] = ""; //TODO: Fix this if (!execute("getPublishedTopics", args, result, payload, true)) { return false; } topics.clear(); for (int i = 0; i < payload.size(); i++) { topics.push_back(TopicInfo(std::string(payload[i][0]), std::string(payload[i][1]), std::string(payload[i][1]))); } return true; } bool getNodes(V_string& nodes) { XmlRpc::XmlRpcValue args, result, payload; args[0] = this_node::getName(); if (!execute("getSystemState", args, result, payload, true)) { return false; } S_string node_set; for (int i = 0; i < payload.size(); ++i) { for (int j = 0; j < payload[i].size(); ++j) { XmlRpc::XmlRpcValue val = payload[i][j][1]; for (int k = 0; k < val.size(); ++k) { std::string name = payload[i][j][1][k]; node_set.insert(name); } } } nodes.insert(nodes.end(), node_set.begin(), node_set.end()); return true; } #if defined(__APPLE__) boost::mutex g_xmlrpc_call_mutex; #endif bool execute(const std::string& method, const XmlRpc::XmlRpcValue& request, XmlRpc::XmlRpcValue& response, XmlRpc::XmlRpcValue& payload, bool wait_for_master) { ros::WallTime start_time = ros::WallTime::now(); std::string master_host = getHost(); uint32_t master_port = getPort(); XmlRpc::XmlRpcClient *c = XMLRPCManager::instance()->getXMLRPCClient(master_host, master_port, "/"); bool printed = false; bool slept = false; bool ok = true; do { bool b = false; { #if defined(__APPLE__) boost::mutex::scoped_lock lock(g_xmlrpc_call_mutex); #endif b = c->execute(method.c_str(), request, response); } ok = !ros::isShuttingDown() && !XMLRPCManager::instance()->isShuttingDown(); if (!b && ok) { if (!printed && wait_for_master) { ROS_ERROR("[%s] Failed to contact master at [%s:%d]. %s", method.c_str(), master_host.c_str(), master_port, wait_for_master ? "Retrying..." : ""); printed = true; } if (!wait_for_master) { XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } if (g_retry_timeout.isZero()) { boost::system_time current_time = boost::get_system_time(); if (g_retry_timeout > ros::WallDuration(0) && (ros::WallTime::now() - start_time) >= g_retry_timeout) { ROS_ERROR("[%s] Timed out trying to connect to the master after [%f] seconds", method.c_str(), g_retry_timeout.toSec()); XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } } ros::WallDuration(0.05).sleep(); slept = true; } else { if (!XMLRPCManager::instance()->validateXmlrpcResponse(method, response, payload) && ok) { XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } break; } ok = !ros::isShuttingDown() && !XMLRPCManager::instance()->isShuttingDown(); } while(ok); if (ok && slept) { ROS_INFO("Connected to master at [%s:%d]", master_host.c_str(), master_port); } XMLRPCManager::instance()->releaseXMLRPCClient(c); return true; } } // namespace master } // namespace ros <commit_msg>Remove unused variable<commit_after>/* * Copyright (C) 2009, Willow Garage, Inc. * * 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 names 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. */ #include "ros/master.h" #include "ros/xmlrpc_manager.h" #include "ros/this_node.h" #include "ros/init.h" #include "ros/network.h" #include <ros/console.h> #include <ros/assert.h> #include "XmlRpc.h" namespace ros { namespace master { uint32_t g_port = 0; std::string g_host; std::string g_uri; ros::WallDuration g_retry_timeout; void init(const M_string& remappings) { M_string::const_iterator it = remappings.find("__master"); if (it != remappings.end()) { g_uri = it->second; } if (g_uri.empty()) { char *master_uri_env = getenv("ROS_MASTER_URI"); if (!master_uri_env) { ROS_FATAL( "ROS_MASTER_URI is not defined in the environment. Either " \ "type the following or (preferrably) add this to your " \ "~/.bashrc file in order set up your " \ "local machine as a ROS master:\n\n" \ "export ROS_MASTER_URI=http://localhost:11311\n\n" \ "then, type 'roscore' in another shell to actually launch " \ "the master program."); ROS_BREAK(); } g_uri = master_uri_env; } // Split URI into if (!network::splitURI(g_uri, g_host, g_port)) { ROS_FATAL( "Couldn't parse the master URI [%s] into a host:port pair.", g_uri.c_str()); ROS_BREAK(); } } const std::string& getHost() { return g_host; } uint32_t getPort() { return g_port; } const std::string& getURI() { return g_uri; } void setRetryTimeout(ros::WallDuration timeout) { g_retry_timeout = timeout; } bool check() { XmlRpc::XmlRpcValue args, result, payload; args[0] = this_node::getName(); return execute("getPid", args, result, payload, false); } bool getTopics(V_TopicInfo& topics) { XmlRpc::XmlRpcValue args, result, payload; args[0] = this_node::getName(); args[1] = ""; //TODO: Fix this if (!execute("getPublishedTopics", args, result, payload, true)) { return false; } topics.clear(); for (int i = 0; i < payload.size(); i++) { topics.push_back(TopicInfo(std::string(payload[i][0]), std::string(payload[i][1]), std::string(payload[i][1]))); } return true; } bool getNodes(V_string& nodes) { XmlRpc::XmlRpcValue args, result, payload; args[0] = this_node::getName(); if (!execute("getSystemState", args, result, payload, true)) { return false; } S_string node_set; for (int i = 0; i < payload.size(); ++i) { for (int j = 0; j < payload[i].size(); ++j) { XmlRpc::XmlRpcValue val = payload[i][j][1]; for (int k = 0; k < val.size(); ++k) { std::string name = payload[i][j][1][k]; node_set.insert(name); } } } nodes.insert(nodes.end(), node_set.begin(), node_set.end()); return true; } #if defined(__APPLE__) boost::mutex g_xmlrpc_call_mutex; #endif bool execute(const std::string& method, const XmlRpc::XmlRpcValue& request, XmlRpc::XmlRpcValue& response, XmlRpc::XmlRpcValue& payload, bool wait_for_master) { ros::WallTime start_time = ros::WallTime::now(); std::string master_host = getHost(); uint32_t master_port = getPort(); XmlRpc::XmlRpcClient *c = XMLRPCManager::instance()->getXMLRPCClient(master_host, master_port, "/"); bool printed = false; bool slept = false; bool ok = true; do { bool b = false; { #if defined(__APPLE__) boost::mutex::scoped_lock lock(g_xmlrpc_call_mutex); #endif b = c->execute(method.c_str(), request, response); } ok = !ros::isShuttingDown() && !XMLRPCManager::instance()->isShuttingDown(); if (!b && ok) { if (!printed && wait_for_master) { ROS_ERROR("[%s] Failed to contact master at [%s:%d]. %s", method.c_str(), master_host.c_str(), master_port, wait_for_master ? "Retrying..." : ""); printed = true; } if (!wait_for_master) { XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } if (g_retry_timeout.isZero()) { if (g_retry_timeout > ros::WallDuration(0) && (ros::WallTime::now() - start_time) >= g_retry_timeout) { ROS_ERROR("[%s] Timed out trying to connect to the master after [%f] seconds", method.c_str(), g_retry_timeout.toSec()); XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } } ros::WallDuration(0.05).sleep(); slept = true; } else { if (!XMLRPCManager::instance()->validateXmlrpcResponse(method, response, payload) && ok) { XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } break; } ok = !ros::isShuttingDown() && !XMLRPCManager::instance()->isShuttingDown(); } while(ok); if (ok && slept) { ROS_INFO("Connected to master at [%s:%d]", master_host.c_str(), master_port); } XMLRPCManager::instance()->releaseXMLRPCClient(c); return true; } } // namespace master } // namespace ros <|endoftext|>
<commit_before>/* * Copyright (C) 2013-2014 Intel Corporation. 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vaapidecoder_base.h" #include "common/log.h" #include "vaapi/vaapisurfaceallocator.h" #include "vaapi/vaapicontext.h" #include "vaapi/vaapidisplay.h" #include "vaapi/VaapiUtils.h" #include "vaapidecsurfacepool.h" #include <string.h> #include <stdlib.h> // for setenv #include <va/va_backend.h> #include <unistd.h> namespace YamiMediaCodec{ typedef VaapiDecoderBase::PicturePtr PicturePtr; inline void unrefAllocator(SurfaceAllocator* allocator) { allocator->unref(allocator); } VaapiDecoderBase::VaapiDecoderBase() : m_VAStarted(false) , m_currentPTS(INVALID_PTS) { INFO("base: construct()"); m_externalDisplay.handle = 0, m_externalDisplay.type = NATIVE_DISPLAY_AUTO, memset(&m_videoFormatInfo, 0, sizeof(VideoFormatInfo)); memset(&m_configBuffer, 0, sizeof(m_configBuffer)); m_configBuffer.fourcc = YAMI_FOURCC_NV12; } VaapiDecoderBase::~VaapiDecoderBase() { INFO("base: deconstruct()"); stop(); } YamiStatus VaapiDecoderBase::createPicture(PicturePtr& picture, int64_t timeStamp /* , VaapiPictureStructure structure = VAAPI_PICTURE_STRUCTURE_FRAME */) { /*accquire one surface from m_surfacePool in base decoder */ SurfacePtr surface = createSurface(); if (!surface) { DEBUG("create surface failed"); return YAMI_DECODE_NO_SURFACE; } picture.reset(new VaapiDecPicture(m_context, surface, timeStamp)); return YAMI_SUCCESS; } YamiStatus VaapiDecoderBase::start(VideoConfigBuffer* buffer) { YamiStatus status; INFO("base: start()"); if (buffer == NULL) { return YAMI_DECODE_INVALID_DATA; } m_configBuffer = *buffer; m_configBuffer.data = NULL; m_configBuffer.size = 0; m_videoFormatInfo.width = buffer->width; m_videoFormatInfo.height = buffer->height; m_videoFormatInfo.surfaceWidth = buffer->surfaceWidth; m_videoFormatInfo.surfaceHeight = buffer->surfaceHeight; m_videoFormatInfo.surfaceNumber = buffer->surfaceNumber; if (!m_configBuffer.fourcc) { /* This just a workaround, user usually memset the VideoConfigBuffer to zero, and we will copy it to m_configBuffer. We need remove fields only for internal user from VideoConfigBuffer i.e., following thing should removed: int32_t surfaceWidth; int32_t surfaceHeight; int32_t frameRate; int32_t surfaceNumber; VAProfile profile; uint32_t flag; uint32_t fourcc; */ m_videoFormatInfo.fourcc = m_configBuffer.fourcc = YAMI_FOURCC_NV12; } else { m_videoFormatInfo.fourcc = m_configBuffer.fourcc; } status = setupVA(buffer->surfaceNumber, buffer->profile); if (status != YAMI_SUCCESS) return status; DEBUG ("m_videoFormatInfo video size: %d x %d, m_videoFormatInfo surface size: %d x %d", m_videoFormatInfo.width, m_videoFormatInfo.height, m_videoFormatInfo.surfaceWidth, m_videoFormatInfo.surfaceHeight); #ifdef __ENABLE_DEBUG__ renderPictureCount = 0; if (access("/tmp/yami", F_OK) == 0) { m_dumpSurface = true; } else { m_dumpSurface = false; } DEBUG("m_dumpSurface: %d", m_dumpSurface); #endif return YAMI_SUCCESS; } YamiStatus VaapiDecoderBase::reset(VideoConfigBuffer* buffer) { YamiStatus status; INFO("base: reset()"); if (buffer == NULL) { return YAMI_DECODE_INVALID_DATA; } flush(); status = terminateVA(); if (status != YAMI_SUCCESS) return status; status = start(buffer); if (status != YAMI_SUCCESS) return status; return YAMI_SUCCESS; } void VaapiDecoderBase::stop(void) { INFO("base: stop()"); terminateVA(); m_currentPTS = INVALID_PTS; m_videoFormatInfo.valid = false; } void VaapiDecoderBase::flush(void) { INFO("base: flush()"); if (m_surfacePool) { m_surfacePool->flush(); } m_currentPTS = INVALID_PTS; } SharedPtr<VideoFrame> VaapiDecoderBase::getOutput() { SharedPtr<VideoFrame> frame; DecSurfacePoolPtr& pool = m_surfacePool; if (!pool) return frame; return pool->getOutput(); } const VideoFormatInfo *VaapiDecoderBase::getFormatInfo(void) { INFO("base: getFormatInfo()"); if (!m_VAStarted) return NULL; return &m_videoFormatInfo; } YamiStatus VaapiDecoderBase::setupVA(uint32_t numSurface, VAProfile profile) { INFO("base: setup VA"); if (m_VAStarted) { return YAMI_SUCCESS; } if (m_display) { WARNING("VA is partially started."); return YAMI_FAIL; } m_display = VaapiDisplay::create(m_externalDisplay); if (!m_display) { ERROR("failed to create display"); return YAMI_FAIL; } VAConfigAttrib attrib; attrib.type = VAConfigAttribRTFormat; attrib.value = VA_RT_FORMAT_YUV420; ConfigPtr config = VaapiConfig::create(m_display, profile, VAEntrypointVLD,&attrib, 1); if (!config) { ERROR("failed to create config"); return YAMI_FAIL; } if (!m_externalAllocator) { //use internal allocator m_allocator.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator); } else { m_allocator = m_externalAllocator; } m_configBuffer.surfaceNumber = numSurface; m_surfacePool = VaapiDecSurfacePool::create(&m_configBuffer, m_allocator); DEBUG("surface pool is created"); if (!m_surfacePool) return YAMI_FAIL; std::vector<VASurfaceID> surfaces; m_surfacePool->getSurfaceIDs(surfaces); if (surfaces.empty()) return YAMI_FAIL; int size = surfaces.size(); m_context = VaapiContext::create(config, m_videoFormatInfo.width, m_videoFormatInfo.height, 0, &surfaces[0], size); if (!m_context) { ERROR("create context failed"); return YAMI_FAIL; } m_videoFormatInfo.surfaceWidth = m_videoFormatInfo.width; m_videoFormatInfo.surfaceHeight = m_videoFormatInfo.height; m_VAStarted = true; return YAMI_SUCCESS; } bool VaapiDecoderBase::createAllocator() { if (m_allocator) return true; m_display = VaapiDisplay::create(m_externalDisplay); if (!m_display) { ERROR("failed to create display"); return false; } if (!m_externalAllocator) { //use internal allocator m_allocator.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator); } else { m_allocator = m_externalAllocator; } if (!m_allocator) { m_display.reset(); ERROR("failed to create allocator"); return false; } return true; } bool VaapiDecoderBase::isSurfaceGeometryChanged() const { return m_config.width < m_videoFormatInfo.width || m_config.height < m_videoFormatInfo.height || m_config.surfaceNumber != m_videoFormatInfo.surfaceNumber || m_config.fourcc != m_videoFormatInfo.fourcc; } YamiStatus VaapiDecoderBase::ensureSurfacePool() { if (!isSurfaceGeometryChanged()) return YAMI_SUCCESS; VideoFormatInfo& info = m_videoFormatInfo; m_config.width = info.surfaceWidth; m_config.height = info.surfaceHeight; m_config.surfaceNumber = info.surfaceNumber; m_config.fourcc = info.fourcc; if (!createAllocator()) return YAMI_FAIL; m_surfacePool = VaapiDecSurfacePool::create(&m_config, m_allocator); if (!m_surfacePool) return YAMI_FAIL; DEBUG("surface pool is created"); return YAMI_SUCCESS; } YamiStatus VaapiDecoderBase::ensureProfile(VAProfile profile) { YamiStatus status; status = ensureSurfacePool(); if (status != YAMI_SUCCESS) return status; if (!m_display || !m_surfacePool) { ERROR("bug: no display or surface pool"); return YAMI_FAIL; } if (m_config.profile == profile) return YAMI_SUCCESS; m_config.profile = profile; VAConfigAttrib attrib; attrib.type = VAConfigAttribRTFormat; attrib.value = VA_RT_FORMAT_YUV420; ConfigPtr config = VaapiConfig::create(m_display, profile, VAEntrypointVLD, &attrib, 1); if (!config) { ERROR("failed to create config"); return YAMI_FAIL; } std::vector<VASurfaceID> surfaces; m_surfacePool->getSurfaceIDs(surfaces); if (surfaces.empty()) return YAMI_FAIL; int size = surfaces.size(); m_context = VaapiContext::create(config, m_videoFormatInfo.width, m_videoFormatInfo.height, 0, &surfaces[0], size); if (!m_context) { ERROR("create context failed"); return YAMI_FAIL; } return YAMI_SUCCESS; } YamiStatus VaapiDecoderBase::terminateVA(void) { INFO("base: terminate VA"); m_config.resetConfig(); m_surfacePool.reset(); m_allocator.reset(); DEBUG("surface pool is reset"); m_context.reset(); m_display.reset(); m_VAStarted = false; return YAMI_SUCCESS; } void VaapiDecoderBase::setNativeDisplay(NativeDisplay * nativeDisplay) { if (!nativeDisplay || nativeDisplay->type == NATIVE_DISPLAY_AUTO) return; m_externalDisplay = *nativeDisplay; } void VaapiDecoderBase::releaseLock(bool lockable) { if (!m_surfacePool) return; } void VaapiDecoderBase::setAllocator(SurfaceAllocator* allocator) { m_externalAllocator.reset(allocator,unrefAllocator); } SurfacePtr VaapiDecoderBase::createSurface() { SurfacePtr surface; if (m_surfacePool) { surface = m_surfacePool->acquire(); } return surface; } YamiStatus VaapiDecoderBase::outputPicture(const PicturePtr& picture) { //TODO: reorder poc return m_surfacePool->output(picture->getSurface(), picture->m_timeStamp) ? YAMI_SUCCESS : YAMI_FAIL; } VADisplay VaapiDecoderBase::getDisplayID() { if (!m_display) return NULL; return m_display->getID(); } #define CHECK(f) \ do { \ if (m_videoFormatInfo.f != f) { \ m_videoFormatInfo.f = f; \ changed = true; \ } \ } while (0) bool VaapiDecoderBase::setFormat(uint32_t width, uint32_t height, uint32_t surfaceWidth, uint32_t surfaceHeight, uint32_t surfaceNumber, uint32_t fourcc) { bool changed = false; CHECK(width); CHECK(height); CHECK(surfaceWidth); CHECK(surfaceHeight); CHECK(surfaceNumber); CHECK(fourcc); //this not true, but it's only way to let user get format info m_VAStarted = true; return changed; } } //namespace YamiMediaCodec <commit_msg>basedec: we need compare m_videoFormatInfo.surfaceWidth instead width for geometry change<commit_after>/* * Copyright (C) 2013-2014 Intel Corporation. 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vaapidecoder_base.h" #include "common/log.h" #include "vaapi/vaapisurfaceallocator.h" #include "vaapi/vaapicontext.h" #include "vaapi/vaapidisplay.h" #include "vaapi/VaapiUtils.h" #include "vaapidecsurfacepool.h" #include <string.h> #include <stdlib.h> // for setenv #include <va/va_backend.h> #include <unistd.h> namespace YamiMediaCodec{ typedef VaapiDecoderBase::PicturePtr PicturePtr; inline void unrefAllocator(SurfaceAllocator* allocator) { allocator->unref(allocator); } VaapiDecoderBase::VaapiDecoderBase() : m_VAStarted(false) , m_currentPTS(INVALID_PTS) { INFO("base: construct()"); m_externalDisplay.handle = 0, m_externalDisplay.type = NATIVE_DISPLAY_AUTO, memset(&m_videoFormatInfo, 0, sizeof(VideoFormatInfo)); memset(&m_configBuffer, 0, sizeof(m_configBuffer)); m_configBuffer.fourcc = YAMI_FOURCC_NV12; } VaapiDecoderBase::~VaapiDecoderBase() { INFO("base: deconstruct()"); stop(); } YamiStatus VaapiDecoderBase::createPicture(PicturePtr& picture, int64_t timeStamp /* , VaapiPictureStructure structure = VAAPI_PICTURE_STRUCTURE_FRAME */) { /*accquire one surface from m_surfacePool in base decoder */ SurfacePtr surface = createSurface(); if (!surface) { DEBUG("create surface failed"); return YAMI_DECODE_NO_SURFACE; } picture.reset(new VaapiDecPicture(m_context, surface, timeStamp)); return YAMI_SUCCESS; } YamiStatus VaapiDecoderBase::start(VideoConfigBuffer* buffer) { YamiStatus status; INFO("base: start()"); if (buffer == NULL) { return YAMI_DECODE_INVALID_DATA; } m_configBuffer = *buffer; m_configBuffer.data = NULL; m_configBuffer.size = 0; m_videoFormatInfo.width = buffer->width; m_videoFormatInfo.height = buffer->height; m_videoFormatInfo.surfaceWidth = buffer->surfaceWidth; m_videoFormatInfo.surfaceHeight = buffer->surfaceHeight; m_videoFormatInfo.surfaceNumber = buffer->surfaceNumber; if (!m_configBuffer.fourcc) { /* This just a workaround, user usually memset the VideoConfigBuffer to zero, and we will copy it to m_configBuffer. We need remove fields only for internal user from VideoConfigBuffer i.e., following thing should removed: int32_t surfaceWidth; int32_t surfaceHeight; int32_t frameRate; int32_t surfaceNumber; VAProfile profile; uint32_t flag; uint32_t fourcc; */ m_videoFormatInfo.fourcc = m_configBuffer.fourcc = YAMI_FOURCC_NV12; } else { m_videoFormatInfo.fourcc = m_configBuffer.fourcc; } status = setupVA(buffer->surfaceNumber, buffer->profile); if (status != YAMI_SUCCESS) return status; DEBUG ("m_videoFormatInfo video size: %d x %d, m_videoFormatInfo surface size: %d x %d", m_videoFormatInfo.width, m_videoFormatInfo.height, m_videoFormatInfo.surfaceWidth, m_videoFormatInfo.surfaceHeight); #ifdef __ENABLE_DEBUG__ renderPictureCount = 0; if (access("/tmp/yami", F_OK) == 0) { m_dumpSurface = true; } else { m_dumpSurface = false; } DEBUG("m_dumpSurface: %d", m_dumpSurface); #endif return YAMI_SUCCESS; } YamiStatus VaapiDecoderBase::reset(VideoConfigBuffer* buffer) { YamiStatus status; INFO("base: reset()"); if (buffer == NULL) { return YAMI_DECODE_INVALID_DATA; } flush(); status = terminateVA(); if (status != YAMI_SUCCESS) return status; status = start(buffer); if (status != YAMI_SUCCESS) return status; return YAMI_SUCCESS; } void VaapiDecoderBase::stop(void) { INFO("base: stop()"); terminateVA(); m_currentPTS = INVALID_PTS; m_videoFormatInfo.valid = false; } void VaapiDecoderBase::flush(void) { INFO("base: flush()"); if (m_surfacePool) { m_surfacePool->flush(); } m_currentPTS = INVALID_PTS; } SharedPtr<VideoFrame> VaapiDecoderBase::getOutput() { SharedPtr<VideoFrame> frame; DecSurfacePoolPtr& pool = m_surfacePool; if (!pool) return frame; return pool->getOutput(); } const VideoFormatInfo *VaapiDecoderBase::getFormatInfo(void) { INFO("base: getFormatInfo()"); if (!m_VAStarted) return NULL; return &m_videoFormatInfo; } YamiStatus VaapiDecoderBase::setupVA(uint32_t numSurface, VAProfile profile) { INFO("base: setup VA"); if (m_VAStarted) { return YAMI_SUCCESS; } if (m_display) { WARNING("VA is partially started."); return YAMI_FAIL; } m_display = VaapiDisplay::create(m_externalDisplay); if (!m_display) { ERROR("failed to create display"); return YAMI_FAIL; } VAConfigAttrib attrib; attrib.type = VAConfigAttribRTFormat; attrib.value = VA_RT_FORMAT_YUV420; ConfigPtr config = VaapiConfig::create(m_display, profile, VAEntrypointVLD,&attrib, 1); if (!config) { ERROR("failed to create config"); return YAMI_FAIL; } if (!m_externalAllocator) { //use internal allocator m_allocator.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator); } else { m_allocator = m_externalAllocator; } m_configBuffer.surfaceNumber = numSurface; m_surfacePool = VaapiDecSurfacePool::create(&m_configBuffer, m_allocator); DEBUG("surface pool is created"); if (!m_surfacePool) return YAMI_FAIL; std::vector<VASurfaceID> surfaces; m_surfacePool->getSurfaceIDs(surfaces); if (surfaces.empty()) return YAMI_FAIL; int size = surfaces.size(); m_context = VaapiContext::create(config, m_videoFormatInfo.width, m_videoFormatInfo.height, 0, &surfaces[0], size); if (!m_context) { ERROR("create context failed"); return YAMI_FAIL; } m_videoFormatInfo.surfaceWidth = m_videoFormatInfo.width; m_videoFormatInfo.surfaceHeight = m_videoFormatInfo.height; m_VAStarted = true; return YAMI_SUCCESS; } bool VaapiDecoderBase::createAllocator() { if (m_allocator) return true; m_display = VaapiDisplay::create(m_externalDisplay); if (!m_display) { ERROR("failed to create display"); return false; } if (!m_externalAllocator) { //use internal allocator m_allocator.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator); } else { m_allocator = m_externalAllocator; } if (!m_allocator) { m_display.reset(); ERROR("failed to create allocator"); return false; } return true; } bool VaapiDecoderBase::isSurfaceGeometryChanged() const { return m_config.width < m_videoFormatInfo.surfaceWidth || m_config.height < m_videoFormatInfo.surfaceHeight || m_config.surfaceNumber != m_videoFormatInfo.surfaceNumber || m_config.fourcc != m_videoFormatInfo.fourcc; } YamiStatus VaapiDecoderBase::ensureSurfacePool() { if (!isSurfaceGeometryChanged()) return YAMI_SUCCESS; VideoFormatInfo& info = m_videoFormatInfo; m_config.width = info.surfaceWidth; m_config.height = info.surfaceHeight; m_config.surfaceNumber = info.surfaceNumber; m_config.fourcc = info.fourcc; if (!createAllocator()) return YAMI_FAIL; m_surfacePool = VaapiDecSurfacePool::create(&m_config, m_allocator); if (!m_surfacePool) return YAMI_FAIL; DEBUG("surface pool is created"); return YAMI_SUCCESS; } YamiStatus VaapiDecoderBase::ensureProfile(VAProfile profile) { YamiStatus status; status = ensureSurfacePool(); if (status != YAMI_SUCCESS) return status; if (!m_display || !m_surfacePool) { ERROR("bug: no display or surface pool"); return YAMI_FAIL; } if (m_config.profile == profile) return YAMI_SUCCESS; m_config.profile = profile; VAConfigAttrib attrib; attrib.type = VAConfigAttribRTFormat; attrib.value = VA_RT_FORMAT_YUV420; ConfigPtr config = VaapiConfig::create(m_display, profile, VAEntrypointVLD, &attrib, 1); if (!config) { ERROR("failed to create config"); return YAMI_FAIL; } std::vector<VASurfaceID> surfaces; m_surfacePool->getSurfaceIDs(surfaces); if (surfaces.empty()) return YAMI_FAIL; int size = surfaces.size(); m_context = VaapiContext::create(config, m_videoFormatInfo.width, m_videoFormatInfo.height, 0, &surfaces[0], size); if (!m_context) { ERROR("create context failed"); return YAMI_FAIL; } return YAMI_SUCCESS; } YamiStatus VaapiDecoderBase::terminateVA(void) { INFO("base: terminate VA"); m_config.resetConfig(); m_surfacePool.reset(); m_allocator.reset(); DEBUG("surface pool is reset"); m_context.reset(); m_display.reset(); m_VAStarted = false; return YAMI_SUCCESS; } void VaapiDecoderBase::setNativeDisplay(NativeDisplay * nativeDisplay) { if (!nativeDisplay || nativeDisplay->type == NATIVE_DISPLAY_AUTO) return; m_externalDisplay = *nativeDisplay; } void VaapiDecoderBase::releaseLock(bool lockable) { if (!m_surfacePool) return; } void VaapiDecoderBase::setAllocator(SurfaceAllocator* allocator) { m_externalAllocator.reset(allocator,unrefAllocator); } SurfacePtr VaapiDecoderBase::createSurface() { SurfacePtr surface; if (m_surfacePool) { surface = m_surfacePool->acquire(); } return surface; } YamiStatus VaapiDecoderBase::outputPicture(const PicturePtr& picture) { //TODO: reorder poc return m_surfacePool->output(picture->getSurface(), picture->m_timeStamp) ? YAMI_SUCCESS : YAMI_FAIL; } VADisplay VaapiDecoderBase::getDisplayID() { if (!m_display) return NULL; return m_display->getID(); } #define CHECK(f) \ do { \ if (m_videoFormatInfo.f != f) { \ m_videoFormatInfo.f = f; \ changed = true; \ } \ } while (0) bool VaapiDecoderBase::setFormat(uint32_t width, uint32_t height, uint32_t surfaceWidth, uint32_t surfaceHeight, uint32_t surfaceNumber, uint32_t fourcc) { bool changed = false; CHECK(width); CHECK(height); CHECK(surfaceWidth); CHECK(surfaceHeight); CHECK(surfaceNumber); CHECK(fourcc); //this not true, but it's only way to let user get format info m_VAStarted = true; return changed; } } //namespace YamiMediaCodec <|endoftext|>
<commit_before> #include <vector> #include <algorithm> #include <iostream> #include "MutableHeap.hpp" #include <boost/test/unit_test.hpp> #include "boost_helpers.hpp" // template< typename T > // class MutablePriorityQueue // { // }; BOOST_AUTO_TEST_SUITE( MutableHeap_tests ); // BOOST_AUTO_TEST_CASE( Hello ) // { // std::vector< int > v; // v.push_back( 4 ); // v.push_back( 1 ); // v.push_back( 7 ); // v.push_back( 3 ); // v.push_back( 2 ); // int n = 0; // std::cout << "[ "; // for( std::vector< int >::iterator i = v.begin(); i != v.end(); ++i, ++n ) { std::cout << n << ":" << *i << " "; } // std::cout << "]" << std::endl; // softxmt::make_heap( v.begin(), v.end() ); // n = 0; // std::cout << "[ "; // for( std::vector< int >::iterator i = v.begin(); i != v.end(); ++i, ++n ) { std::cout << n << ":" << *i << " "; } // std::cout << "]" << std::endl; // v.push_back( 44 ); softxmt::push_heap( v.begin(), v.end() ); // n = 0; // std::cout << "[ "; // for( std::vector< int >::iterator i = v.begin(); i != v.end(); ++i, ++n ) { std::cout << n << ":" << *i << " "; } // std::cout << "]" << std::endl; // n = 0; // std::cout << "[ "; // for( std::vector< int >::iterator i = v.begin(); i != v.end(); ++i, ++n ) { std::cout << n << ":" << *i << " "; } // std::cout << "]" << std::endl; // } BOOST_AUTO_TEST_CASE( MyHeap1 ) { MutableHeap<int,int> mh; mh.insert( 2345, 4 ); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap2 ) { MutableHeap<int,int> mh; mh.insert( 2345, 4 ); mh.insert( 1234, 1 ); mh.dump(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap3 ) { MutableHeap<int,int> mh; mh.insert( 2345, 1 ); mh.insert( 1234, 4 ); mh.dump(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap4 ) { MutableHeap<int,int> mh; mh.insert( 2345, 4 ); mh.insert( 1234, 1 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_MESSAGE( "Removing top" ); mh.remove(); mh.dump(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap123 ) { MutableHeap<int,int> mh; mh.insert( 1, 1 ); mh.insert( 2, 2 ); mh.insert( 3, 3 ); BOOST_CHECK( mh.check() ); mh.dump(); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap132 ) { MutableHeap<int,int> mh; mh.insert( 1, 1 ); mh.insert( 3, 3 ); mh.insert( 2, 2 ); BOOST_CHECK( mh.check() ); mh.dump(); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap231 ) { MutableHeap<int,int> mh; mh.insert( 2, 2 ); mh.insert( 3, 3 ); mh.insert( 1, 1 ); BOOST_CHECK( mh.check() ); mh.dump(); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap213 ) { MutableHeap<int,int> mh; mh.insert( 2, 2 ); mh.insert( 1, 1 ); mh.insert( 3, 3 ); BOOST_CHECK( mh.check() ); mh.dump(); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap321 ) { MutableHeap<int,int> mh; mh.insert( 3, 3 ); mh.insert( 2, 2 ); mh.insert( 1, 1 ); BOOST_CHECK( mh.check() ); mh.dump(); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap312 ) { MutableHeap<int,int> mh; mh.insert( 3, 3 ); mh.insert( 1, 1 ); mh.insert( 2, 2 ); BOOST_CHECK( mh.check() ); mh.dump(); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeapX ) { MutableHeap<int,int> mh; mh.insert( 2345, 4 ); mh.insert( 1234, 1 ); mh.insert( 3456, 7 ); mh.insert( 4567, 2 ); mh.insert( 5678, 3 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 7 ); BOOST_MESSAGE( "Removing top key" ); mh.remove(); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 4 ); } BOOST_AUTO_TEST_CASE( MyHeapRemAddRem ) { MutableHeap<int,int> mh; mh.insert( 2345, 5 ); mh.insert( 1234, 1 ); mh.insert( 3456, 7 ); mh.insert( 4567, 2 ); mh.insert( 5678, 3 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 7 ); BOOST_MESSAGE( "Removing top" ); mh.remove(); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); mh.insert( 4444, 4 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); BOOST_MESSAGE( "Removing top" ); mh.remove(); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 4 ); } BOOST_AUTO_TEST_CASE( MyHeapUpdate ) { MutableHeap<int,int> mh; mh.insert( 2345, 5 ); mh.insert( 1234, 1 ); mh.insert( 3456, 7 ); mh.insert( 4567, 2 ); mh.insert( 5678, 3 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 7 ); BOOST_MESSAGE("Increasing 4567 to 8"); mh.increase( 4567, 8 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 8 ); BOOST_MESSAGE("Updating 3456 to 4"); mh.update( 3456, 4 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 8 ); } BOOST_AUTO_TEST_CASE( MyHeapIdent ) { MutableHeap<int,int> mh; mh.insert( 2345, 5 ); mh.insert( 1234, 5 ); mh.insert( 3456, 5 ); mh.insert( 4567, 5 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); BOOST_CHECK_EQUAL( mh.top_key(), 4567 ); BOOST_MESSAGE("Updating 1234 to 4"); mh.update( 1234, 4 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); } BOOST_AUTO_TEST_CASE( MyHeapRemoveTop ) { MutableHeap<int,int> mh; mh.insert( 4567, 4 ); mh.insert( 1234, 1 ); mh.insert( 2345, 2 ); mh.insert( 5678, 5 ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); BOOST_CHECK_EQUAL( mh.top_priority(), 5 ); int top_key = mh.top_key(); BOOST_CHECK_EQUAL( top_key, 5678 ); BOOST_MESSAGE("Removing " << top_key); mh.remove_key( top_key ); mh.dump(); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 4 ); BOOST_CHECK_EQUAL( mh.top_priority(), 4 ); BOOST_CHECK_EQUAL( mh.top_key(), 4567 ); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Update MutableHeap tests to match MutableHeap modifications a while ago<commit_after> #include <vector> #include <algorithm> #include <iostream> #include "MutableHeap.hpp" #include <boost/test/unit_test.hpp> #include "boost_helpers.hpp" // template< typename T > // class MutablePriorityQueue // { // }; BOOST_AUTO_TEST_SUITE( MutableHeap_tests ); // BOOST_AUTO_TEST_CASE( Hello ) // { // std::vector< int > v; // v.push_back( 4 ); // v.push_back( 1 ); // v.push_back( 7 ); // v.push_back( 3 ); // v.push_back( 2 ); // int n = 0; // std::cout << "[ "; // for( std::vector< int >::iterator i = v.begin(); i != v.end(); ++i, ++n ) { std::cout << n << ":" << *i << " "; } // std::cout << "]" << std::endl; // softxmt::make_heap( v.begin(), v.end() ); // n = 0; // std::cout << "[ "; // for( std::vector< int >::iterator i = v.begin(); i != v.end(); ++i, ++n ) { std::cout << n << ":" << *i << " "; } // std::cout << "]" << std::endl; // v.push_back( 44 ); softxmt::push_heap( v.begin(), v.end() ); // n = 0; // std::cout << "[ "; // for( std::vector< int >::iterator i = v.begin(); i != v.end(); ++i, ++n ) { std::cout << n << ":" << *i << " "; } // std::cout << "]" << std::endl; // n = 0; // std::cout << "[ "; // for( std::vector< int >::iterator i = v.begin(); i != v.end(); ++i, ++n ) { std::cout << n << ":" << *i << " "; } // std::cout << "]" << std::endl; // } BOOST_AUTO_TEST_CASE( MyHeap1 ) { MutableHeap<int,int> mh; mh.insert( 2345, 4 ); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap2 ) { MutableHeap<int,int> mh; mh.insert( 2345, 4 ); mh.insert( 1234, 1 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap3 ) { MutableHeap<int,int> mh; mh.insert( 2345, 1 ); mh.insert( 1234, 4 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap4 ) { MutableHeap<int,int> mh; mh.insert( 2345, 4 ); mh.insert( 1234, 1 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_MESSAGE( "Removing top" ); mh.remove(); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap123 ) { MutableHeap<int,int> mh; mh.insert( 1, 1 ); mh.insert( 2, 2 ); mh.insert( 3, 3 ); BOOST_CHECK( mh.check() ); mh.dump( std::cout ); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap132 ) { MutableHeap<int,int> mh; mh.insert( 1, 1 ); mh.insert( 3, 3 ); mh.insert( 2, 2 ); BOOST_CHECK( mh.check() ); mh.dump( std::cout ); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap231 ) { MutableHeap<int,int> mh; mh.insert( 2, 2 ); mh.insert( 3, 3 ); mh.insert( 1, 1 ); BOOST_CHECK( mh.check() ); mh.dump( std::cout ); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap213 ) { MutableHeap<int,int> mh; mh.insert( 2, 2 ); mh.insert( 1, 1 ); mh.insert( 3, 3 ); BOOST_CHECK( mh.check() ); mh.dump( std::cout ); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap321 ) { MutableHeap<int,int> mh; mh.insert( 3, 3 ); mh.insert( 2, 2 ); mh.insert( 1, 1 ); BOOST_CHECK( mh.check() ); mh.dump( std::cout ); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeap312 ) { MutableHeap<int,int> mh; mh.insert( 3, 3 ); mh.insert( 1, 1 ); mh.insert( 2, 2 ); BOOST_CHECK( mh.check() ); mh.dump( std::cout ); BOOST_MESSAGE( "Removing top" ); mh.remove(); BOOST_CHECK( mh.check() ); } BOOST_AUTO_TEST_CASE( MyHeapX ) { MutableHeap<int,int> mh; mh.insert( 2345, 4 ); mh.insert( 1234, 1 ); mh.insert( 3456, 7 ); mh.insert( 4567, 2 ); mh.insert( 5678, 3 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 7 ); BOOST_MESSAGE( "Removing top key" ); mh.remove(); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 4 ); } BOOST_AUTO_TEST_CASE( MyHeapRemAddRem ) { MutableHeap<int,int> mh; mh.insert( 2345, 5 ); mh.insert( 1234, 1 ); mh.insert( 3456, 7 ); mh.insert( 4567, 2 ); mh.insert( 5678, 3 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 7 ); BOOST_MESSAGE( "Removing top" ); mh.remove(); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); mh.insert( 4444, 4 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); BOOST_MESSAGE( "Removing top" ); mh.remove(); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 4 ); } BOOST_AUTO_TEST_CASE( MyHeapUpdate ) { MutableHeap<int,int> mh; mh.insert( 2345, 5 ); mh.insert( 1234, 1 ); mh.insert( 3456, 7 ); mh.insert( 4567, 2 ); mh.insert( 5678, 3 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 7 ); BOOST_MESSAGE("Increasing 4567 to 8"); mh.increase( 4567, 8 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 8 ); BOOST_MESSAGE("Updating 3456 to 4"); mh.update( 3456, 4 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 8 ); } BOOST_AUTO_TEST_CASE( MyHeapIdent ) { MutableHeap<int,int> mh; mh.insert( 2345, 5 ); mh.insert( 1234, 5 ); mh.insert( 3456, 5 ); mh.insert( 4567, 5 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); BOOST_CHECK_EQUAL( mh.top_key(), 4567 ); BOOST_MESSAGE("Updating 1234 to 4"); mh.update( 1234, 4 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); } BOOST_AUTO_TEST_CASE( MyHeapRemoveTop ) { MutableHeap<int,int> mh; mh.insert( 4567, 4 ); mh.insert( 1234, 1 ); mh.insert( 2345, 2 ); mh.insert( 5678, 5 ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 5 ); BOOST_CHECK_EQUAL( mh.top_priority(), 5 ); int top_key = mh.top_key(); BOOST_CHECK_EQUAL( top_key, 5678 ); BOOST_MESSAGE("Removing " << top_key); mh.remove_key( top_key ); mh.dump( std::cout ); BOOST_CHECK( mh.check() ); BOOST_CHECK_EQUAL( mh.top(), 4 ); BOOST_CHECK_EQUAL( mh.top_priority(), 4 ); BOOST_CHECK_EQUAL( mh.top_key(), 4567 ); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>// Virtual memory allocator for CPU/GPU #if defined(CUDA_FOUND) #include "cuda_utils.h" #endif #include "tlang_util.h" #include <taichi/unified_allocator.h> #include <taichi/system/virtual_memory.h> #include <string> TLANG_NAMESPACE_BEGIN UnifiedAllocator *allocator_instance = nullptr; UnifiedAllocator *&allocator() { return allocator_instance; } taichi::Tlang::UnifiedAllocator::UnifiedAllocator(std::size_t size, bool gpu) : size(size), gpu(gpu) { size += 4096; if (gpu) { #if defined(CUDA_FOUND) check_cuda_errors(cudaMallocManaged(&_cuda_data, size + 4096)); if (_cuda_data == nullptr) { TC_ERROR("GPU memory allocation failed."); } check_cuda_errors(cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetPreferredLocation, 0)); // http://on-demand.gputechconf.com/gtc/2017/presentation/s7285-nikolay-sakharnykh-unified-memory-on-pascal-and-volta.pdf /* cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetReadMostly, cudaCpuDeviceId); cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetAccessedBy, 0); */ data = _cuda_data; #else TC_NOT_IMPLEMENTED #endif } else { cpu_vm = std::make_unique<VirtualMemoryAllocator>(size); data = cpu_vm->ptr; } TC_ASSERT(data != nullptr); auto p = reinterpret_cast<uint64>(data); data = (void *)(p + (4096 - p % 4096)); // allocate head/tail ptrs on unified memory head = (void **)data; tail = (void **)((char *)data + sizeof(void *)); data = (char *)data + 4096; *head = data; *tail = (void *)(((char *)head) + size); } taichi::Tlang::UnifiedAllocator::~UnifiedAllocator() { if (!initialized()) { return; } if (gpu) { #if defined(CUDA_FOUND) check_cuda_errors(cudaFree(_cuda_data)); #else TC_ERROR("No CUDA support"); #endif } } void taichi::Tlang::UnifiedAllocator::create(bool gpu) { TC_ASSERT(allocator() == nullptr); void *dst; if (gpu) { #if defined(CUDA_FOUND) gpu = true; check_cuda_errors(cudaMallocManaged(&dst, sizeof(UnifiedAllocator))); #else TC_NOT_IMPLEMENTED #endif } else { dst = std::malloc(sizeof(UnifiedAllocator)); } #if !defined(TC_PLATFORM_WINDOWS) allocator() = new (dst) UnifiedAllocator(1LL << 44, gpu); #else std::size_t phys_mem_size; GetPhysicallyInstalledSystemMemory(&phys_mem_size); // KB phys_mem_size /= 1024; // MB TC_INFO("Physical memory size size {} MB", phys_mem_size); auto virtual_mem_to_allocate = (phys_mem_size << 20) / 4; TC_INFO("Allocating virtual memory pool (size = {} MB)", virtual_mem_to_allocate / 1024 / 1024); allocator() = new (dst) UnifiedAllocator(virtual_mem_to_allocate, gpu); #endif } void taichi::Tlang::UnifiedAllocator::free() { (*allocator()).~UnifiedAllocator(); if (allocator()->gpu) { #if defined(CUDA_FOUND) check_cuda_errors(cudaFree(allocator())); #else TC_NOT_IMPLEMENTED #endif } else { std::free(allocator()); } allocator() = nullptr; } void taichi::Tlang::UnifiedAllocator::memset(unsigned char val) { std::memset(data, val, size); } UnifiedAllocator::UnifiedAllocator() { data = nullptr; gpu_error_code = 0; } TLANG_NAMESPACE_END extern "C" void *taichi_allocate_aligned(std::size_t size, int alignment) { return taichi::Tlang::allocate(size, alignment); } <commit_msg>fixed unified_allocator message typo<commit_after>// Virtual memory allocator for CPU/GPU #if defined(CUDA_FOUND) #include "cuda_utils.h" #endif #include "tlang_util.h" #include <taichi/unified_allocator.h> #include <taichi/system/virtual_memory.h> #include <string> TLANG_NAMESPACE_BEGIN UnifiedAllocator *allocator_instance = nullptr; UnifiedAllocator *&allocator() { return allocator_instance; } taichi::Tlang::UnifiedAllocator::UnifiedAllocator(std::size_t size, bool gpu) : size(size), gpu(gpu) { size += 4096; if (gpu) { #if defined(CUDA_FOUND) check_cuda_errors(cudaMallocManaged(&_cuda_data, size + 4096)); if (_cuda_data == nullptr) { TC_ERROR("GPU memory allocation failed."); } check_cuda_errors(cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetPreferredLocation, 0)); // http://on-demand.gputechconf.com/gtc/2017/presentation/s7285-nikolay-sakharnykh-unified-memory-on-pascal-and-volta.pdf /* cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetReadMostly, cudaCpuDeviceId); cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetAccessedBy, 0); */ data = _cuda_data; #else TC_NOT_IMPLEMENTED #endif } else { cpu_vm = std::make_unique<VirtualMemoryAllocator>(size); data = cpu_vm->ptr; } TC_ASSERT(data != nullptr); auto p = reinterpret_cast<uint64>(data); data = (void *)(p + (4096 - p % 4096)); // allocate head/tail ptrs on unified memory head = (void **)data; tail = (void **)((char *)data + sizeof(void *)); data = (char *)data + 4096; *head = data; *tail = (void *)(((char *)head) + size); } taichi::Tlang::UnifiedAllocator::~UnifiedAllocator() { if (!initialized()) { return; } if (gpu) { #if defined(CUDA_FOUND) check_cuda_errors(cudaFree(_cuda_data)); #else TC_ERROR("No CUDA support"); #endif } } void taichi::Tlang::UnifiedAllocator::create(bool gpu) { TC_ASSERT(allocator() == nullptr); void *dst; if (gpu) { #if defined(CUDA_FOUND) gpu = true; check_cuda_errors(cudaMallocManaged(&dst, sizeof(UnifiedAllocator))); #else TC_NOT_IMPLEMENTED #endif } else { dst = std::malloc(sizeof(UnifiedAllocator)); } #if !defined(TC_PLATFORM_WINDOWS) allocator() = new (dst) UnifiedAllocator(1LL << 44, gpu); #else std::size_t phys_mem_size; GetPhysicallyInstalledSystemMemory(&phys_mem_size); // KB phys_mem_size /= 1024; // MB TC_INFO("Physical memory size {} MB", phys_mem_size); auto virtual_mem_to_allocate = (phys_mem_size << 20) / 4; TC_INFO("Allocating virtual memory pool (size = {} MB)", virtual_mem_to_allocate / 1024 / 1024); allocator() = new (dst) UnifiedAllocator(virtual_mem_to_allocate, gpu); #endif } void taichi::Tlang::UnifiedAllocator::free() { (*allocator()).~UnifiedAllocator(); if (allocator()->gpu) { #if defined(CUDA_FOUND) check_cuda_errors(cudaFree(allocator())); #else TC_NOT_IMPLEMENTED #endif } else { std::free(allocator()); } allocator() = nullptr; } void taichi::Tlang::UnifiedAllocator::memset(unsigned char val) { std::memset(data, val, size); } UnifiedAllocator::UnifiedAllocator() { data = nullptr; gpu_error_code = 0; } TLANG_NAMESPACE_END extern "C" void *taichi_allocate_aligned(std::size_t size, int alignment) { return taichi::Tlang::allocate(size, alignment); } <|endoftext|>
<commit_before>//NIM dabs oktber 1997 #include <iostream> #include <conio.h> #include <stdlib.h> using namespace std; //etta fall a birta stu allra eldsptnahrgna (hrgur fleirtlu eignarfalli) void birta( int* hruga ); //etta fall a reikna t hversu margar eldsptur eru eftir hrgunum: int samtals( int* hruga ); //etta fall ltur tlvuna gera: void tolva( int* hruga ); //etta fall ltur notandann gera: void notandi( int* hruga ); //etta fall birtir reglurnar spilinu: void hjalp( ); //etta fall spilar spili: void spila( ); //g leyfi mr a nota eina vvra breytu af v a forriti notar alltaf //mismargar hrgur hvert og eitt skipti: int hrugufjoldi; //Hr byrjar aalforriti: void main( ) { int val; do { cout << endl << endl << endl; cout << " ADALVALMYND " << endl << endl; cout << " 1. Spila NIM" << endl; cout << " 2. Birta reglurnar i NIM" << endl; cout << " 3. Haetta " << endl << endl; cout << " Veldu 1, 2 eda 3:" << endl << endl; cin >> val; switch ( val ) { case 1: spila( ); break; case 2: hjalp( ); break; case 3: break; } } while ( val != 3 ); } void spila( ) { int hruga[ 10 ]; cout << "*-------------------------------------------------------*" << endl; cout << " NU SPILUM VID NIM!!" << endl; cout << "*-------------------------------------------------------*" << endl; cout << endl << endl; cout << "Veljum med hve margar hrugur vid spilum. " << endl; cout << "Yttu a einhvern lykil: " << endl; while( !kbhit( ) ) { rand( ); } hrugufjoldi = ( (rand( ) % 8 ) + 2 ); cout << "Vid spilum med " << hrugufjoldi << " hrugur. " << endl; for ( int i = 0; i < hrugufjoldi; i++ ) { hruga[ i ]=( ( rand( ) % 14 ) + 1 ); } cout << endl; birta ( hruga ); do { notandi( hruga ); birta( hruga ); tolva( hruga ); birta( hruga ); } while ( samtals( hruga ) ); } void hjalp( ) { cout << " UM NIM - LEIKINN " << endl << endl; cout << "Leikurinn NIM er upprunninn fra Asiu thar sem hann var" << endl; cout << "leikinn med steinvolum. Reglurnar eru thessar: " << endl; cout << "Keppendur setja einhvern fjolda af eldspytum i hrugur " << endl; cout << "(their akveda sjalfir hve margar hrugur og hve margar " << endl; cout << "eldspytur i hverri hrugu) og skiptast svo a um ad " << endl; cout << "draga eldspytur ur einhverri hrugunni. Their mega " << endl; cout << "taka eina eldspytu, nokkrar eda allar ur einni " << endl; cout << "hrugunni en their mega aldrei taka ur fleiri en " << endl; cout << "einni hrugu i einu. Sa sem tekur sidustu eldspytuna " << endl; cout << "ur sidustu hrugunni vinnur. Gangi ykkur vel! " << endl << endl; cout << "Sladu a einhvern lykil... " << endl; getch( ); } void birta( int* hruga ) { if( !samtals( hruga ) ) { return; } cout << " Hruga nr.: "; for (int i = 0; i < hrugufjoldi; i++ ) { cout << " " << (i + 1) << " "; } cout << endl << endl; cout << "Fjoldi eldspytna i hverri hrugu er: "; for ( int c = 0; c < hrugufjoldi; c++ ) { if( hruga[c] < 10 ) { cout << " " << hruga[ c ] << " "; } else { cout << hruga[ c ] << " "; } } cout << endl << endl; } void notandi( int* hruga ) { if ( samtals( hruga ) == 0 ) { return; } int eldspytur; int hrugunumer; do { cout << "Sladu inn hve margar eldspytur thu vilt taka: "; cin >> eldspytur; cout << endl; if( eldspytur < 1 ) { cout << "Thu verdur ad taka a.m.k. eina eldspytu. Veldu aftur. " << endl << endl; continue; } cout << "Sladu inn ur hvada hrugu: "; cin >> hrugunumer; if( hrugunumer > hrugufjoldi ) { cout << "Thad er engin hruga med thessu numeri. Veldu aftur." <<endl<<endl; continue; } if( eldspytur > hruga[ (hrugunumer) - 1 ] ) { cout <<"Thad eru ekki nogu margar eldspytur eftir i hrugunni. Veldu aftur."<<endl<<endl; continue; } } while ( eldspytur > hruga[ (hrugunumer) - 1 ] || eldspytur < 1 ); hruga[ hrugunumer - 1 ] -= eldspytur; if( !samtals( hruga ) ) { cout << endl << "Thu vannst. Til hamingju!" << endl << endl; cout << "Sladu a einhvern lykil... " << endl; getch( ); } cout << endl; } void tolva( int* hruga ) { if( samtals( hruga ) == 0 ) { return; } int eldspytur; int hrugunumer; do { eldspytur = ( ( rand( ) % 14 ) + 1 ); hrugunumer = ( ( rand( ) % hrugufjoldi ) + 1 ); if( eldspytur > hruga[(hrugunumer)-1] ) { continue; } } while ( eldspytur > hruga[ (hrugunumer) - 1 ] ); if ( eldspytur > 1 ) { cout << " Eg tek " << eldspytur << " eldspytur ur hrugu nr. "; } else { cout << " Eg tek " << eldspytur << " eldspytu ur hrugu nr. "; } cout << hrugunumer << "." << endl; hruga[ (hrugunumer) - 1 ] -= eldspytur; if( !samtals( hruga ) ) { cout << endl << "Eg vann. Thad gengur bara betur naest!" << endl << endl; cout << "Sladu a einhvern lykil... " << endl; getch( ); } cout << endl; } int samtals( int* hruga ) { int samtala = 0; for( int i = 0; i < hrugufjoldi; i++ ) { samtala += hruga[ i ]; } return samtala; }<commit_msg>Second commit<commit_after>//NIM dabs oktber 1997 #include <iostream> #include <conio.h> #include <stdlib.h> using namespace std; //etta fall a birta stu allra eldsptnahrgna (hrgur fleirtlu eignarfalli) void birta( int* hruga ); //etta fall a reikna t hversu margar eldsptur eru eftir hrgunum: int samtals( int* hruga ); //etta fall ltur tlvuna gera: void tolva( int* hruga ); //etta fall ltur notandann gera: void notandi( int* hruga ); //etta fall birtir reglurnar spilinu: void hjalp( ); //etta fall spilar spili: void spila( ); //g leyfi mr a nota eina vvra breytu af v a forriti notar alltaf //mismargar hrgur hvert og eitt skipti: int hrugufjoldi; //Hr byrjar aalforriti: void main( ) { int val; do { cout << endl << endl << endl; cout << " ADALVALMYND " << endl << endl; cout << " 1. Spila NIM" << endl; cout << " 2. Birta reglurnar i NIM" << endl; cout << " 3. Haetta " << endl << endl; cout << " Veldu 1, 2 eda 3:" << endl << endl; cin >> val; switch ( val ) { case 1: spila( ); break; case 2: hjalp( ); break; case 3: break; } } while ( val != 3 ); } void spila( ) { int hruga[ 10 ]; cout << "*-------------------------------------------------------*" << endl; cout << " NU SPILUM VID NIM!!" << endl; cout << "*-------------------------------------------------------*" << endl; cout << endl << endl; cout << "Veljum med hve margar hrugur vid spilum. " << endl; cout << "Yttu a einhvern lykil: " << endl; while( !kbhit( ) ) { rand( ); } hrugufjoldi = ( (rand( ) % 8 ) + 2 ); cout << "Vid spilum med " << hrugufjoldi << " hrugur. " << endl; for ( int i = 0; i < hrugufjoldi; i++ ) { hruga[ i ]=( ( rand( ) % 14 ) + 1 ); } cout << endl; birta ( hruga ); do { notandi( hruga ); birta( hruga ); tolva( hruga ); birta( hruga ); } while ( samtals( hruga ) ); } void hjalp( ) { cout << " UM NIM - LEIKINN " << endl << endl; cout << "Leikurinn NIM er upprunninn fra Asiu thar sem hann var" << endl; cout << "leikinn med steinvolum. Reglurnar eru thessar: " << endl; cout << "Keppendur setja einhvern fjolda af eldspytum i hrugur " << endl; cout << "(their akveda sjalfir hve margar hrugur og hve margar " << endl; cout << "eldspytur i hverri hrugu) og skiptast svo a um ad " << endl; cout << "draga eldspytur ur einhverri hrugunni. Their mega " << endl; cout << "taka eina eldspytu, nokkrar eda allar ur einni " << endl; cout << "hrugunni en their mega aldrei taka ur fleiri en " << endl; cout << "einni hrugu i einu. Sa sem tekur sidustu eldspytuna " << endl; cout << "ur sidustu hrugunni vinnur. Gangi ykkur vel! " << endl << endl; cout << "Sladu a einhvern lykil... " << endl; getch( ); } void birta( int* hruga ) { if( !samtals( hruga ) ) { return; } cout << " Hruga nr.: "; for (int i = 0; i < hrugufjoldi; i++ ) { cout << " " << (i + 1) << " "; } cout << endl << endl; cout << "Fjoldi eldspytna i hverri hrugu er: "; for ( int c = 0; c < hrugufjoldi; c++ ) { if( hruga[c] < 10 ) { cout << " " << hruga[ c ] << " "; } else { cout << hruga[ c ] << " "; } } cout << endl << endl; } void notandi( int* hruga ) { if ( samtals( hruga ) == 0 ) { return; } int eldspytur; int hrugunumer; do { cout << "Sladu inn hve margar eldspytur thu vilt taka: "; cin >> eldspytur; cout << endl; if( eldspytur < 1 ) { cout << "Thu verdur ad taka a.m.k. eina eldspytu. Veldu aftur. " << endl << endl; continue; } cout << "Sladu inn ur hvada hrugu: "; cin >> hrugunumer; if( hrugunumer > hrugufjoldi ) { cout << "Thad er engin hruga med thessu numeri. Veldu aftur." <<endl<<endl; continue; } if( eldspytur > hruga[ (hrugunumer) - 1 ] ) { cout <<"Thad eru ekki nogu margar eldspytur eftir i hrugunni. Veldu aftur."<<endl<<endl; continue; } } while ( eldspytur > hruga[ (hrugunumer) - 1 ] || eldspytur < 1 ); hruga[ hrugunumer - 1 ] -= eldspytur; if( !samtals( hruga ) ) { cout << endl << "Thu vannst. Til hamingju!" << endl << endl; cout << "Sladu a einhvern lykil... " << endl; getch( ); } cout << endl; } void tolva( int* hruga ) { if( samtals( hruga ) == 0 ) { return; } int eldspytur; int hrugunumer; do { eldspytur = ( ( rand( ) % 14 ) + 1 ); hrugunumer = ( ( rand( ) % hrugufjoldi ) + 1 ); if( eldspytur > hruga[(hrugunumer)-1] ) { continue; } } while ( eldspytur > hruga[ (hrugunumer) - 1 ] ); if ( eldspytur > 1 ) { cout << " Eg tek " << eldspytur << " eldspytur ur hrugu nr. "; } else { cout << " Eg tek " << eldspytur << " eldspytu ur hrugu nr. "; } cout << hrugunumer << "." << endl; hruga[ (hrugunumer) - 1 ] -= eldspytur; if( !samtals( hruga ) ) { cout << endl << "Eg vann. Thad gengur bara betur naest!" << endl << endl; cout << "Sladu a einhvern lykil... " << endl; getch( ); } cout << endl; } int samtals( int* hruga ) { int samtala = 0; for( int i = 0; i < hrugufjoldi; i++ ) { samtala += hruga[ i ]; } return samtala; }<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: vcscommand.cpp // Purpose: Implementation of wxExVCSCommand class // Author: Anton van Wezenbeek // Created: 2010-08-27 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/vcscommand.h> int wxExVCSCommand::m_Instances = 0; wxExVCSCommand::wxExVCSCommand() : m_Command() , m_SubMenu() , m_SubMenuIsCommand(false) , m_No(0) , m_Type(VCS_COMMAND_IS_UNKNOWN) { } wxExVCSCommand::wxExVCSCommand( const wxString& command, const wxString& type, const wxString& submenu, const wxString& subcommand) : m_Command(command) , m_SubMenu(!submenu.empty() ? submenu: subcommand) , m_SubMenuIsCommand(!subcommand.empty()) , m_No(m_Instances++) , m_Type(From(type)) { } int wxExVCSCommand::From(const wxString& type) const { if (type.IsEmpty()) { return VCS_COMMAND_IS_BOTH; } else if (type == "popup") { return VCS_COMMAND_IS_POPUP; } else if (type == "main") { return VCS_COMMAND_IS_MAIN; } else { return VCS_COMMAND_IS_UNKNOWN; } } const wxString wxExVCSCommand::GetCommand( bool include_subcommand, bool include_accelerators) const { wxString command = m_Command; if (m_SubMenuIsCommand && include_subcommand) { command += " " + m_SubMenu; } if (command.Contains("&") && !include_accelerators) { command.Replace("&", wxEmptyString); } return command; } bool wxExVCSCommand::IsAdd() const { return GetCommand(false) == "add"; } bool wxExVCSCommand::IsCheckout() const { return GetCommand(false) == "checkout" || GetCommand(false) == "co"; } bool wxExVCSCommand::IsCommit() const { return GetCommand(false) == "commit" || GetCommand(false) == "ci"; } bool wxExVCSCommand::IsDiff() const { return GetCommand(false) == "diff"; } bool wxExVCSCommand::IsHelp() const { return GetCommand(false) == "help"; } bool wxExVCSCommand::IsOpen() const { return GetCommand(false) == "blame" || GetCommand(false) == "cat" || GetCommand(false) == "diff"; } bool wxExVCSCommand::IsUpdate() const { return GetCommand(false) == "update" || GetCommand(false) == "up"; } <commit_msg>use IsDiff instead of diff<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: vcscommand.cpp // Purpose: Implementation of wxExVCSCommand class // Author: Anton van Wezenbeek // Created: 2010-08-27 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/vcscommand.h> int wxExVCSCommand::m_Instances = 0; wxExVCSCommand::wxExVCSCommand() : m_Command() , m_SubMenu() , m_SubMenuIsCommand(false) , m_No(0) , m_Type(VCS_COMMAND_IS_UNKNOWN) { } wxExVCSCommand::wxExVCSCommand( const wxString& command, const wxString& type, const wxString& submenu, const wxString& subcommand) : m_Command(command) , m_SubMenu(!submenu.empty() ? submenu: subcommand) , m_SubMenuIsCommand(!subcommand.empty()) , m_No(m_Instances++) , m_Type(From(type)) { } int wxExVCSCommand::From(const wxString& type) const { if (type.IsEmpty()) { return VCS_COMMAND_IS_BOTH; } else if (type == "popup") { return VCS_COMMAND_IS_POPUP; } else if (type == "main") { return VCS_COMMAND_IS_MAIN; } else { return VCS_COMMAND_IS_UNKNOWN; } } const wxString wxExVCSCommand::GetCommand( bool include_subcommand, bool include_accelerators) const { wxString command = m_Command; if (m_SubMenuIsCommand && include_subcommand) { command += " " + m_SubMenu; } if (command.Contains("&") && !include_accelerators) { command.Replace("&", wxEmptyString); } return command; } bool wxExVCSCommand::IsAdd() const { return GetCommand(false) == "add"; } bool wxExVCSCommand::IsCheckout() const { return GetCommand(false) == "checkout" || GetCommand(false) == "co"; } bool wxExVCSCommand::IsCommit() const { return GetCommand(false) == "commit" || GetCommand(false) == "ci"; } bool wxExVCSCommand::IsDiff() const { return GetCommand(false) == "diff"; } bool wxExVCSCommand::IsHelp() const { return GetCommand(false) == "help"; } bool wxExVCSCommand::IsOpen() const { return GetCommand(false) == "blame" || GetCommand(false) == "cat" || IsDiff(); } bool wxExVCSCommand::IsUpdate() const { return GetCommand(false) == "update" || GetCommand(false) == "up"; } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2006 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "FFMpegDecoder.h" #include "Player.h" #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/ScopeTimer.h" #include <iostream> #include <sstream> #include <unistd.h> using namespace std; namespace avg { bool FFMpegDecoder::m_bInitialized = false; FFMpegDecoder::FFMpegDecoder () : m_pFormatContext(0), m_pVStream(0), m_pPacketData(0) { initVideoSupport(); } FFMpegDecoder::~FFMpegDecoder () { if (m_pFormatContext) { close(); } } void avcodecError(const string & filename, int err) { switch(err) { case AVERROR_NUMEXPECTED: AVG_TRACE(Logger::ERROR, filename << ": Incorrect image filename syntax."); AVG_TRACE(Logger::ERROR, "Use '%%d' to specify the image number:"); AVG_TRACE(Logger::ERROR, " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';"); AVG_TRACE(Logger::ERROR, " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'."); break; case AVERROR_INVALIDDATA: AVG_TRACE(Logger::ERROR, filename << ": Error while parsing header"); break; case AVERROR_NOFMT: AVG_TRACE(Logger::ERROR, filename << ": Unknown format"); break; default: AVG_TRACE(Logger::ERROR, filename << ": Error while opening file (Num:" << err << ")"); break; } // TODO: Continue without video. exit(-1); } void dump_stream_info(AVFormatContext *s) { cerr << "Stream info: " << endl; if (s->track != 0) fprintf(stderr, " Track: %d\n", s->track); if (s->title[0] != '\0') fprintf(stderr, " Title: %s\n", s->title); if (s->author[0] != '\0') fprintf(stderr, " Author: %s\n", s->author); if (s->album[0] != '\0') fprintf(stderr, " Album: %s\n", s->album); if (s->year != 0) fprintf(stderr, " Year: %d\n", s->year); if (s->genre[0] != '\0') fprintf(stderr, " Genre: %s\n", s->genre); } bool FFMpegDecoder::open (const std::string& sFilename, int* pWidth, int* pHeight) { AVFormatParameters params; int err; m_sFilename = sFilename; AVG_TRACE(Logger::PROFILE, "Opening " << sFilename); memset(&params, 0, sizeof(params)); params.image_format = 0; err = av_open_input_file(&m_pFormatContext, sFilename.c_str(), 0, 0, &params); if (err < 0) { avcodecError(sFilename, err); } err = av_find_stream_info(m_pFormatContext); if (err < 0) { AVG_TRACE(Logger::ERROR, sFilename << ": Could not find codec parameters."); return false; } av_read_play(m_pFormatContext); m_VStreamIndex = -1; for(int i = 0; i < m_pFormatContext->nb_streams; i++) { #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) AVCodecContext *enc = &m_pFormatContext->streams[i]->codec; #else AVCodecContext *enc = m_pFormatContext->streams[i]->codec; #endif switch(enc->codec_type) { /* case CODEC_TYPE_AUDIO: if (audio_index < 0 && !audio_disable) audio_index = i; break; */ case CODEC_TYPE_VIDEO: if (m_VStreamIndex < 0) m_VStreamIndex = i; break; default: break; } } // dump_format(m_pFormatContext, 0, m_sFilename.c_str(), 0); // dump_stream_info(m_pFormatContext); if (m_VStreamIndex < 0) { AVG_TRACE(Logger::ERROR, sFilename << " does not contain any video streams."); return false; } AVCodecContext *enc; #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) enc = &(m_pFormatContext->streams[m_VStreamIndex]->codec); #else enc = m_pFormatContext->streams[m_VStreamIndex]->codec; #endif // enc->debug = 0x0001; // see avcodec.h AVCodec * codec = avcodec_find_decoder(enc->codec_id); if (!codec || avcodec_open(enc, codec) < 0) { AVG_TRACE(Logger::ERROR, sFilename << ": could not open codec (?!)."); return false; } m_pVStream = m_pFormatContext->streams[m_VStreamIndex]; #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) *pWidth = m_pVStream->codec.width; *pHeight = m_pVStream->codec.height; #else *pWidth = m_pVStream->codec->width; *pHeight = m_pVStream->codec->height; #endif m_bFirstPacket = true; m_PacketLenLeft = 0; m_bEOF = false; return true; } void FFMpegDecoder::close() { AVG_TRACE(Logger::PROFILE, "Closing " << m_sFilename); AVCodecContext * enc; #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) enc = &(m_pFormatContext->streams[m_VStreamIndex]->codec); #else enc = m_pFormatContext->streams[m_VStreamIndex]->codec; #endif if (!m_bFirstPacket) { av_free_packet(&m_Packet); } m_pPacketData = 0; avcodec_close(enc); m_pVStream = 0; av_close_input_file(m_pFormatContext); m_pFormatContext = 0; } void FFMpegDecoder::seek(int DestFrame, int CurFrame) { #if LIBAVFORMAT_BUILD <= 4616 av_seek_frame(m_pFormatContext, m_VStreamIndex, int((double(DestFrame)*1000000*1000)/m_pVStream->r_frame_rate)); #else #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) av_seek_frame(m_pFormatContext, m_VStreamIndex, int((double(DestFrame)*1000000*1000)/m_pVStream->r_frame_rate), 0); #else double framerate = (m_pVStream->r_frame_rate.num)/m_pVStream->r_frame_rate.den; av_seek_frame(m_pFormatContext, m_VStreamIndex, int((double(DestFrame)*1000000*1000)/framerate), 0); #endif #endif } int FFMpegDecoder::getNumFrames() { // This is broken for some videos, but the code here is correct. // So fix the videos or ffmpeg :-). #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) return m_pVStream->r_frame_rate*(m_pVStream->duration/AV_TIME_BASE); #else return (m_pVStream->r_frame_rate.num/m_pVStream->r_frame_rate.den)*(m_pVStream->duration/AV_TIME_BASE); #endif } double FFMpegDecoder::getFPS() { #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) return m_pVStream->r_frame_rate; #else return (m_pVStream->r_frame_rate.num/m_pVStream->r_frame_rate.den); #endif } static ProfilingZone RenderToBmpProfilingZone(" FFMpeg: renderToBmp"); static ProfilingZone ImgConvertProfilingZone(" FFMpeg: img_convert"); bool FFMpegDecoder::renderToBmp(BitmapPtr pBmp) { ScopeTimer Timer(RenderToBmpProfilingZone); AVFrame Frame; readFrame(Frame); if (!m_bEOF) { AVPicture DestPict; unsigned char * pDestBits = pBmp->getPixels(); DestPict.data[0] = pDestBits; DestPict.data[1] = pDestBits+1; DestPict.data[2] = pDestBits+2; DestPict.data[3] = pDestBits+3; DestPict.linesize[0] = pBmp->getStride(); DestPict.linesize[1] = pBmp->getStride(); DestPict.linesize[2] = pBmp->getStride(); DestPict.linesize[3] = pBmp->getStride(); int DestFmt; switch(pBmp->getPixelFormat()) { case R8G8B8X8: DestFmt = PIX_FMT_RGBA32; break; case B8G8R8X8: // This isn't supported directly by FFMpeg. DestFmt = PIX_FMT_RGBA32; DestPict.data[1] = pDestBits+3; DestPict.data[3] = pDestBits+1; break; case R8G8B8: DestFmt = PIX_FMT_RGB24; break; case B8G8R8: DestFmt = PIX_FMT_BGR24; break; case YCbCr422: DestFmt = PIX_FMT_YUV422; break; default: AVG_TRACE(Logger::ERROR, "FFMpegDecoder: Dest format " << pBmp->getPixelFormatString() << " not supported."); assert(false); } #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) AVCodecContext *enc = &m_pVStream->codec; #else AVCodecContext *enc = m_pVStream->codec; #endif { ScopeTimer Timer(ImgConvertProfilingZone); img_convert(&DestPict, DestFmt, (AVPicture*)&Frame, enc->pix_fmt, enc->width, enc->height); } } return m_bEOF; } bool FFMpegDecoder::isYCbCrSupported() { return true; } bool FFMpegDecoder::canRenderToBuffer(int BPP) { //TODO: This is a bug: We should enable direct rendering if DFB is being // used and not just compiled in! #ifdef AVG_ENABLE_DFB return (BPP == 24); #else return false; #endif } void FFMpegDecoder::initVideoSupport() { if (!m_bInitialized) { av_register_all(); m_bInitialized = true; // Avoid libavcodec console spam - turn this up again when libavcodec // doesn't spam anymore :-). // av_log_set_level(AV_LOG_DEBUG); av_log_set_level(AV_LOG_QUIET); } } void FFMpegDecoder::readFrame(AVFrame& Frame) { #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) AVCodecContext *enc = &m_pVStream->codec; #else AVCodecContext *enc = m_pVStream->codec; #endif if (enc->codec_id == CODEC_ID_RAWVIDEO) { AVPacket Packet; m_bEOF = getNextVideoPacket(Packet); if (m_bEOF) { return ; } avpicture_fill((AVPicture*)&Frame, Packet.data, enc->pix_fmt, enc->width, enc->height); av_free_packet(&Packet); } else { int gotPicture = 0; while (!gotPicture) { if (m_PacketLenLeft <= 0) { if (!m_bFirstPacket) { av_free_packet(&m_Packet); } m_bFirstPacket = false; m_bEOF = getNextVideoPacket(m_Packet); if (m_bEOF) { return ; } m_PacketLenLeft = m_Packet.size; m_pPacketData = m_Packet.data; } int Len1 = avcodec_decode_video(enc, &Frame, &gotPicture, m_pPacketData, m_PacketLenLeft); if (Len1 < 0) { AVG_TRACE(Logger::WARNING, "Error decoding " << m_sFilename); // TODO: simulate eof. } m_pPacketData += Len1; m_PacketLenLeft -= Len1; } /* cerr << "coded_picture_number: " << Frame.coded_picture_number << ", display_picture_number: " << Frame.display_picture_number << ", pts: " << Frame.pts << endl; cerr << "key_frame: " << Frame.key_frame << ", pict_type: " << Frame.pict_type << endl; AVFrac spts = m_pVStream->pts; cerr << "Stream.pts: " << spts.val + double(spts.num)/spts.den << endl; */ } } bool FFMpegDecoder::getNextVideoPacket(AVPacket & Packet) { AVPacket CurPacket; int err = av_read_frame(m_pFormatContext, &CurPacket); if (err < 0) { return true; } while (CurPacket.stream_index != m_VStreamIndex) { av_free_packet(&CurPacket); int err = av_read_frame(m_pFormatContext, &CurPacket); if (err < 0) { return true; } } Packet = CurPacket; /* if (Packet.pts != AV_NOPTS_VALUE) { cerr << "Packet.pts: " << double(Packet.pts)*m_pFormatContext->pts_num/m_pFormatContext->pts_den << endl; } */ return false; } } <commit_msg>Fixed seek with newer ffmpeg.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2006 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "FFMpegDecoder.h" #include "Player.h" #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/ScopeTimer.h" #include <iostream> #include <sstream> #include <unistd.h> using namespace std; namespace avg { bool FFMpegDecoder::m_bInitialized = false; FFMpegDecoder::FFMpegDecoder () : m_pFormatContext(0), m_pVStream(0), m_pPacketData(0) { initVideoSupport(); } FFMpegDecoder::~FFMpegDecoder () { if (m_pFormatContext) { close(); } } void avcodecError(const string & filename, int err) { switch(err) { case AVERROR_NUMEXPECTED: AVG_TRACE(Logger::ERROR, filename << ": Incorrect image filename syntax."); AVG_TRACE(Logger::ERROR, "Use '%%d' to specify the image number:"); AVG_TRACE(Logger::ERROR, " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';"); AVG_TRACE(Logger::ERROR, " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'."); break; case AVERROR_INVALIDDATA: AVG_TRACE(Logger::ERROR, filename << ": Error while parsing header"); break; case AVERROR_NOFMT: AVG_TRACE(Logger::ERROR, filename << ": Unknown format"); break; default: AVG_TRACE(Logger::ERROR, filename << ": Error while opening file (Num:" << err << ")"); break; } // TODO: Continue without video. exit(-1); } void dump_stream_info(AVFormatContext *s) { cerr << "Stream info: " << endl; if (s->track != 0) fprintf(stderr, " Track: %d\n", s->track); if (s->title[0] != '\0') fprintf(stderr, " Title: %s\n", s->title); if (s->author[0] != '\0') fprintf(stderr, " Author: %s\n", s->author); if (s->album[0] != '\0') fprintf(stderr, " Album: %s\n", s->album); if (s->year != 0) fprintf(stderr, " Year: %d\n", s->year); if (s->genre[0] != '\0') fprintf(stderr, " Genre: %s\n", s->genre); } bool FFMpegDecoder::open (const std::string& sFilename, int* pWidth, int* pHeight) { AVFormatParameters params; int err; m_sFilename = sFilename; AVG_TRACE(Logger::PROFILE, "Opening " << sFilename); memset(&params, 0, sizeof(params)); params.image_format = 0; err = av_open_input_file(&m_pFormatContext, sFilename.c_str(), 0, 0, &params); if (err < 0) { avcodecError(sFilename, err); } err = av_find_stream_info(m_pFormatContext); if (err < 0) { AVG_TRACE(Logger::ERROR, sFilename << ": Could not find codec parameters."); return false; } av_read_play(m_pFormatContext); m_VStreamIndex = -1; for(int i = 0; i < m_pFormatContext->nb_streams; i++) { #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) AVCodecContext *enc = &m_pFormatContext->streams[i]->codec; #else AVCodecContext *enc = m_pFormatContext->streams[i]->codec; #endif switch(enc->codec_type) { /* case CODEC_TYPE_AUDIO: if (audio_index < 0 && !audio_disable) audio_index = i; break; */ case CODEC_TYPE_VIDEO: if (m_VStreamIndex < 0) m_VStreamIndex = i; break; default: break; } } // dump_format(m_pFormatContext, 0, m_sFilename.c_str(), 0); // dump_stream_info(m_pFormatContext); if (m_VStreamIndex < 0) { AVG_TRACE(Logger::ERROR, sFilename << " does not contain any video streams."); return false; } AVCodecContext *enc; #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) enc = &(m_pFormatContext->streams[m_VStreamIndex]->codec); #else enc = m_pFormatContext->streams[m_VStreamIndex]->codec; #endif // enc->debug = 0x0001; // see avcodec.h AVCodec * codec = avcodec_find_decoder(enc->codec_id); if (!codec || avcodec_open(enc, codec) < 0) { AVG_TRACE(Logger::ERROR, sFilename << ": could not open codec (?!)."); return false; } m_pVStream = m_pFormatContext->streams[m_VStreamIndex]; #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) *pWidth = m_pVStream->codec.width; *pHeight = m_pVStream->codec.height; #else *pWidth = m_pVStream->codec->width; *pHeight = m_pVStream->codec->height; #endif m_bFirstPacket = true; m_PacketLenLeft = 0; m_bEOF = false; return true; } void FFMpegDecoder::close() { AVG_TRACE(Logger::PROFILE, "Closing " << m_sFilename); AVCodecContext * enc; #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) enc = &(m_pFormatContext->streams[m_VStreamIndex]->codec); #else enc = m_pFormatContext->streams[m_VStreamIndex]->codec; #endif if (!m_bFirstPacket) { av_free_packet(&m_Packet); } m_pPacketData = 0; avcodec_close(enc); m_pVStream = 0; av_close_input_file(m_pFormatContext); m_pFormatContext = 0; } void FFMpegDecoder::seek(int DestFrame, int CurFrame) { #if LIBAVFORMAT_BUILD <= 4616 av_seek_frame(m_pFormatContext, m_VStreamIndex, int((double(DestFrame)*1000000*1000)/m_pVStream->r_frame_rate)); #else #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) av_seek_frame(m_pFormatContext, m_VStreamIndex, int((double(DestFrame)*1000000*1000)/m_pVStream->r_frame_rate), 0); #else double framerate = (m_pVStream->r_frame_rate.num)/m_pVStream->r_frame_rate.den; av_seek_frame(m_pFormatContext, m_VStreamIndex, int((double(DestFrame)*AV_TIME_BASE)/framerate), 0); #endif #endif } int FFMpegDecoder::getNumFrames() { // This is broken for some videos, but the code here is correct. // So fix the videos or ffmpeg :-). #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) return m_pVStream->r_frame_rate*(m_pVStream->duration/AV_TIME_BASE); #else return (m_pVStream->r_frame_rate.num/m_pVStream->r_frame_rate.den)*(m_pVStream->duration/AV_TIME_BASE); #endif } double FFMpegDecoder::getFPS() { #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) return m_pVStream->r_frame_rate; #else return (m_pVStream->r_frame_rate.num/m_pVStream->r_frame_rate.den); #endif } static ProfilingZone RenderToBmpProfilingZone(" FFMpeg: renderToBmp"); static ProfilingZone ImgConvertProfilingZone(" FFMpeg: img_convert"); bool FFMpegDecoder::renderToBmp(BitmapPtr pBmp) { ScopeTimer Timer(RenderToBmpProfilingZone); AVFrame Frame; readFrame(Frame); if (!m_bEOF) { AVPicture DestPict; unsigned char * pDestBits = pBmp->getPixels(); DestPict.data[0] = pDestBits; DestPict.data[1] = pDestBits+1; DestPict.data[2] = pDestBits+2; DestPict.data[3] = pDestBits+3; DestPict.linesize[0] = pBmp->getStride(); DestPict.linesize[1] = pBmp->getStride(); DestPict.linesize[2] = pBmp->getStride(); DestPict.linesize[3] = pBmp->getStride(); int DestFmt; switch(pBmp->getPixelFormat()) { case R8G8B8X8: DestFmt = PIX_FMT_RGBA32; break; case B8G8R8X8: // This isn't supported directly by FFMpeg. DestFmt = PIX_FMT_RGBA32; DestPict.data[1] = pDestBits+3; DestPict.data[3] = pDestBits+1; break; case R8G8B8: DestFmt = PIX_FMT_RGB24; break; case B8G8R8: DestFmt = PIX_FMT_BGR24; break; case YCbCr422: DestFmt = PIX_FMT_YUV422; break; default: AVG_TRACE(Logger::ERROR, "FFMpegDecoder: Dest format " << pBmp->getPixelFormatString() << " not supported."); assert(false); } #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) AVCodecContext *enc = &m_pVStream->codec; #else AVCodecContext *enc = m_pVStream->codec; #endif { ScopeTimer Timer(ImgConvertProfilingZone); img_convert(&DestPict, DestFmt, (AVPicture*)&Frame, enc->pix_fmt, enc->width, enc->height); } } return m_bEOF; } bool FFMpegDecoder::isYCbCrSupported() { return true; } bool FFMpegDecoder::canRenderToBuffer(int BPP) { //TODO: This is a bug: We should enable direct rendering if DFB is being // used and not just compiled in! #ifdef AVG_ENABLE_DFB return (BPP == 24); #else return false; #endif } void FFMpegDecoder::initVideoSupport() { if (!m_bInitialized) { av_register_all(); m_bInitialized = true; // Avoid libavcodec console spam - turn this up again when libavcodec // doesn't spam anymore :-). // av_log_set_level(AV_LOG_DEBUG); av_log_set_level(AV_LOG_QUIET); } } void FFMpegDecoder::readFrame(AVFrame& Frame) { #if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0) AVCodecContext *enc = &m_pVStream->codec; #else AVCodecContext *enc = m_pVStream->codec; #endif if (enc->codec_id == CODEC_ID_RAWVIDEO) { AVPacket Packet; m_bEOF = getNextVideoPacket(Packet); if (m_bEOF) { return ; } avpicture_fill((AVPicture*)&Frame, Packet.data, enc->pix_fmt, enc->width, enc->height); av_free_packet(&Packet); } else { int gotPicture = 0; while (!gotPicture) { if (m_PacketLenLeft <= 0) { if (!m_bFirstPacket) { av_free_packet(&m_Packet); } m_bFirstPacket = false; m_bEOF = getNextVideoPacket(m_Packet); if (m_bEOF) { return ; } m_PacketLenLeft = m_Packet.size; m_pPacketData = m_Packet.data; } int Len1 = avcodec_decode_video(enc, &Frame, &gotPicture, m_pPacketData, m_PacketLenLeft); if (Len1 < 0) { AVG_TRACE(Logger::WARNING, "Error decoding " << m_sFilename); // TODO: simulate eof. } m_pPacketData += Len1; m_PacketLenLeft -= Len1; } /* cerr << "coded_picture_number: " << Frame.coded_picture_number << ", display_picture_number: " << Frame.display_picture_number << ", pts: " << Frame.pts << endl; cerr << "key_frame: " << Frame.key_frame << ", pict_type: " << Frame.pict_type << endl; AVFrac spts = m_pVStream->pts; cerr << "Stream.pts: " << spts.val + double(spts.num)/spts.den << endl; */ } } bool FFMpegDecoder::getNextVideoPacket(AVPacket & Packet) { AVPacket CurPacket; int err = av_read_frame(m_pFormatContext, &CurPacket); if (err < 0) { return true; } while (CurPacket.stream_index != m_VStreamIndex) { av_free_packet(&CurPacket); int err = av_read_frame(m_pFormatContext, &CurPacket); if (err < 0) { return true; } } Packet = CurPacket; /* if (Packet.pts != AV_NOPTS_VALUE) { cerr << "Packet.pts: " << double(Packet.pts)*m_pFormatContext->pts_num/m_pFormatContext->pts_den << endl; } */ return false; } } <|endoftext|>
<commit_before>/******************************************************************************* Module: JSBSim.cpp Author: Jon S. Berndt Date started: 08/17/99 Purpose: Standalone version of JSBSim. Called by: The USER. ------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- This class Handles calling JSBSim standalone. It is set up for compilation under Borland C+Builder or other compiler. HISTORY -------------------------------------------------------------------------------- 08/17/99 JSB Created ******************************************************************************** INCLUDES *******************************************************************************/ #if __BCPLUSPLUS__ >= 0x0540 // If compiling under Borland C++Builder #pragma hdrstop #include <condefs.h> USEUNIT("FGUtility.cpp"); USEUNIT("FGAtmosphere.cpp"); USEUNIT("FGAuxiliary.cpp"); USEUNIT("FGCoefficient.cpp"); USEUNIT("FGConfigFile.cpp"); USEUNIT("FGControls.cpp"); USEUNIT("FGEngine.cpp"); USEUNIT("FGFCS.cpp"); USEUNIT("FGFDMExec.cpp"); USEUNIT("FGfdmSocket.cpp"); USEUNIT("FGInitialCondition.cpp"); USEUNIT("FGLGear.cpp"); USEUNIT("FGMatrix.cpp"); USEUNIT("FGModel.cpp"); USEUNIT("FGOutput.cpp"); USEUNIT("FGPosition.cpp"); USEUNIT("FGRotation.cpp"); USEUNIT("FGState.cpp"); USEUNIT("FGTank.cpp"); USEUNIT("FGTranslation.cpp"); USEUNIT("FGAircraft.cpp"); USERES("JSBSim.res"); //--------------------------------------------------------------------------- #pragma argsused #endif #include "FGFDMExec.h" #include "FGRotation.h" #include "FGAtmosphere.h" #include "FGState.h" #include "FGFCS.h" #include "FGAircraft.h" #include "FGTranslation.h" #include "FGPosition.h" #include "FGAuxiliary.h" #include "FGOutput.h" #ifdef FGFS #include <Include/compiler.h> #include STL_IOSTREAM # ifdef FG_HAVE_STD_INCLUDES # include <ctime> # else # include <time.h> # endif #else #include <iostream> #include <ctime> #endif int main(int argc, char** argv) { FGFDMExec* FDMExec; if (argc != 3) { cout << endl << " You must enter the name of a registered aircraft and reset point:" << endl << endl << " FDM <aircraft name> <reset file>" << endl; exit(0); } FDMExec = new FGFDMExec(); FDMExec->GetAircraft()->LoadAircraft("aircraft", "engine", string(argv[1])); FDMExec->GetState()->Reset("aircraft", string(argv[2])); while (FDMExec->GetState()->Getsim_time() <= 25.0) { // // Fake an elevator kick here after 5 seconds // if (FDMExec->GetState()->Getsim_time() > 5.0 && FDMExec->GetState()->Getsim_time() < 6.0) { FDMExec->GetFCS()->SetDe(0.05); } else { FDMExec->GetFCS()->SetDe(0.00); } FDMExec->Run(); } delete FDMExec; return 0; } <commit_msg>Replace call to Reset with call to Initialize<commit_after>/******************************************************************************* Module: JSBSim.cpp Author: Jon S. Berndt Date started: 08/17/99 Purpose: Standalone version of JSBSim. Called by: The USER. ------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- This class Handles calling JSBSim standalone. It is set up for compilation under Borland C+Builder or other compiler. HISTORY -------------------------------------------------------------------------------- 08/17/99 JSB Created ******************************************************************************** INCLUDES *******************************************************************************/ #if __BCPLUSPLUS__ >= 0x0540 // If compiling under Borland C++Builder #pragma hdrstop #include <condefs.h> USEUNIT("FGUtility.cpp"); USEUNIT("FGAtmosphere.cpp"); USEUNIT("FGAuxiliary.cpp"); USEUNIT("FGCoefficient.cpp"); USEUNIT("FGConfigFile.cpp"); USEUNIT("FGControls.cpp"); USEUNIT("FGEngine.cpp"); USEUNIT("FGFCS.cpp"); USEUNIT("FGFDMExec.cpp"); USEUNIT("FGfdmSocket.cpp"); USEUNIT("FGInitialCondition.cpp"); USEUNIT("FGLGear.cpp"); USEUNIT("FGMatrix.cpp"); USEUNIT("FGModel.cpp"); USEUNIT("FGOutput.cpp"); USEUNIT("FGPosition.cpp"); USEUNIT("FGRotation.cpp"); USEUNIT("FGState.cpp"); USEUNIT("FGTank.cpp"); USEUNIT("FGTranslation.cpp"); USEUNIT("FGAircraft.cpp"); USERES("JSBSim.res"); //--------------------------------------------------------------------------- #pragma argsused #endif #include "FGFDMExec.h" #include "FGRotation.h" #include "FGAtmosphere.h" #include "FGState.h" #include "FGFCS.h" #include "FGAircraft.h" #include "FGTranslation.h" #include "FGPosition.h" #include "FGAuxiliary.h" #include "FGOutput.h" #ifdef FGFS #include <Include/compiler.h> #include STL_IOSTREAM # ifdef FG_HAVE_STD_INCLUDES # include <ctime> # else # include <time.h> # endif #else #include <iostream> #include <ctime> #endif int main(int argc, char** argv) { FGFDMExec* FDMExec; if (argc != 3) { cout << endl << " You must enter the name of a registered aircraft and reset point:" << endl << endl << " FDM <aircraft name> <reset file>" << endl; exit(0); } FDMExec = new FGFDMExec(); FDMExec->GetAircraft()->LoadAircraft("aircraft", "engine", string(argv[1])); //FDMExec->GetState()->Reset("aircraft", string(argv[2])); FDMExec->GetState()->Initialize(2000,0,0,0,0,0,0.5,0.5,40000); while (FDMExec->GetState()->Getsim_time() <= 5.0) { // // Fake an elevator kick here after 5 seconds // if (FDMExec->GetState()->Getsim_time() > 5.0 && FDMExec->GetState()->Getsim_time() < 6.0) { FDMExec->GetFCS()->SetDe(0.05); } else { FDMExec->GetFCS()->SetDe(0.00); } FDMExec->Run(); } delete FDMExec; return 0; } <|endoftext|>
<commit_before>#include "instanciate.h" #include "details/context/isolate.h" #include <memory> #include "details/reporting/report.h" #include "details/atom/func-overload-match.h" #include "details/reporting/message.h" #include "details/utils/origin.h" #include "libnany-traces.h" using namespace Yuni; namespace Nany { namespace Pass { namespace Instanciate { ProgramBuilder::ProgramBuilder(Logs::Report report, ClassdefTableView& cdeftable, const IntrinsicTable& intrinsics, IR::Program& out, IR::Program& program) : cdeftable(cdeftable) , intrinsics(intrinsics) , out(out) , currentProgram(program) , overloadMatch(report, cdeftable) , report(report) { // reduce memory allocations atomStack.reserve(4); // arbitrary lastPushedNamedParameters.reserve(32); // arbitrary lastPushedIndexedParameters.reserve(32); multipleResults.reserve(8); // arbitrary value } ProgramBuilder::~ProgramBuilder() { if (Config::Traces::printClassdefTable) printClassdefTable(); } void ProgramBuilder::printClassdefTable() { while (not atomStack.empty()) { printClassdefTable(report.subgroup(), atomStack.back()); atomStack.pop_back(); } } void ProgramBuilder::releaseScopedVariables(int scope, bool forget) { if (unlikely(atomStack.empty())) return; if (not forget and (not canGenerateCode())) return; auto& frame = atomStack.back(); // unref in the reverse order auto i = static_cast<uint32_t>(frame.lvids.size()); if (canGenerateCode()) { while (i-- != 0) { auto& clcvr = frame.lvids[i]; if (not (clcvr.scope >= scope)) continue; if (clcvr.autorelease) { //if (not clcvr.userDefinedName.empty()) // out.emitComment(String{"unref var "} << clcvr.userDefinedName << " -> %" << i); tryUnrefObject(i); } // forget this variable! if (forget) { if (not clcvr.userDefinedName.empty() and clcvr.warning.unused) { if (unlikely(not clcvr.hasBeenUsed) and (clcvr.userDefinedName != "self")) complainUnusedVariable(frame, i); } clcvr.userDefinedName.clear(); clcvr.scope = -1; } } } else { assert(forget == true); while (i-- != 0) // just invalidate everything { auto& clcvr = frame.lvids[i]; if (clcvr.scope >= scope) { clcvr.userDefinedName.clear(); clcvr.scope = -1; } } } } uint32_t ProgramBuilder::createLocalVariables(uint32_t count) { assert(lastOpcodeStacksizeOffset != (uint32_t) -1); assert(not atomStack.empty()); assert(count > 0); auto& operands = out.at<IR::ISA::Op::stacksize>(lastOpcodeStacksizeOffset); uint32_t startOffset = operands.add; operands.add += count; auto& frame = atomStack.back(); frame.resizeRegisterCount(operands.add, cdeftable); if (canGenerateCode()) { for (uint32_t i = 0; i != count; ++i) { auto& lvidinfo = frame.lvids[startOffset + i]; lvidinfo.scope = frame.scope; lvidinfo.offsetDeclOut = out.opcodeCount(); out.emitStackalloc(startOffset + i, nyt_any); } } else { for (uint32_t i = 0; i != count; ++i) frame.lvids[startOffset + i].scope = frame.scope; } return startOffset; } void ProgramBuilder::printClassdefTable(Logs::Report trace, const AtomStackFrame& frame) const { auto entry = trace.trace(); entry.message.prefix << cdeftable.keyword(frame.atom) << ' '; frame.atom.appendCaption(entry.message.prefix, cdeftable); entry << " - type matrix, after instanciation - atom " << frame.atom.atomid; for (uint i = 0; i != frame.localVariablesCount(); ++i) { auto clid = CLID{frame.atomid, i}; auto entry = trace.trace(); if (cdeftable.hasClassdef(clid) or cdeftable.hasSubstitute(clid)) { cdeftable.printClassdef(entry.message.message, clid, cdeftable.classdef(clid)); entry.message.message.trimRight(); if (cdeftable.hasSubstitute(clid)) entry << " (local replacement)"; if (frame.lvids[i].isConstexpr) entry << " (constexpr)"; } else { entry << " " << clid << ": !!INVALID CLID"; } } } bool ProgramBuilder::readAndInstanciate(uint32_t offset) { currentProgram.each(*this, offset); return success; } } // namespace Instanciate } // namespace Pass } // namespace Nany namespace Nany { bool Isolate::instanciate(Logs::Report report, const AnyString& entrypoint) { // lock the isolate MutexLocker locker{mutex}; // try to find the entrypoint Atom* entrypointAtom = nullptr; { bool canContinue = true; classdefTable.atoms.root.eachChild(entrypoint, [&](Atom& child) -> bool { if (entrypointAtom != nullptr) { canContinue = false; report.error() << "failed to instanciate '" << entrypoint << "': multiple entry points found"; return false; } entrypointAtom = &child; return true; }); if (not canContinue) return false; } if (unlikely(nullptr == entrypointAtom)) { report.ICE() << "failed to instanciate '" << entrypoint << "()': function not found"; return false; } if (unlikely(entrypointAtom->type != Atom::Type::funcdef)) { report.ICE() << "failed to instanciate '" << entrypoint << "': the atom is not a function"; return false; } // parameters for the signature decltype(FuncOverloadMatch::result.params) params; Logs::Message::Ptr newReport; ClassdefTableView cdeftblView{classdefTable}; Pass::Instanciate::InstanciateData info{newReport, *entrypointAtom, cdeftblView, intrinsics, params}; auto* program = Pass::Instanciate::InstanciateAtom(info); report.appendEntry(newReport); return (nullptr != program); } } // namespace Nany <commit_msg>minor optimization for creating local variables<commit_after>#include "instanciate.h" #include "details/context/isolate.h" #include <memory> #include "details/reporting/report.h" #include "details/atom/func-overload-match.h" #include "details/reporting/message.h" #include "details/utils/origin.h" #include "libnany-traces.h" using namespace Yuni; namespace Nany { namespace Pass { namespace Instanciate { ProgramBuilder::ProgramBuilder(Logs::Report report, ClassdefTableView& cdeftable, const IntrinsicTable& intrinsics, IR::Program& out, IR::Program& program) : cdeftable(cdeftable) , intrinsics(intrinsics) , out(out) , currentProgram(program) , overloadMatch(report, cdeftable) , report(report) { // reduce memory allocations atomStack.reserve(4); // arbitrary lastPushedNamedParameters.reserve(32); // arbitrary lastPushedIndexedParameters.reserve(32); multipleResults.reserve(8); // arbitrary value } ProgramBuilder::~ProgramBuilder() { if (Config::Traces::printClassdefTable) printClassdefTable(); } void ProgramBuilder::printClassdefTable() { while (not atomStack.empty()) { printClassdefTable(report.subgroup(), atomStack.back()); atomStack.pop_back(); } } void ProgramBuilder::releaseScopedVariables(int scope, bool forget) { if (unlikely(atomStack.empty())) return; if (not forget and (not canGenerateCode())) return; auto& frame = atomStack.back(); // unref in the reverse order auto i = static_cast<uint32_t>(frame.lvids.size()); if (canGenerateCode()) { while (i-- != 0) { auto& clcvr = frame.lvids[i]; if (not (clcvr.scope >= scope)) continue; if (clcvr.autorelease) { //if (not clcvr.userDefinedName.empty()) // out.emitComment(String{"unref var "} << clcvr.userDefinedName << " -> %" << i); tryUnrefObject(i); } // forget this variable! if (forget) { if (not clcvr.userDefinedName.empty() and clcvr.warning.unused) { if (unlikely(not clcvr.hasBeenUsed) and (clcvr.userDefinedName != "self")) complainUnusedVariable(frame, i); } clcvr.userDefinedName.clear(); clcvr.scope = -1; } } } else { assert(forget == true); while (i-- != 0) // just invalidate everything { auto& clcvr = frame.lvids[i]; if (clcvr.scope >= scope) { clcvr.userDefinedName.clear(); clcvr.scope = -1; } } } } uint32_t ProgramBuilder::createLocalVariables(uint32_t count) { assert(lastOpcodeStacksizeOffset != (uint32_t) -1); assert(not atomStack.empty()); assert(count > 0); auto& operands = out.at<IR::ISA::Op::stacksize>(lastOpcodeStacksizeOffset); uint32_t startOffset = operands.add; auto& frame = atomStack.back(); if (count == 1) { frame.resizeRegisterCount((++operands.add), cdeftable); if (canGenerateCode()) { auto& lvidinfo = frame.lvids[startOffset]; lvidinfo.scope = frame.scope; lvidinfo.offsetDeclOut = out.opcodeCount(); out.emitStackalloc(startOffset, nyt_any); } else frame.lvids[startOffset].scope = frame.scope; } else { operands.add += count; frame.resizeRegisterCount(operands.add, cdeftable); if (canGenerateCode()) { for (uint32_t i = 0; i != count; ++i) { auto& lvidinfo = frame.lvids[startOffset + i]; lvidinfo.scope = frame.scope; lvidinfo.offsetDeclOut = out.opcodeCount(); out.emitStackalloc(startOffset + i, nyt_any); } } else { for (uint32_t i = 0; i != count; ++i) frame.lvids[startOffset + i].scope = frame.scope; } } return startOffset; } void ProgramBuilder::printClassdefTable(Logs::Report trace, const AtomStackFrame& frame) const { auto entry = trace.trace(); entry.message.prefix << cdeftable.keyword(frame.atom) << ' '; frame.atom.appendCaption(entry.message.prefix, cdeftable); entry << " - type matrix, after instanciation - atom " << frame.atom.atomid; for (uint i = 0; i != frame.localVariablesCount(); ++i) { auto clid = CLID{frame.atomid, i}; auto entry = trace.trace(); if (cdeftable.hasClassdef(clid) or cdeftable.hasSubstitute(clid)) { cdeftable.printClassdef(entry.message.message, clid, cdeftable.classdef(clid)); entry.message.message.trimRight(); if (cdeftable.hasSubstitute(clid)) entry << " (local replacement)"; if (frame.lvids[i].isConstexpr) entry << " (constexpr)"; } else { entry << " " << clid << ": !!INVALID CLID"; } } } bool ProgramBuilder::readAndInstanciate(uint32_t offset) { currentProgram.each(*this, offset); return success; } } // namespace Instanciate } // namespace Pass } // namespace Nany namespace Nany { bool Isolate::instanciate(Logs::Report report, const AnyString& entrypoint) { // lock the isolate MutexLocker locker{mutex}; // try to find the entrypoint Atom* entrypointAtom = nullptr; { bool canContinue = true; classdefTable.atoms.root.eachChild(entrypoint, [&](Atom& child) -> bool { if (entrypointAtom != nullptr) { canContinue = false; report.error() << "failed to instanciate '" << entrypoint << "': multiple entry points found"; return false; } entrypointAtom = &child; return true; }); if (not canContinue) return false; } if (unlikely(nullptr == entrypointAtom)) { report.ICE() << "failed to instanciate '" << entrypoint << "()': function not found"; return false; } if (unlikely(entrypointAtom->type != Atom::Type::funcdef)) { report.ICE() << "failed to instanciate '" << entrypoint << "': the atom is not a function"; return false; } // parameters for the signature decltype(FuncOverloadMatch::result.params) params; Logs::Message::Ptr newReport; ClassdefTableView cdeftblView{classdefTable}; Pass::Instanciate::InstanciateData info{newReport, *entrypointAtom, cdeftblView, intrinsics, params}; auto* program = Pass::Instanciate::InstanciateAtom(info); report.appendEntry(newReport); return (nullptr != program); } } // namespace Nany <|endoftext|>
<commit_before>#include "yebash.hpp" #include "History.hpp" #include "catch.hpp" #include <initializer_list> #include <iostream> #include <algorithm> #include <sstream> using namespace yb; using namespace std; namespace { History createHistory(initializer_list<string> const& commands) { stringstream ss; for (auto && command: commands) { ss << command << std::endl; } History history; history.read(ss); return history; } void tearDown() { std::stringstream output, ss; Printer printer(output); History history; history.read(ss); HistorySuggestion suggestion(history); yebash(suggestion, printer, '\n'); } } // anon namespace TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]" ) { auto testCharacter = [] (char const c) { History history = createHistory({}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); auto result = yebash(suggestion, printer, c); REQUIRE(result == c); REQUIRE(output.str() == ""); }; string domain = "abcdefghijklmnopqrstuvwxyz01234567890-_"; for_each(begin(domain), end(domain), testCharacter); tearDown(); } TEST_CASE( "Order of commands from history is preserved", "[basic.history_order_preserved]" ) { History history = createHistory({"abc1", "abc2"}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); auto character = 'a'; auto result = yebash(suggestion, printer, character); REQUIRE(result == character); REQUIRE(output.str() == "bc2"); tearDown(); } unsigned char rollSuggestions(HistorySuggestion &suggestion, Printer &printer, int n) { unsigned char result; for (int i = 0; i < n; i++) { result = yebash(suggestion, printer, 0x06); } return result; } TEST_CASE( "Suggestions can be switched", "[basic.browsing_suggestions]" ) { History history = createHistory({"a", "ab", "abc", "abcd", "bcd"}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); yebash(suggestion, printer, 'a'); SECTION( "one switch" ) { auto result = rollSuggestions(suggestion, printer, 1); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbc"); } SECTION( "two switches" ) { auto result = rollSuggestions(suggestion, printer, 2); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbcb"); } SECTION( "third switch to empty suggestion" ) { auto result = rollSuggestions(suggestion, printer, 3); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbcb"); } SECTION( "no more suggestions" ) { auto result = rollSuggestions(suggestion, printer, 4); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbcb"); } SECTION( "go back to the first suggestion" ) { auto result = rollSuggestions(suggestion, printer, 5); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbcbbcd"); } tearDown(); } <commit_msg>added backspace test that fails<commit_after>#include "yebash.hpp" #include "History.hpp" #include "catch.hpp" #include <initializer_list> #include <iostream> #include <algorithm> #include <sstream> using namespace yb; using namespace std; namespace { History createHistory(initializer_list<string> const& commands) { stringstream ss; for (auto && command: commands) { ss << command << std::endl; } History history; history.read(ss); return history; } void tearDown() { std::stringstream output, ss; Printer printer(output); History history; history.read(ss); HistorySuggestion suggestion(history); yebash(suggestion, printer, '\n'); } } // anon namespace TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]" ) { auto testCharacter = [] (char const c) { History history = createHistory({}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); auto result = yebash(suggestion, printer, c); REQUIRE(result == c); REQUIRE(output.str() == ""); }; string domain = "abcdefghijklmnopqrstuvwxyz01234567890-_"; for_each(begin(domain), end(domain), testCharacter); tearDown(); } TEST_CASE( "Order of commands from history is preserved", "[basic.history_order_preserved]" ) { History history = createHistory({"abc1", "abc2"}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); auto character = 'a'; auto result = yebash(suggestion, printer, character); REQUIRE(result == character); REQUIRE(output.str() == "bc2"); tearDown(); } unsigned char rollSuggestions(HistorySuggestion &suggestion, Printer &printer, int n) { unsigned char result; for (int i = 0; i < n; i++) { result = yebash(suggestion, printer, 0x06); } return result; } TEST_CASE( "Suggestions can be switched", "[basic.browsing_suggestions]" ) { History history = createHistory({"a", "ab", "abc", "abcd", "bcd"}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); yebash(suggestion, printer, 'a'); SECTION( "one switch" ) { auto result = rollSuggestions(suggestion, printer, 1); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbc"); } SECTION( "two switches" ) { auto result = rollSuggestions(suggestion, printer, 2); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbcb"); } SECTION( "third switch to empty suggestion" ) { auto result = rollSuggestions(suggestion, printer, 3); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbcb"); } SECTION( "no more suggestions" ) { auto result = rollSuggestions(suggestion, printer, 4); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbcb"); } SECTION( "go back to the first suggestion" ) { auto result = rollSuggestions(suggestion, printer, 5); REQUIRE(result == 0); REQUIRE(output.str() == "bcdbcbbcd"); } tearDown(); } TEST_CASE( "Backspace invalidates suggestions", "[basic.backspace]" ) { History history = createHistory({"12345", "def", "trolo", "abc", "123"}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); constexpr char backspace = 0x7f; SECTION( "go through history -> 1234" ) { yebash(suggestion, printer, '1'); yebash(suggestion, printer, '2'); yebash(suggestion, printer, '3'); yebash(suggestion, printer, '4'); REQUIRE(output.str() == "2335"); } SECTION( "backspace -> 123" ) { yebash(suggestion, printer, backspace); REQUIRE(output.str() == ""); } SECTION( "go forward again" ) { auto result = yebash(suggestion, printer, '4'); REQUIRE(output.str() == "5"); } tearDown(); } <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <Nazara/Core/Error.hpp> #include <type_traits> namespace Ndk { inline World::World(bool addDefaultSystems) { if (addDefaultSystems) AddDefaultSystems(); } inline World::World(World&& world) noexcept : HandledObject(std::move(world)) { operator=(std::move(world)); } inline BaseSystem& World::AddSystem(std::unique_ptr<BaseSystem>&& system) { NazaraAssert(system, "System must be valid"); SystemIndex index = system->GetIndex(); // Nous nous assurons que le vecteur de component est suffisamment grand pour contenir le nouveau component if (index >= m_systems.size()) m_systems.resize(index + 1); // Affectation et retour du système m_systems[index] = std::move(system); m_systems[index]->SetWorld(this); Invalidate(); // On force une mise à jour de toutes les entités return *m_systems[index].get(); } template<typename SystemType, typename... Args> SystemType& World::AddSystem(Args&&... args) { static_assert(std::is_base_of<BaseSystem, SystemType>::value, "SystemType is not a component"); // Allocation et affectation du component std::unique_ptr<SystemType> ptr(new SystemType(std::forward(args)...)); return static_cast<SystemType&>(AddSystem(std::move(ptr))); } inline World::EntityList World::CreateEntities(unsigned int count) { EntityList list; list.reserve(count); for (unsigned int i = 0; i < count; ++i) list.emplace_back(CreateEntity()); return list; } inline const World::EntityList& World::GetEntities() { return m_aliveEntities; } inline BaseSystem& World::GetSystem(SystemIndex index) { ///DOC: Le système doit être présent NazaraAssert(HasSystem(index), "This system is not part of the world"); BaseSystem* system = m_systems[index].get(); NazaraAssert(system, "Invalid system pointer"); return *system; } template<typename SystemType> SystemType& World::GetSystem() { ///DOC: Le système doit être présent static_assert(std::is_base_of<BaseSystem, SystemType>::value, "SystemType is not a system"); SystemIndex index = GetSystemIndex<SystemType>(); return static_cast<SystemType&>(GetSystem(index)); } inline bool World::HasSystem(SystemIndex index) const { return index < m_systems.size() && m_systems[index]; } template<typename SystemType> bool World::HasSystem() const { static_assert(std::is_base_of<BaseSystem, SystemType>::value, "SystemType is not a component"); SystemIndex index = GetSystemIndex<SystemType>(); return HasSystem(index); } inline void World::KillEntities(const EntityList& list) { for (const EntityHandle& entity : list) KillEntity(entity); } inline bool World::IsEntityValid(const Entity* entity) const { return entity && entity->GetWorld() == this && IsEntityIdValid(entity->GetId()); } inline bool World::IsEntityIdValid(EntityId id) const { return id < m_entities.size() && m_entities[id].entity.IsValid(); } inline void World::RemoveAllSystems() { m_systems.clear(); } inline void World::RemoveSystem(SystemIndex index) { ///DOC: N'a aucun effet si le système n'est pas présent if (HasSystem(index)) m_systems[index].reset(); } template<typename SystemType> void World::RemoveSystem() { static_assert(std::is_base_of<BaseSystem, SystemType>(), "SystemType is not a system"); SystemIndex index = GetSystemIndex<SystemType>(); RemoveSystem(index); } inline void World::Update(float elapsedTime) { Update(); //< Update entities // And then update systems for (auto& systemPtr : m_systems) { if (systemPtr) systemPtr->Update(elapsedTime); } } inline void World::Invalidate() { m_dirtyEntities.Resize(m_entities.size(), false); m_dirtyEntities.Set(true); // Activation de tous les bits } inline void World::Invalidate(EntityId id) { m_dirtyEntities.UnboundedSet(id, true); } inline World& World::operator=(World&& world) noexcept { m_aliveEntities = std::move(world.m_aliveEntities); m_dirtyEntities = std::move(world.m_dirtyEntities); m_freeIdList = std::move(world.m_freeIdList); m_killedEntities = std::move(world.m_killedEntities); m_entities = std::move(world.m_entities); for (EntityBlock& block : m_entities) block.entity.SetWorld(this); m_systems = std::move(world.m_systems); for (const auto& systemPtr : m_systems) systemPtr->SetWorld(this); return *this; } } <commit_msg>Sdk/World: Fix compilation error when submitting arguments on system creation<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <Nazara/Core/Error.hpp> #include <type_traits> namespace Ndk { inline World::World(bool addDefaultSystems) { if (addDefaultSystems) AddDefaultSystems(); } inline World::World(World&& world) noexcept : HandledObject(std::move(world)) { operator=(std::move(world)); } inline BaseSystem& World::AddSystem(std::unique_ptr<BaseSystem>&& system) { NazaraAssert(system, "System must be valid"); SystemIndex index = system->GetIndex(); // Nous nous assurons que le vecteur de component est suffisamment grand pour contenir le nouveau component if (index >= m_systems.size()) m_systems.resize(index + 1); // Affectation et retour du système m_systems[index] = std::move(system); m_systems[index]->SetWorld(this); Invalidate(); // On force une mise à jour de toutes les entités return *m_systems[index].get(); } template<typename SystemType, typename... Args> SystemType& World::AddSystem(Args&&... args) { static_assert(std::is_base_of<BaseSystem, SystemType>::value, "SystemType is not a component"); // Allocation et affectation du component std::unique_ptr<SystemType> ptr(new SystemType(std::forward<Args>(args)...)); return static_cast<SystemType&>(AddSystem(std::move(ptr))); } inline World::EntityList World::CreateEntities(unsigned int count) { EntityList list; list.reserve(count); for (unsigned int i = 0; i < count; ++i) list.emplace_back(CreateEntity()); return list; } inline const World::EntityList& World::GetEntities() { return m_aliveEntities; } inline BaseSystem& World::GetSystem(SystemIndex index) { ///DOC: Le système doit être présent NazaraAssert(HasSystem(index), "This system is not part of the world"); BaseSystem* system = m_systems[index].get(); NazaraAssert(system, "Invalid system pointer"); return *system; } template<typename SystemType> SystemType& World::GetSystem() { ///DOC: Le système doit être présent static_assert(std::is_base_of<BaseSystem, SystemType>::value, "SystemType is not a system"); SystemIndex index = GetSystemIndex<SystemType>(); return static_cast<SystemType&>(GetSystem(index)); } inline bool World::HasSystem(SystemIndex index) const { return index < m_systems.size() && m_systems[index]; } template<typename SystemType> bool World::HasSystem() const { static_assert(std::is_base_of<BaseSystem, SystemType>::value, "SystemType is not a component"); SystemIndex index = GetSystemIndex<SystemType>(); return HasSystem(index); } inline void World::KillEntities(const EntityList& list) { for (const EntityHandle& entity : list) KillEntity(entity); } inline bool World::IsEntityValid(const Entity* entity) const { return entity && entity->GetWorld() == this && IsEntityIdValid(entity->GetId()); } inline bool World::IsEntityIdValid(EntityId id) const { return id < m_entities.size() && m_entities[id].entity.IsValid(); } inline void World::RemoveAllSystems() { m_systems.clear(); } inline void World::RemoveSystem(SystemIndex index) { ///DOC: N'a aucun effet si le système n'est pas présent if (HasSystem(index)) m_systems[index].reset(); } template<typename SystemType> void World::RemoveSystem() { static_assert(std::is_base_of<BaseSystem, SystemType>(), "SystemType is not a system"); SystemIndex index = GetSystemIndex<SystemType>(); RemoveSystem(index); } inline void World::Update(float elapsedTime) { Update(); //< Update entities // And then update systems for (auto& systemPtr : m_systems) { if (systemPtr) systemPtr->Update(elapsedTime); } } inline void World::Invalidate() { m_dirtyEntities.Resize(m_entities.size(), false); m_dirtyEntities.Set(true); // Activation de tous les bits } inline void World::Invalidate(EntityId id) { m_dirtyEntities.UnboundedSet(id, true); } inline World& World::operator=(World&& world) noexcept { m_aliveEntities = std::move(world.m_aliveEntities); m_dirtyEntities = std::move(world.m_dirtyEntities); m_freeIdList = std::move(world.m_freeIdList); m_killedEntities = std::move(world.m_killedEntities); m_entities = std::move(world.m_entities); for (EntityBlock& block : m_entities) block.entity.SetWorld(this); m_systems = std::move(world.m_systems); for (const auto& systemPtr : m_systems) systemPtr->SetWorld(this); return *this; } } <|endoftext|>
<commit_before>AliAnalysisTaskSEDs *AddTaskDs() { // // Test macro for the AliAnalysisTaskSE for Ds candidates AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskDs", "No analysis manager to connect to."); return NULL; } // Aanalysis task AliAnalysisTaskSEDs *dsTask = new AliAnalysisTaskSEDs("DsAnalysis"); dsTask->SetReadMC(kTRUE); dsTask->SetDebugLevel(0); mgr->AddTask(dsTask); // // Create containers for input/output AliAnalysisDataContainer *cinputDs = mgr->CreateContainer("cinputDs",TChain::Class(), AliAnalysisManager::kInputContainer); TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG3_D2H_InvMassDs"; AliAnalysisDataContainer *coutputDs = mgr->CreateContainer("coutputDs",TList::Class(), AliAnalysisManager::kOutputContainer, outputfile.Data()); mgr->ConnectInput(dsTask,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(dsTask,1,coutputDs); return dsTask; } <commit_msg>Added flag readMC as an argument of AddTaskDs()<commit_after>AliAnalysisTaskSEDs *AddTaskDs(Bool_t readMC=kTRUE) { // // Test macro for the AliAnalysisTaskSE for Ds candidates AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskDs", "No analysis manager to connect to."); return NULL; } // Aanalysis task AliAnalysisTaskSEDs *dsTask = new AliAnalysisTaskSEDs("DsAnalysis"); dsTask->SetReadMC(readMC); dsTask->SetDebugLevel(0); mgr->AddTask(dsTask); // // Create containers for input/output AliAnalysisDataContainer *cinputDs = mgr->CreateContainer("cinputDs",TChain::Class(), AliAnalysisManager::kInputContainer); TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG3_D2H_InvMassDs"; AliAnalysisDataContainer *coutputDs = mgr->CreateContainer("coutputDs",TList::Class(), AliAnalysisManager::kOutputContainer, outputfile.Data()); mgr->ConnectInput(dsTask,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(dsTask,1,coutputDs); return dsTask; } <|endoftext|>
<commit_before>#include "schedulers/bulk_scheduler.h" #include "schedulers/always_switch_scheduler.h" #include "schedulers/never_switch_scheduler.h" #include "schedulers/binary_throttle_scheduler.h" #include "schedulers/wojtek_throttle_scheduler.h" #include "schedulers/magic_throttle_scheduler.h" #include "gflags/gflags.h" DECLARE_bool(check_if_safe_ahead); DEFINE_bool(always_switch, false, ""); DECLARE_string(throttle_scheduler); DECLARE_string(switch_scheduler); namespace schedulers { BulkScheduler::BulkScheduler(const game::Race& race, game::RaceTracker& race_tracker, game::CarTracker& car_tracker, int time_limit) : race_(race), car_tracker_(car_tracker), race_tracker_(race_tracker), time_limit_(time_limit) { turbo_scheduler_.reset(new GreedyTurboScheduler(race_, car_tracker_)); throttle_scheduler_.reset(CreateThrottleScheduler()); switch_scheduler_.reset(CreateSwitchScheduler()); bump_scheduler_.reset( new BumpScheduler(race_, race_tracker_, car_tracker_)); } void BulkScheduler::Schedule(const game::CarState& state) { bump_scheduler_->Schedule(state); if (bump_scheduler_->HasTarget()) { command_ = bump_scheduler_->command(); return; } // Bumper has priority over anything else. turbo_scheduler_->Schedule(state); switch_scheduler_->Schedule(state); // If we want to switch, schedule throttle for target lane bent auto state_with_switch = state; state_with_switch.set_switch_state(switch_scheduler_->ExpectedSwitch()); throttle_scheduler_->Schedule(state_with_switch); if (car_tracker_.IsReady() && turbo_scheduler_->ShouldFireTurbo()) { command_ = game::Command(game::TurboToggle::kToggleOn); } else if (car_tracker_.IsReady() && switch_scheduler_->ShouldSwitch()) { command_ = game::Command(switch_scheduler_->SwitchDirection()); } else { command_ = game::Command(throttle_scheduler_->throttle()); } game::Command safe_command; if (FLAGS_check_if_safe_ahead && !race_tracker_.IsSafeInFront(command_, &safe_command)) command_ = safe_command; } void BulkScheduler::set_strategy(const Strategy& strategy) { strategy_ = strategy; throttle_scheduler_->set_strategy(strategy); switch_scheduler_->set_strategy(strategy); turbo_scheduler_->set_strategy(strategy); } void BulkScheduler::Overtake(const string& color) { printf("NOT IMPLEMENTED\n"); } void BulkScheduler::IssuedCommand(const game::Command& command) { if (command.SwitchSet()) { printf("Switch\n"); switch_scheduler_->Switched(); } else if (command.TurboSet()) { printf("YABADABADUUUU\n"); turbo_scheduler_->TurboUsed(); } } ThrottleScheduler* BulkScheduler::CreateThrottleScheduler() { if (FLAGS_throttle_scheduler == "BinaryThrottleScheduler") { std::cout << "Using BinaryThrottleScheduler" << std::endl; return new BinaryThrottleScheduler(race_, car_tracker_, time_limit_); } else if (FLAGS_throttle_scheduler == "WojtekThrottleScheduler") { std::cout << "Using WojtekThrottleScheduler" << std::endl; return new WojtekThrottleScheduler(&race_, &car_tracker_); } else if (FLAGS_throttle_scheduler == "MagicThrottleScheduler") { std::cout << "Using " << FLAGS_throttle_scheduler << std::endl; return new MagicThrottleScheduler(race_, car_tracker_, time_limit_); } std::cerr << "UNKNOWN throttle scheduler: " << FLAGS_throttle_scheduler << std::endl; return new BinaryThrottleScheduler(race_, car_tracker_, time_limit_); } SwitchScheduler* BulkScheduler::CreateSwitchScheduler() { if (FLAGS_switch_scheduler == "ShortestPathSwitchScheduler") { std::cout << "Using ShortestPathSwitchScheduler" << std::endl; return new ShortestPathSwitchScheduler(race_, race_tracker_, car_tracker_); } else if (FLAGS_switch_scheduler == "AlwaysSwitchScheduler") { std::cout << "Using AlwaysSwitchScheduler" << std::endl; return new AlwaysSwitchScheduler(&race_.track()); } else if (FLAGS_switch_scheduler == "NeverSwitchScheduler") { std::cout << "Using NeverSwitchScheduler" << std::endl; return new NeverSwitchScheduler(); } std::cerr << "UNKNOWN switch scheduler: " << FLAGS_switch_scheduler << std::endl; return new ShortestPathSwitchScheduler(race_, race_tracker_, car_tracker_); } } // namespace schedulers <commit_msg>Allow to use switches and turbo even if model not learnt<commit_after>#include "schedulers/bulk_scheduler.h" #include "schedulers/always_switch_scheduler.h" #include "schedulers/never_switch_scheduler.h" #include "schedulers/binary_throttle_scheduler.h" #include "schedulers/wojtek_throttle_scheduler.h" #include "schedulers/magic_throttle_scheduler.h" #include "gflags/gflags.h" DECLARE_bool(check_if_safe_ahead); DEFINE_bool(always_switch, false, ""); DECLARE_string(throttle_scheduler); DECLARE_string(switch_scheduler); namespace schedulers { BulkScheduler::BulkScheduler(const game::Race& race, game::RaceTracker& race_tracker, game::CarTracker& car_tracker, int time_limit) : race_(race), car_tracker_(car_tracker), race_tracker_(race_tracker), time_limit_(time_limit) { turbo_scheduler_.reset(new GreedyTurboScheduler(race_, car_tracker_)); throttle_scheduler_.reset(CreateThrottleScheduler()); switch_scheduler_.reset(CreateSwitchScheduler()); bump_scheduler_.reset( new BumpScheduler(race_, race_tracker_, car_tracker_)); } void BulkScheduler::Schedule(const game::CarState& state) { bump_scheduler_->Schedule(state); if (bump_scheduler_->HasTarget()) { command_ = bump_scheduler_->command(); return; } // Bumper has priority over anything else. turbo_scheduler_->Schedule(state); switch_scheduler_->Schedule(state); // If we want to switch, schedule throttle for target lane bent auto state_with_switch = state; state_with_switch.set_switch_state(switch_scheduler_->ExpectedSwitch()); throttle_scheduler_->Schedule(state_with_switch); if (turbo_scheduler_->ShouldFireTurbo()) { command_ = game::Command(game::TurboToggle::kToggleOn); } else if (switch_scheduler_->ShouldSwitch()) { command_ = game::Command(switch_scheduler_->SwitchDirection()); } else { command_ = game::Command(throttle_scheduler_->throttle()); } game::Command safe_command; if (FLAGS_check_if_safe_ahead && !race_tracker_.IsSafeInFront(command_, &safe_command)) command_ = safe_command; } void BulkScheduler::set_strategy(const Strategy& strategy) { strategy_ = strategy; throttle_scheduler_->set_strategy(strategy); switch_scheduler_->set_strategy(strategy); turbo_scheduler_->set_strategy(strategy); } void BulkScheduler::Overtake(const string& color) { printf("NOT IMPLEMENTED\n"); } void BulkScheduler::IssuedCommand(const game::Command& command) { if (command.SwitchSet()) { printf("Switch\n"); switch_scheduler_->Switched(); } else if (command.TurboSet()) { printf("YABADABADUUUU\n"); turbo_scheduler_->TurboUsed(); } } ThrottleScheduler* BulkScheduler::CreateThrottleScheduler() { if (FLAGS_throttle_scheduler == "BinaryThrottleScheduler") { std::cout << "Using BinaryThrottleScheduler" << std::endl; return new BinaryThrottleScheduler(race_, car_tracker_, time_limit_); } else if (FLAGS_throttle_scheduler == "WojtekThrottleScheduler") { std::cout << "Using WojtekThrottleScheduler" << std::endl; return new WojtekThrottleScheduler(&race_, &car_tracker_); } else if (FLAGS_throttle_scheduler == "MagicThrottleScheduler") { std::cout << "Using " << FLAGS_throttle_scheduler << std::endl; return new MagicThrottleScheduler(race_, car_tracker_, time_limit_); } std::cerr << "UNKNOWN throttle scheduler: " << FLAGS_throttle_scheduler << std::endl; return new BinaryThrottleScheduler(race_, car_tracker_, time_limit_); } SwitchScheduler* BulkScheduler::CreateSwitchScheduler() { if (FLAGS_switch_scheduler == "ShortestPathSwitchScheduler") { std::cout << "Using ShortestPathSwitchScheduler" << std::endl; return new ShortestPathSwitchScheduler(race_, race_tracker_, car_tracker_); } else if (FLAGS_switch_scheduler == "AlwaysSwitchScheduler") { std::cout << "Using AlwaysSwitchScheduler" << std::endl; return new AlwaysSwitchScheduler(&race_.track()); } else if (FLAGS_switch_scheduler == "NeverSwitchScheduler") { std::cout << "Using NeverSwitchScheduler" << std::endl; return new NeverSwitchScheduler(); } std::cerr << "UNKNOWN switch scheduler: " << FLAGS_switch_scheduler << std::endl; return new ShortestPathSwitchScheduler(race_, race_tracker_, car_tracker_); } } // namespace schedulers <|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 <cstdint> #include <limits> #include <string> #include "gtest/gtest.h" #include "arrow/test-util.h" #include "arrow/util/buffer.h" #include "arrow/util/status.h" using std::string; namespace arrow { class TestBuffer : public ::testing::Test {}; TEST_F(TestBuffer, Resize) { PoolBuffer buf; ASSERT_EQ(0, buf.size()); ASSERT_OK(buf.Resize(100)); ASSERT_EQ(100, buf.size()); ASSERT_OK(buf.Resize(200)); ASSERT_EQ(200, buf.size()); // Make it smaller, too ASSERT_OK(buf.Resize(50)); ASSERT_EQ(50, buf.size()); } TEST_F(TestBuffer, ResizeOOM) { // realloc fails, even though there may be no explicit limit PoolBuffer buf; ASSERT_OK(buf.Resize(100)); int64_t to_alloc = std::numeric_limits<int64_t>::max(); ASSERT_RAISES(OutOfMemory, buf.Resize(to_alloc)); } TEST_F(TestBuffer, EqualsWithSameContent) { MemoryPool* pool = default_memory_pool(); int32_t bufferSize = 128 * 1024; uint8_t* rawBuffer1 = NULL; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer1)); memset(rawBuffer1, 12, bufferSize); uint8_t* rawBuffer2 = NULL; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer2)); memset(rawBuffer2, 12, bufferSize); uint8_t* rawBuffer3 = NULL; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer3)); memset(rawBuffer3, 3, bufferSize); Buffer buffer1(rawBuffer1, bufferSize); Buffer buffer2(rawBuffer2, bufferSize); Buffer buffer3(rawBuffer3, bufferSize); ASSERT_TRUE(buffer1.Equals(buffer2)); ASSERT_FALSE(buffer1.Equals(buffer3)); } TEST_F(TestBuffer, EqualsWithSameBuffer) { MemoryPool* pool = default_memory_pool(); int32_t bufferSize = 128 * 1024; uint8_t* rawBuffer = NULL; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer)); Buffer buffer1(rawBuffer, bufferSize); Buffer buffer2(rawBuffer, bufferSize); ASSERT_TRUE(buffer1.Equals(buffer2)); int64_t nbytes = bufferSize / 2; Buffer buffer3(rawBuffer, nbytes); ASSERT_TRUE(buffer1.Equals(buffer3, nbytes)); ASSERT_FALSE(buffer1.Equals(buffer3, nbytes + 1)); } } // namespace arrow <commit_msg>Fixed some comments<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 <cstdint> #include <limits> #include <string> #include "gtest/gtest.h" #include "arrow/test-util.h" #include "arrow/util/buffer.h" #include "arrow/util/status.h" using std::string; namespace arrow { class TestBuffer : public ::testing::Test {}; TEST_F(TestBuffer, Resize) { PoolBuffer buf; ASSERT_EQ(0, buf.size()); ASSERT_OK(buf.Resize(100)); ASSERT_EQ(100, buf.size()); ASSERT_OK(buf.Resize(200)); ASSERT_EQ(200, buf.size()); // Make it smaller, too ASSERT_OK(buf.Resize(50)); ASSERT_EQ(50, buf.size()); } TEST_F(TestBuffer, ResizeOOM) { // realloc fails, even though there may be no explicit limit PoolBuffer buf; ASSERT_OK(buf.Resize(100)); int64_t to_alloc = std::numeric_limits<int64_t>::max(); ASSERT_RAISES(OutOfMemory, buf.Resize(to_alloc)); } TEST_F(TestBuffer, EqualsWithSameContent) { MemoryPool* pool = default_memory_pool(); const int32_t bufferSize = 128 * 1024; uint8_t* rawBuffer1; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer1)); memset(rawBuffer1, 12, bufferSize); uint8_t* rawBuffer2; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer2)); memset(rawBuffer2, 12, bufferSize); uint8_t* rawBuffer3; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer3)); memset(rawBuffer3, 3, bufferSize); Buffer buffer1(rawBuffer1, bufferSize); Buffer buffer2(rawBuffer2, bufferSize); Buffer buffer3(rawBuffer3, bufferSize); ASSERT_TRUE(buffer1.Equals(buffer2)); ASSERT_FALSE(buffer1.Equals(buffer3)); } TEST_F(TestBuffer, EqualsWithSameBuffer) { MemoryPool* pool = default_memory_pool(); const int32_t bufferSize = 128 * 1024; uint8_t* rawBuffer; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer)); memset(rawBuffer, 111, bufferSize); Buffer buffer1(rawBuffer, bufferSize); Buffer buffer2(rawBuffer, bufferSize); ASSERT_TRUE(buffer1.Equals(buffer2)); const int64_t nbytes = bufferSize / 2; Buffer buffer3(rawBuffer, nbytes); ASSERT_TRUE(buffer1.Equals(buffer3, nbytes)); ASSERT_FALSE(buffer1.Equals(buffer3, nbytes + 1)); } } // namespace arrow <|endoftext|>
<commit_before>#include "Particles/ParticleSystem.h" #include "Particles/ParticleData.h" #include <iostream> namespace particles { /* ParticleSystem */ ParticleSystem::ParticleSystem(int maxCount) : emitRate(0.f), m_dt(0.f) { m_particles = new ParticleData(maxCount); } ParticleSystem::~ParticleSystem() { delete m_particles; for (auto s : m_spawners) { delete s; } for (auto g : m_generators) { delete g; } for (auto u : m_updaters) { delete u; } } void ParticleSystem::emitWithRate(float dt) { m_dt += dt; int maxNewParticles = 0; if (m_dt * emitRate > 1.0f) { maxNewParticles = static_cast<int>(m_dt * emitRate); m_dt -= maxNewParticles / emitRate; } if (maxNewParticles == 0) return; emitParticles(maxNewParticles); } void ParticleSystem::emitParticles(int count) { if (m_spawners.size() == 0) return; const int startId = m_particles->countAlive; const int endId = std::min(startId + count, m_particles->count - 1); const int newParticles = endId - startId; const int nSpawners = static_cast<int>(m_spawners.size()); const int spawnerCount = newParticles / nSpawners; const int remainder = newParticles - spawnerCount * nSpawners; int spawnerStartId = startId; for (int i = 0; i < nSpawners; ++i) { int numberToSpawn = (i < remainder) ? spawnerCount + 1 : spawnerCount; m_spawners[i]->spawn(m_particles, spawnerStartId, spawnerStartId + numberToSpawn); spawnerStartId += numberToSpawn; } m_spawners[0]->spawn(m_particles, startId, endId); for (auto &generator : m_generators) { generator->generate(m_particles, startId, endId); } m_particles->countAlive += newParticles; } void ParticleSystem::update(const sf::Time &dt) { if (emitRate > 0.0f) { emitWithRate(dt.asSeconds()); } for (int i = 0; i < m_particles->countAlive; ++i) { m_particles->acc[i] = { 0.0f, 0.0f }; } for (auto & updater : m_updaters) { updater->update(m_particles, dt.asSeconds()); } } void ParticleSystem::reset() { m_particles->countAlive = 0; } /* PointParticleSystem */ PointParticleSystem::PointParticleSystem(int maxCount) : ParticleSystem(maxCount) { m_vertices = sf::VertexArray(sf::Points, maxCount); } void PointParticleSystem::render(sf::RenderTarget &renderTarget) { updateVertices(); sf::RenderStates states = sf::RenderStates::Default; const sf::Vertex *ver = &m_vertices[0]; renderTarget.draw(ver, m_particles->countAlive, sf::Points, states); } void PointParticleSystem::updateVertices() { for (int i = 0; i < m_particles->countAlive; ++i) { m_vertices[i].position = m_particles->pos[i]; m_vertices[i].color = m_particles->col[i]; } } /* TextureParticleSystem */ TextureParticleSystem::TextureParticleSystem(int maxCount, sf::Texture *texture) : ParticleSystem(maxCount), m_texture(texture) { m_vertices = sf::VertexArray(sf::Quads, maxCount * 4); float x = static_cast<float>(m_texture->getSize().x); float y = static_cast<float>(m_texture->getSize().y); for (int i = 0; i < m_particles->count; ++i) { m_vertices[4 * i + 0].texCoords = sf::Vector2f(0.f, 0.f); m_vertices[4 * i + 1].texCoords = sf::Vector2f(x, 0.f); m_vertices[4 * i + 2].texCoords = sf::Vector2f(x, y); m_vertices[4 * i + 3].texCoords = sf::Vector2f(0.f, y); m_vertices[4 * i + 0].color = sf::Color::White; m_vertices[4 * i + 1].color = sf::Color::White; m_vertices[4 * i + 2].color = sf::Color::White; m_vertices[4 * i + 3].color = sf::Color::White; } additiveBlendMode = false; } void TextureParticleSystem::setTexture(sf::Texture *texture) { m_texture = texture; float x = static_cast<float>(m_texture->getSize().x); float y = static_cast<float>(m_texture->getSize().y); for (int i = 0; i < m_particles->count; ++i) { m_vertices[4 * i + 0].texCoords = sf::Vector2f(0.f, 0.f); m_vertices[4 * i + 1].texCoords = sf::Vector2f(x, 0.f); m_vertices[4 * i + 2].texCoords = sf::Vector2f(x, y); m_vertices[4 * i + 3].texCoords = sf::Vector2f(0.f, y); } } void TextureParticleSystem::updateVertices() { for (int i = 0; i < m_particles->countAlive; ++i) { float size = 0.5f * m_particles->size[i].x; float angle = m_particles->angle[i].x; m_vertices[4 * i + 0].position.x = -size; m_vertices[4 * i + 0].position.y = -size; m_vertices[4 * i + 1].position.x = +size; m_vertices[4 * i + 1].position.y = -size; m_vertices[4 * i + 2].position.x = +size; m_vertices[4 * i + 2].position.y = +size; m_vertices[4 * i + 3].position.x = -size; m_vertices[4 * i + 3].position.y = +size; if (angle != 0.f) { float sin = std::sin(angle); float cos = std::cos(angle); for (int j = 0; j < 4; ++j) { float x = m_vertices[4 * i + j].position.x; float y = m_vertices[4 * i + j].position.y; m_vertices[4 * i + j].position.x = cos * x - sin * y; m_vertices[4 * i + j].position.y = sin * x + cos * y; } } m_vertices[4 * i + 0].position.x += m_particles->pos[i].x; m_vertices[4 * i + 0].position.y += m_particles->pos[i].y; m_vertices[4 * i + 1].position.x += m_particles->pos[i].x; m_vertices[4 * i + 1].position.y += m_particles->pos[i].y; m_vertices[4 * i + 2].position.x += m_particles->pos[i].x; m_vertices[4 * i + 2].position.y += m_particles->pos[i].y; m_vertices[4 * i + 3].position.x += m_particles->pos[i].x; m_vertices[4 * i + 3].position.y += m_particles->pos[i].y; m_vertices[4 * i + 0].color = m_particles->col[i]; m_vertices[4 * i + 1].color = m_particles->col[i]; m_vertices[4 * i + 2].color = m_particles->col[i]; m_vertices[4 * i + 3].color = m_particles->col[i]; } } void TextureParticleSystem::render(sf::RenderTarget &renderTarget) { updateVertices(); sf::RenderStates states = sf::RenderStates::Default; if (additiveBlendMode) { states.blendMode = sf::BlendAdd; } states.texture = m_texture; const sf::Vertex *ver = &m_vertices[0]; renderTarget.draw(ver, m_particles->countAlive * 4, sf::Quads, states); } /* SpriteSheetParticleSystem */ void SpriteSheetParticleSystem::render(sf::RenderTarget &renderTarget) { updateVertices(); sf::RenderStates states = sf::RenderStates::Default; if (additiveBlendMode) { states.blendMode = sf::BlendAdd; } states.texture = m_texture; const sf::Vertex *ver = &m_vertices[0]; renderTarget.draw(ver, m_particles->countAlive * 4, sf::Quads, states); } void SpriteSheetParticleSystem::updateVertices() { TextureParticleSystem::updateVertices(); for (int i = 0; i < m_particles->countAlive; ++i) { float left = static_cast<float>(m_particles->texCoords[i].left); float top = static_cast<float>(m_particles->texCoords[i].top); float width = static_cast<float>(m_particles->texCoords[i].width); float height = static_cast<float>(m_particles->texCoords[i].height); m_vertices[4 * i + 0].texCoords = sf::Vector2f(left, top); m_vertices[4 * i + 1].texCoords = sf::Vector2f(left + width, top); m_vertices[4 * i + 2].texCoords = sf::Vector2f(left + width, top + height); m_vertices[4 * i + 3].texCoords = sf::Vector2f(left, top + height); } } /* MetaballParticleSystem */ const std::string vertexShader = \ "void main()" \ "{" \ " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;" \ " gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;" \ " gl_FrontColor = gl_Color;" \ "}"; const std::string fragmentShader = \ "uniform sampler2D texture;" \ "uniform vec4 customColor;" \ "uniform float threshold;" \ "" \ "void main()" \ "{" \ " vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);" \ " if (pixel.a > threshold) {" \ " gl_FragColor = customColor;" \ " }" \ " else {" \ " gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);" \ " }" \ "}"; MetaballParticleSystem::MetaballParticleSystem(int maxCount, sf::Texture *texture, int windowWidth, int windowHeight) : TextureParticleSystem(maxCount, texture) { additiveBlendMode = true; m_shader.setUniform("texture", sf::Shader::CurrentTexture); m_shader.loadFromMemory(vertexShader, fragmentShader); m_renderTexture.create(windowWidth, windowHeight); } void MetaballParticleSystem::render(sf::RenderTarget &renderTarget) { updateVertices(); sf::RenderStates states = sf::RenderStates::Default; states.blendMode = sf::BlendAdd; states.texture = m_texture; const sf::Vertex *ver = &m_vertices[0]; sf::View oldView = renderTarget.getView(); sf::View defaultView = renderTarget.getDefaultView(); m_renderTexture.setView(oldView); m_renderTexture.clear(sf::Color(0, 0, 0, 0)); m_renderTexture.draw(ver, m_particles->countAlive * 4, sf::Quads, states); m_renderTexture.display(); m_sprite.setTexture(m_renderTexture.getTexture()); sf::Glsl::Vec4 colorVec = sf::Glsl::Vec4(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f); m_shader.setUniform("customColor", colorVec); m_shader.setUniform("threshold", threshold); renderTarget.setView(defaultView); renderTarget.draw(m_sprite, &m_shader); renderTarget.setView(oldView); } }<commit_msg>Fix include<commit_after>#include "Particles/ParticleSystem.h" #include "Particles/ParticleData.h" #include "Particles/ParticleHelpers.h" namespace particles { /* ParticleSystem */ ParticleSystem::ParticleSystem(int maxCount) : emitRate(0.f), m_dt(0.f) { m_particles = new ParticleData(maxCount); } ParticleSystem::~ParticleSystem() { delete m_particles; for (auto s : m_spawners) { delete s; } for (auto g : m_generators) { delete g; } for (auto u : m_updaters) { delete u; } } void ParticleSystem::emitWithRate(float dt) { m_dt += dt; int maxNewParticles = 0; if (m_dt * emitRate > 1.0f) { maxNewParticles = static_cast<int>(m_dt * emitRate); m_dt -= maxNewParticles / emitRate; } if (maxNewParticles == 0) return; emitParticles(maxNewParticles); } void ParticleSystem::emitParticles(int count) { if (m_spawners.size() == 0) return; const int startId = m_particles->countAlive; const int endId = std::min(startId + count, m_particles->count - 1); const int newParticles = endId - startId; const int nSpawners = static_cast<int>(m_spawners.size()); const int spawnerCount = newParticles / nSpawners; const int remainder = newParticles - spawnerCount * nSpawners; int spawnerStartId = startId; for (int i = 0; i < nSpawners; ++i) { int numberToSpawn = (i < remainder) ? spawnerCount + 1 : spawnerCount; m_spawners[i]->spawn(m_particles, spawnerStartId, spawnerStartId + numberToSpawn); spawnerStartId += numberToSpawn; } m_spawners[0]->spawn(m_particles, startId, endId); for (auto &generator : m_generators) { generator->generate(m_particles, startId, endId); } m_particles->countAlive += newParticles; } void ParticleSystem::update(const sf::Time &dt) { if (emitRate > 0.0f) { emitWithRate(dt.asSeconds()); } for (int i = 0; i < m_particles->countAlive; ++i) { m_particles->acc[i] = { 0.0f, 0.0f }; } for (auto & updater : m_updaters) { updater->update(m_particles, dt.asSeconds()); } } void ParticleSystem::reset() { m_particles->countAlive = 0; } /* PointParticleSystem */ PointParticleSystem::PointParticleSystem(int maxCount) : ParticleSystem(maxCount) { m_vertices = sf::VertexArray(sf::Points, maxCount); } void PointParticleSystem::render(sf::RenderTarget &renderTarget) { updateVertices(); sf::RenderStates states = sf::RenderStates::Default; const sf::Vertex *ver = &m_vertices[0]; renderTarget.draw(ver, m_particles->countAlive, sf::Points, states); } void PointParticleSystem::updateVertices() { for (int i = 0; i < m_particles->countAlive; ++i) { m_vertices[i].position = m_particles->pos[i]; m_vertices[i].color = m_particles->col[i]; } } /* TextureParticleSystem */ TextureParticleSystem::TextureParticleSystem(int maxCount, sf::Texture *texture) : ParticleSystem(maxCount), m_texture(texture) { m_vertices = sf::VertexArray(sf::Quads, maxCount * 4); float x = static_cast<float>(m_texture->getSize().x); float y = static_cast<float>(m_texture->getSize().y); for (int i = 0; i < m_particles->count; ++i) { m_vertices[4 * i + 0].texCoords = sf::Vector2f(0.f, 0.f); m_vertices[4 * i + 1].texCoords = sf::Vector2f(x, 0.f); m_vertices[4 * i + 2].texCoords = sf::Vector2f(x, y); m_vertices[4 * i + 3].texCoords = sf::Vector2f(0.f, y); m_vertices[4 * i + 0].color = sf::Color::White; m_vertices[4 * i + 1].color = sf::Color::White; m_vertices[4 * i + 2].color = sf::Color::White; m_vertices[4 * i + 3].color = sf::Color::White; } additiveBlendMode = false; } void TextureParticleSystem::setTexture(sf::Texture *texture) { m_texture = texture; float x = static_cast<float>(m_texture->getSize().x); float y = static_cast<float>(m_texture->getSize().y); for (int i = 0; i < m_particles->count; ++i) { m_vertices[4 * i + 0].texCoords = sf::Vector2f(0.f, 0.f); m_vertices[4 * i + 1].texCoords = sf::Vector2f(x, 0.f); m_vertices[4 * i + 2].texCoords = sf::Vector2f(x, y); m_vertices[4 * i + 3].texCoords = sf::Vector2f(0.f, y); } } void TextureParticleSystem::updateVertices() { for (int i = 0; i < m_particles->countAlive; ++i) { float size = 0.5f * m_particles->size[i].x; float angle = m_particles->angle[i].x; m_vertices[4 * i + 0].position.x = -size; m_vertices[4 * i + 0].position.y = -size; m_vertices[4 * i + 1].position.x = +size; m_vertices[4 * i + 1].position.y = -size; m_vertices[4 * i + 2].position.x = +size; m_vertices[4 * i + 2].position.y = +size; m_vertices[4 * i + 3].position.x = -size; m_vertices[4 * i + 3].position.y = +size; if (angle != 0.f) { float sin = std::sin(angle); float cos = std::cos(angle); for (int j = 0; j < 4; ++j) { float x = m_vertices[4 * i + j].position.x; float y = m_vertices[4 * i + j].position.y; m_vertices[4 * i + j].position.x = cos * x - sin * y; m_vertices[4 * i + j].position.y = sin * x + cos * y; } } m_vertices[4 * i + 0].position.x += m_particles->pos[i].x; m_vertices[4 * i + 0].position.y += m_particles->pos[i].y; m_vertices[4 * i + 1].position.x += m_particles->pos[i].x; m_vertices[4 * i + 1].position.y += m_particles->pos[i].y; m_vertices[4 * i + 2].position.x += m_particles->pos[i].x; m_vertices[4 * i + 2].position.y += m_particles->pos[i].y; m_vertices[4 * i + 3].position.x += m_particles->pos[i].x; m_vertices[4 * i + 3].position.y += m_particles->pos[i].y; m_vertices[4 * i + 0].color = m_particles->col[i]; m_vertices[4 * i + 1].color = m_particles->col[i]; m_vertices[4 * i + 2].color = m_particles->col[i]; m_vertices[4 * i + 3].color = m_particles->col[i]; } } void TextureParticleSystem::render(sf::RenderTarget &renderTarget) { updateVertices(); sf::RenderStates states = sf::RenderStates::Default; if (additiveBlendMode) { states.blendMode = sf::BlendAdd; } states.texture = m_texture; const sf::Vertex *ver = &m_vertices[0]; renderTarget.draw(ver, m_particles->countAlive * 4, sf::Quads, states); } /* SpriteSheetParticleSystem */ void SpriteSheetParticleSystem::render(sf::RenderTarget &renderTarget) { updateVertices(); sf::RenderStates states = sf::RenderStates::Default; if (additiveBlendMode) { states.blendMode = sf::BlendAdd; } states.texture = m_texture; const sf::Vertex *ver = &m_vertices[0]; renderTarget.draw(ver, m_particles->countAlive * 4, sf::Quads, states); } void SpriteSheetParticleSystem::updateVertices() { TextureParticleSystem::updateVertices(); for (int i = 0; i < m_particles->countAlive; ++i) { float left = static_cast<float>(m_particles->texCoords[i].left); float top = static_cast<float>(m_particles->texCoords[i].top); float width = static_cast<float>(m_particles->texCoords[i].width); float height = static_cast<float>(m_particles->texCoords[i].height); m_vertices[4 * i + 0].texCoords = sf::Vector2f(left, top); m_vertices[4 * i + 1].texCoords = sf::Vector2f(left + width, top); m_vertices[4 * i + 2].texCoords = sf::Vector2f(left + width, top + height); m_vertices[4 * i + 3].texCoords = sf::Vector2f(left, top + height); } } /* MetaballParticleSystem */ const std::string vertexShader = \ "void main()" \ "{" \ " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;" \ " gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;" \ " gl_FrontColor = gl_Color;" \ "}"; const std::string fragmentShader = \ "uniform sampler2D texture;" \ "uniform vec4 customColor;" \ "uniform float threshold;" \ "" \ "void main()" \ "{" \ " vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);" \ " if (pixel.a > threshold) {" \ " gl_FragColor = customColor;" \ " }" \ " else {" \ " gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);" \ " }" \ "}"; MetaballParticleSystem::MetaballParticleSystem(int maxCount, sf::Texture *texture, int windowWidth, int windowHeight) : TextureParticleSystem(maxCount, texture) { additiveBlendMode = true; m_shader.setUniform("texture", sf::Shader::CurrentTexture); m_shader.loadFromMemory(vertexShader, fragmentShader); m_renderTexture.create(windowWidth, windowHeight); } void MetaballParticleSystem::render(sf::RenderTarget &renderTarget) { updateVertices(); sf::RenderStates states = sf::RenderStates::Default; states.blendMode = sf::BlendAdd; states.texture = m_texture; const sf::Vertex *ver = &m_vertices[0]; sf::View oldView = renderTarget.getView(); sf::View defaultView = renderTarget.getDefaultView(); m_renderTexture.setView(oldView); m_renderTexture.clear(sf::Color(0, 0, 0, 0)); m_renderTexture.draw(ver, m_particles->countAlive * 4, sf::Quads, states); m_renderTexture.display(); m_sprite.setTexture(m_renderTexture.getTexture()); sf::Glsl::Vec4 colorVec = sf::Glsl::Vec4(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f); m_shader.setUniform("customColor", colorVec); m_shader.setUniform("threshold", threshold); renderTarget.setView(defaultView); renderTarget.draw(m_sprite, &m_shader); renderTarget.setView(oldView); } }<|endoftext|>
<commit_before><commit_msg>cid#1254675 Uncaught exception<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: testcontainer.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 09:32:23 $ * * 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 * ************************************************************************/ #include <osl/mutex.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <cppuhelper/implbase1.hxx> #include <com/sun/star/beans/XVetoableChangeListener.hpp> using namespace ::cppu; using namespace ::osl; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; class TestListener : public WeakImplHelper1< XVetoableChangeListener > { // Methods virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException) { } virtual void SAL_CALL vetoableChange( const ::com::sun::star::beans::PropertyChangeEvent& aEvent ) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::uno::RuntimeException) { } }; void test_interfacecontainer() { Mutex mutex; { OInterfaceContainerHelper helper( mutex ); Reference< XVetoableChangeListener > r1 = new TestListener(); Reference< XVetoableChangeListener > r2 = new TestListener(); Reference< XVetoableChangeListener > r3 = new TestListener(); helper.addInterface( r1 ); helper.addInterface( r2 ); helper.addInterface( r3 ); helper.disposeAndClear( EventObject() ); } { OInterfaceContainerHelper helper( mutex ); Reference< XVetoableChangeListener > r1 = new TestListener(); Reference< XVetoableChangeListener > r2 = new TestListener(); Reference< XVetoableChangeListener > r3 = new TestListener(); helper.addInterface( r1 ); helper.addInterface( r2 ); helper.addInterface( r3 ); OInterfaceIteratorHelper iterator( helper ); while( iterator.hasMoreElements() ) ((XVetoableChangeListener*)iterator.next())->vetoableChange( PropertyChangeEvent() ); helper.disposeAndClear( EventObject() ); } { OInterfaceContainerHelper helper( mutex ); Reference< XVetoableChangeListener > r1 = new TestListener(); Reference< XVetoableChangeListener > r2 = new TestListener(); Reference< XVetoableChangeListener > r3 = new TestListener(); helper.addInterface( r1 ); helper.addInterface( r2 ); helper.addInterface( r3 ); OInterfaceIteratorHelper iterator( helper ); ((XVetoableChangeListener*)iterator.next())->vetoableChange( PropertyChangeEvent() ); iterator.remove(); ((XVetoableChangeListener*)iterator.next())->vetoableChange( PropertyChangeEvent() ); iterator.remove(); ((XVetoableChangeListener*)iterator.next())->vetoableChange( PropertyChangeEvent() ); iterator.remove(); OSL_ASSERT( helper.getLength() == 0 ); helper.disposeAndClear( EventObject() ); } { OInterfaceContainerHelper helper( mutex ); Reference< XVetoableChangeListener > r1 = new TestListener(); Reference< XVetoableChangeListener > r2 = new TestListener(); Reference< XVetoableChangeListener > r3 = new TestListener(); helper.addInterface( r1 ); helper.addInterface( r2 ); helper.addInterface( r3 ); { OInterfaceIteratorHelper iterator( helper ); while( iterator.hasMoreElements() ) { Reference< XVetoableChangeListener > r = ((XVetoableChangeListener*)iterator.next()); if( r == r1 ) iterator.remove(); } } OSL_ASSERT( helper.getLength() == 2 ); { OInterfaceIteratorHelper iterator( helper ); while( iterator.hasMoreElements() ) { Reference< XVetoableChangeListener > r = ((XVetoableChangeListener*)iterator.next()); OSL_ASSERT( r != r1 && ( r == r2 || r == r3 ) ); } } helper.disposeAndClear( EventObject() ); } } <commit_msg>INTEGRATION: CWS pchfix02 (1.2.56); FILE MERGED 2006/09/01 17:23:19 kaib 1.2.56.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: testcontainer.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-16 12:44:03 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cppuhelper.hxx" #include <osl/mutex.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <cppuhelper/implbase1.hxx> #include <com/sun/star/beans/XVetoableChangeListener.hpp> using namespace ::cppu; using namespace ::osl; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; class TestListener : public WeakImplHelper1< XVetoableChangeListener > { // Methods virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException) { } virtual void SAL_CALL vetoableChange( const ::com::sun::star::beans::PropertyChangeEvent& aEvent ) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::uno::RuntimeException) { } }; void test_interfacecontainer() { Mutex mutex; { OInterfaceContainerHelper helper( mutex ); Reference< XVetoableChangeListener > r1 = new TestListener(); Reference< XVetoableChangeListener > r2 = new TestListener(); Reference< XVetoableChangeListener > r3 = new TestListener(); helper.addInterface( r1 ); helper.addInterface( r2 ); helper.addInterface( r3 ); helper.disposeAndClear( EventObject() ); } { OInterfaceContainerHelper helper( mutex ); Reference< XVetoableChangeListener > r1 = new TestListener(); Reference< XVetoableChangeListener > r2 = new TestListener(); Reference< XVetoableChangeListener > r3 = new TestListener(); helper.addInterface( r1 ); helper.addInterface( r2 ); helper.addInterface( r3 ); OInterfaceIteratorHelper iterator( helper ); while( iterator.hasMoreElements() ) ((XVetoableChangeListener*)iterator.next())->vetoableChange( PropertyChangeEvent() ); helper.disposeAndClear( EventObject() ); } { OInterfaceContainerHelper helper( mutex ); Reference< XVetoableChangeListener > r1 = new TestListener(); Reference< XVetoableChangeListener > r2 = new TestListener(); Reference< XVetoableChangeListener > r3 = new TestListener(); helper.addInterface( r1 ); helper.addInterface( r2 ); helper.addInterface( r3 ); OInterfaceIteratorHelper iterator( helper ); ((XVetoableChangeListener*)iterator.next())->vetoableChange( PropertyChangeEvent() ); iterator.remove(); ((XVetoableChangeListener*)iterator.next())->vetoableChange( PropertyChangeEvent() ); iterator.remove(); ((XVetoableChangeListener*)iterator.next())->vetoableChange( PropertyChangeEvent() ); iterator.remove(); OSL_ASSERT( helper.getLength() == 0 ); helper.disposeAndClear( EventObject() ); } { OInterfaceContainerHelper helper( mutex ); Reference< XVetoableChangeListener > r1 = new TestListener(); Reference< XVetoableChangeListener > r2 = new TestListener(); Reference< XVetoableChangeListener > r3 = new TestListener(); helper.addInterface( r1 ); helper.addInterface( r2 ); helper.addInterface( r3 ); { OInterfaceIteratorHelper iterator( helper ); while( iterator.hasMoreElements() ) { Reference< XVetoableChangeListener > r = ((XVetoableChangeListener*)iterator.next()); if( r == r1 ) iterator.remove(); } } OSL_ASSERT( helper.getLength() == 2 ); { OInterfaceIteratorHelper iterator( helper ); while( iterator.hasMoreElements() ) { Reference< XVetoableChangeListener > r = ((XVetoableChangeListener*)iterator.next()); OSL_ASSERT( r != r1 && ( r == r2 || r == r3 ) ); } } helper.disposeAndClear( EventObject() ); } } <|endoftext|>
<commit_before>// -*- mode: c++; c-basic-offset:4 -*- // This file is part of libdap, A C++ implementation of the OPeNDAP Data // Access Protocol. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: James Gallagher <jgallagher@opendap.org> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. #include <cstdlib> #include <string> #include <sstream> #include <iterator> //#define DODS_DEBUG #include "D4FunctionScanner.h" #include "D4FunctionDriver.h" #include "d4_function_parser.tab.hh" #include "DMR.h" #include "D4RValue.h" #include "BaseType.h" #include "escaping.h" #include "debug.h" namespace libdap { bool D4FunctionDriver::parse(const std::string &expr) { d_expr = expr; // set for error messages. See the %initial-action section of .yy std::istringstream iss(expr); D4FunctionScanner *scanner = new D4FunctionScanner(iss); D4FunctionParser *parser = new D4FunctionParser(*scanner, *this /* driver */); if (trace_parsing()) { parser->set_debug_level(1); parser->set_debug_stream(std::cerr); } return parser->parse() == 0; } /** * Build and return a new RValue. Allocates the new D4RValue object. * The code tries first to find the id in the DMR - that is, it checks * first to see if it is a variable in the current dataset. If that * fails it will try to build an unsigned long long, a long long or * a double from the string (in that order). If that fails the code * converts the id into a string. * * @param id An identifier (really a string) parsed from the function * expression. May contain quotes. * @return Return a pointer to the new allocated D4RValue object. */ D4RValue * D4FunctionDriver::build_rvalue(const std::string &id) { BaseType *btp = 0; // Look for the id in the dataset first if (top_basetype()) { btp = top_basetype()->var(id); } else { btp = dmr()->root()->find_var(id); } if (btp) return new D4RValue(btp); // If the id is not a variable, try to turn it into a constant, // otherwise, its an error. char *end_ptr = 0; errno = 0; unsigned long long ull_val = strtoull(id.c_str(), &end_ptr, 0); if (end_ptr == '\0' && errno == 0) return new D4RValue(ull_val); errno = 0; long long ll_val = strtoll(id.c_str(), &end_ptr, 0); if (end_ptr == '\0' && errno == 0) return new D4RValue(ll_val); errno = 0; double d_val = strtod(id.c_str(), &end_ptr); if (end_ptr == '\0' && errno == 0) return new D4RValue(d_val); return new D4RValue(www2id(id)); } void D4FunctionDriver::throw_not_found(const string &id, const string &ident) { throw Error(d_expr + ": The variable " + id + " was not found in the dataset (" + ident + ")."); } void D4FunctionDriver::throw_not_array(const string &id, const string &ident) { throw Error(d_expr + ": The variable '" + id + "' is not an Array variable (" + ident + ")."); } // This method is called from the parser (see d4_ce_parser.yy, down in the code // section). This will be called during the call to D4FunctionParser::parse(), that // is inside D4FunctionDriver::parse(...) void D4FunctionDriver::error(const libdap::location &l, const std::string &m) { std::cerr << l << ": " << m << std::endl; } #if 0 void D4CEDriver::set_array_slices(const std::string &id, Array *a) { // Test that the indexes and dimensions match in number if (d_indexes.size() != a->dimensions()) throw Error("The index constraint for '" + id + "' does not match its rank."); Array::Dim_iter d = a->dim_begin(); for (vector<index>::iterator i = d_indexes.begin(), e = d_indexes.end(); i != e; ++i) { if ((*i).stride > (unsigned long long)a->dimension_stop(d, false)) throw Error("For '" + id + "', the index stride value is greater than the number of elements in the Array"); if (!(*i).rest && ((*i).stop) > (unsigned long long)a->dimension_stop(d, false)) throw Error("For '" + id + "', the index stop value is greater than the number of elements in the Array"); D4Dimension *dim = a->dimension_D4dim(d); // In a DAP4 CE, specifying '[]' as an array dimension slice has two meanings. // It can mean 'all the elements' of the dimension or 'apply the slicing inherited // from the shared dimension'. The latter might be provide 'all the elements' // but regardless, the Array object must record the CE correctly. if (dim && (*i).empty) { a->add_constraint(d, dim); } else { a->add_constraint(d, (*i).start, (*i).stride, (*i).rest ? -1 : (*i).stop); } ++d; } d_indexes.clear(); } #endif #if 0 void D4CEDriver::search_for_and_mark_arrays(BaseType *btp) { DBG(cerr << "Entering D4CEDriver::search_for_and_mark_arrays...(" << btp->name() << ")" << endl); assert(btp->is_constructor_type()); Constructor *ctor = static_cast<Constructor*>(btp); for (Constructor::Vars_iter i = ctor->var_begin(), e = ctor->var_end(); i != e; ++i) { switch ((*i)->type()) { case dods_array_c: DBG(cerr << "Found an array: " << (*i)->name() << endl); mark_array_variable(*i); break; case dods_structure_c: case dods_sequence_c: DBG(cerr << "Found a ctor: " << (*i)->name() << endl); search_for_and_mark_arrays(*i); break; default: break; } } } /** * When an identifier is used in a CE, is becomes part of the 'current projection,' * which means it is part of the set of variable to be sent back to the client. This * method sets a flag in the variable (send_p: send predicate) indicating that. * * @note This will check if the variable is an array and set it's slices accordingly * @param btp BaseType pointer to the variable. Must be non-null * @return The BaseType* to the variable; the send_p flag is set as a side effect. */ BaseType * D4CEDriver::mark_variable(BaseType *btp) { assert(btp); DBG(cerr << "In D4CEDriver::mark_variable... (" << btp->name() << "; " << btp->type_name() << ")" << endl); btp->set_send_p(true); if (btp->type() == dods_array_c ) { mark_array_variable(btp); } // Test for Constructors and marks arrays they contain if (btp->is_constructor_type()) { search_for_and_mark_arrays(btp); } else if (btp->type() == dods_array_c && btp->var() && btp->var()->is_constructor_type()) { search_for_and_mark_arrays(btp->var()); } // Now set the parent variables BaseType *parent = btp->get_parent(); while (parent) { parent->BaseType::set_send_p(true); // Just set the parent using BaseType's impl. parent = parent->get_parent(); } return btp; } /** * Add an array to the current projection with slicing. Calling this method will result * in the array being returned with anonymous dimensions. * * @note If id is an array that has shared dimensions and uses '[]' where a shared dimension * is found and if that shared dimension has been sliced, then the slice is used as the array's * slice for that dimension (there must be an easier way to explain that...) * * @param id * @return The BaseType* to the Array variable; the send_p and slicing information is * set as a side effect. */ BaseType * D4CEDriver::mark_array_variable(BaseType *btp) { assert(btp->type() == dods_array_c); Array *a = static_cast<Array*>(btp); // If an array appears in a CE without the slicing operators ([]) we still have to // call set_user_by_projected_var(true) for all of it's sdims for them to appear in // the CDMR. if (d_indexes.empty()) { for (Array::Dim_iter d = a->dim_begin(), de = a->dim_end(); d != de; ++d) { D4Dimension *dim = a->dimension_D4dim(d); if (dim) { a->add_constraint(d, dim); } } } else { // Test that the indexes and dimensions match in number if (d_indexes.size() != a->dimensions()) throw Error("The index constraint for '" + btp->name() + "' does not match its rank."); Array::Dim_iter d = a->dim_begin(); for (vector<index>::iterator i = d_indexes.begin(), e = d_indexes.end(); i != e; ++i) { if ((*i).stride > (unsigned long long) a->dimension_stop(d, false)) throw Error( "For '" + btp->name() + "', the index stride value is greater than the number of elements in the Array"); if (!(*i).rest && ((*i).stop) > (unsigned long long) a->dimension_stop(d, false)) throw Error( "For '" + btp->name() + "', the index stop value is greater than the number of elements in the Array"); D4Dimension *dim = a->dimension_D4dim(d); // In a DAP4 CE, specifying '[]' as an array dimension slice has two meanings. // It can mean 'all the elements' of the dimension or 'apply the slicing inherited // from the shared dimension'. The latter might be provide 'all the elements' // but regardless, the Array object must record the CE correctly. if (dim && (*i).empty) { a->add_constraint(d, dim); // calls set_used_by_projected_var(true) + more } else { a->add_constraint(d, (*i).start, (*i).stride, (*i).rest ? -1 : (*i).stop); } ++d; } d_indexes.clear(); } return btp; } /** * Add an array to the current projection with slicing. Calling this method will result * in the array being returned with anonymous dimensions. * @param id * @return The BaseType* to the Array variable; the send_p and slicing information is * set as a side effect. */ D4Dimension * D4CEDriver::slice_dimension(const std::string &id, const index &i) { D4Dimension *dim = dmr()->root()->find_dim(id); if (i.stride > dim->size()) throw Error("For '" + id + "', the index stride value is greater than the size of the dimension"); if (!i.rest && (i.stop > dim->size() - 1)) throw Error("For '" + id + "', the index stop value is greater than the size of the dimension"); dim->set_constraint(i.start, i.stride, i.rest ? dim->size() - 1: i.stop); return dim; } D4CEDriver::index D4CEDriver::make_index(const std::string &i) { unsigned long long v = get_ull(i.c_str()); return index(v, 1, v, false, false /*empty*/); } D4CEDriver::index D4CEDriver::make_index(const std::string &i, const std::string &s, const std::string &e) { return index(get_ull(i.c_str()), get_ull(s.c_str()), get_ull(e.c_str()), false, false /*empty*/); } D4CEDriver::index D4CEDriver::make_index(const std::string &i, unsigned long long s, const std::string &e) { return index(get_ull(i.c_str()), s, get_ull(e.c_str()), false, false /*empty*/); } D4CEDriver::index D4CEDriver::make_index(const std::string &i, const std::string &s) { return index(get_ull(i.c_str()), get_ull(s.c_str()), 0, true, false /*empty*/); } D4CEDriver::index D4CEDriver::make_index(const std::string &i, unsigned long long s) { return index(get_ull(i.c_str()), s, 0, true, false /*empty*/); } #endif } /* namespace libdap */ <commit_msg>lobdap: Fixed compile issue<commit_after>// -*- mode: c++; c-basic-offset:4 -*- // This file is part of libdap, A C++ implementation of the OPeNDAP Data // Access Protocol. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: James Gallagher <jgallagher@opendap.org> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. #include <cstdlib> #include <cerrno> #include <string> #include <sstream> #include <iterator> //#define DODS_DEBUG #include "D4FunctionScanner.h" #include "D4FunctionDriver.h" #include "d4_function_parser.tab.hh" #include "DMR.h" #include "D4RValue.h" #include "BaseType.h" #include "escaping.h" #include "debug.h" namespace libdap { bool D4FunctionDriver::parse(const std::string &expr) { d_expr = expr; // set for error messages. See the %initial-action section of .yy std::istringstream iss(expr); D4FunctionScanner *scanner = new D4FunctionScanner(iss); D4FunctionParser *parser = new D4FunctionParser(*scanner, *this /* driver */); if (trace_parsing()) { parser->set_debug_level(1); parser->set_debug_stream(std::cerr); } return parser->parse() == 0; } /** * Build and return a new RValue. Allocates the new D4RValue object. * The code tries first to find the id in the DMR - that is, it checks * first to see if it is a variable in the current dataset. If that * fails it will try to build an unsigned long long, a long long or * a double from the string (in that order). If that fails the code * converts the id into a string. * * @param id An identifier (really a string) parsed from the function * expression. May contain quotes. * @return Return a pointer to the new allocated D4RValue object. */ D4RValue * D4FunctionDriver::build_rvalue(const std::string &id) { BaseType *btp = 0; // Look for the id in the dataset first if (top_basetype()) { btp = top_basetype()->var(id); } else { btp = dmr()->root()->find_var(id); } if (btp) return new D4RValue(btp); // If the id is not a variable, try to turn it into a constant, // otherwise, its an error. char *end_ptr = 0; errno = 0; unsigned long long ull_val = strtoull(id.c_str(), &end_ptr, 0); if (end_ptr == '\0' && errno == 0) return new D4RValue(ull_val); errno = 0; long long ll_val = strtoll(id.c_str(), &end_ptr, 0); if (end_ptr == '\0' && errno == 0) return new D4RValue(ll_val); errno = 0; double d_val = strtod(id.c_str(), &end_ptr); if (end_ptr == '\0' && errno == 0) return new D4RValue(d_val); return new D4RValue(www2id(id)); } void D4FunctionDriver::throw_not_found(const string &id, const string &ident) { throw Error(d_expr + ": The variable " + id + " was not found in the dataset (" + ident + ")."); } void D4FunctionDriver::throw_not_array(const string &id, const string &ident) { throw Error(d_expr + ": The variable '" + id + "' is not an Array variable (" + ident + ")."); } // This method is called from the parser (see d4_ce_parser.yy, down in the code // section). This will be called during the call to D4FunctionParser::parse(), that // is inside D4FunctionDriver::parse(...) void D4FunctionDriver::error(const libdap::location &l, const std::string &m) { std::cerr << l << ": " << m << std::endl; } #if 0 void D4CEDriver::set_array_slices(const std::string &id, Array *a) { // Test that the indexes and dimensions match in number if (d_indexes.size() != a->dimensions()) throw Error("The index constraint for '" + id + "' does not match its rank."); Array::Dim_iter d = a->dim_begin(); for (vector<index>::iterator i = d_indexes.begin(), e = d_indexes.end(); i != e; ++i) { if ((*i).stride > (unsigned long long)a->dimension_stop(d, false)) throw Error("For '" + id + "', the index stride value is greater than the number of elements in the Array"); if (!(*i).rest && ((*i).stop) > (unsigned long long)a->dimension_stop(d, false)) throw Error("For '" + id + "', the index stop value is greater than the number of elements in the Array"); D4Dimension *dim = a->dimension_D4dim(d); // In a DAP4 CE, specifying '[]' as an array dimension slice has two meanings. // It can mean 'all the elements' of the dimension or 'apply the slicing inherited // from the shared dimension'. The latter might be provide 'all the elements' // but regardless, the Array object must record the CE correctly. if (dim && (*i).empty) { a->add_constraint(d, dim); } else { a->add_constraint(d, (*i).start, (*i).stride, (*i).rest ? -1 : (*i).stop); } ++d; } d_indexes.clear(); } #endif #if 0 void D4CEDriver::search_for_and_mark_arrays(BaseType *btp) { DBG(cerr << "Entering D4CEDriver::search_for_and_mark_arrays...(" << btp->name() << ")" << endl); assert(btp->is_constructor_type()); Constructor *ctor = static_cast<Constructor*>(btp); for (Constructor::Vars_iter i = ctor->var_begin(), e = ctor->var_end(); i != e; ++i) { switch ((*i)->type()) { case dods_array_c: DBG(cerr << "Found an array: " << (*i)->name() << endl); mark_array_variable(*i); break; case dods_structure_c: case dods_sequence_c: DBG(cerr << "Found a ctor: " << (*i)->name() << endl); search_for_and_mark_arrays(*i); break; default: break; } } } /** * When an identifier is used in a CE, is becomes part of the 'current projection,' * which means it is part of the set of variable to be sent back to the client. This * method sets a flag in the variable (send_p: send predicate) indicating that. * * @note This will check if the variable is an array and set it's slices accordingly * @param btp BaseType pointer to the variable. Must be non-null * @return The BaseType* to the variable; the send_p flag is set as a side effect. */ BaseType * D4CEDriver::mark_variable(BaseType *btp) { assert(btp); DBG(cerr << "In D4CEDriver::mark_variable... (" << btp->name() << "; " << btp->type_name() << ")" << endl); btp->set_send_p(true); if (btp->type() == dods_array_c ) { mark_array_variable(btp); } // Test for Constructors and marks arrays they contain if (btp->is_constructor_type()) { search_for_and_mark_arrays(btp); } else if (btp->type() == dods_array_c && btp->var() && btp->var()->is_constructor_type()) { search_for_and_mark_arrays(btp->var()); } // Now set the parent variables BaseType *parent = btp->get_parent(); while (parent) { parent->BaseType::set_send_p(true); // Just set the parent using BaseType's impl. parent = parent->get_parent(); } return btp; } /** * Add an array to the current projection with slicing. Calling this method will result * in the array being returned with anonymous dimensions. * * @note If id is an array that has shared dimensions and uses '[]' where a shared dimension * is found and if that shared dimension has been sliced, then the slice is used as the array's * slice for that dimension (there must be an easier way to explain that...) * * @param id * @return The BaseType* to the Array variable; the send_p and slicing information is * set as a side effect. */ BaseType * D4CEDriver::mark_array_variable(BaseType *btp) { assert(btp->type() == dods_array_c); Array *a = static_cast<Array*>(btp); // If an array appears in a CE without the slicing operators ([]) we still have to // call set_user_by_projected_var(true) for all of it's sdims for them to appear in // the CDMR. if (d_indexes.empty()) { for (Array::Dim_iter d = a->dim_begin(), de = a->dim_end(); d != de; ++d) { D4Dimension *dim = a->dimension_D4dim(d); if (dim) { a->add_constraint(d, dim); } } } else { // Test that the indexes and dimensions match in number if (d_indexes.size() != a->dimensions()) throw Error("The index constraint for '" + btp->name() + "' does not match its rank."); Array::Dim_iter d = a->dim_begin(); for (vector<index>::iterator i = d_indexes.begin(), e = d_indexes.end(); i != e; ++i) { if ((*i).stride > (unsigned long long) a->dimension_stop(d, false)) throw Error( "For '" + btp->name() + "', the index stride value is greater than the number of elements in the Array"); if (!(*i).rest && ((*i).stop) > (unsigned long long) a->dimension_stop(d, false)) throw Error( "For '" + btp->name() + "', the index stop value is greater than the number of elements in the Array"); D4Dimension *dim = a->dimension_D4dim(d); // In a DAP4 CE, specifying '[]' as an array dimension slice has two meanings. // It can mean 'all the elements' of the dimension or 'apply the slicing inherited // from the shared dimension'. The latter might be provide 'all the elements' // but regardless, the Array object must record the CE correctly. if (dim && (*i).empty) { a->add_constraint(d, dim); // calls set_used_by_projected_var(true) + more } else { a->add_constraint(d, (*i).start, (*i).stride, (*i).rest ? -1 : (*i).stop); } ++d; } d_indexes.clear(); } return btp; } /** * Add an array to the current projection with slicing. Calling this method will result * in the array being returned with anonymous dimensions. * @param id * @return The BaseType* to the Array variable; the send_p and slicing information is * set as a side effect. */ D4Dimension * D4CEDriver::slice_dimension(const std::string &id, const index &i) { D4Dimension *dim = dmr()->root()->find_dim(id); if (i.stride > dim->size()) throw Error("For '" + id + "', the index stride value is greater than the size of the dimension"); if (!i.rest && (i.stop > dim->size() - 1)) throw Error("For '" + id + "', the index stop value is greater than the size of the dimension"); dim->set_constraint(i.start, i.stride, i.rest ? dim->size() - 1: i.stop); return dim; } D4CEDriver::index D4CEDriver::make_index(const std::string &i) { unsigned long long v = get_ull(i.c_str()); return index(v, 1, v, false, false /*empty*/); } D4CEDriver::index D4CEDriver::make_index(const std::string &i, const std::string &s, const std::string &e) { return index(get_ull(i.c_str()), get_ull(s.c_str()), get_ull(e.c_str()), false, false /*empty*/); } D4CEDriver::index D4CEDriver::make_index(const std::string &i, unsigned long long s, const std::string &e) { return index(get_ull(i.c_str()), s, get_ull(e.c_str()), false, false /*empty*/); } D4CEDriver::index D4CEDriver::make_index(const std::string &i, const std::string &s) { return index(get_ull(i.c_str()), get_ull(s.c_str()), 0, true, false /*empty*/); } D4CEDriver::index D4CEDriver::make_index(const std::string &i, unsigned long long s) { return index(get_ull(i.c_str()), s, 0, true, false /*empty*/); } #endif } /* namespace libdap */ <|endoftext|>
<commit_before>#include "stdafx.h" #include "CityGen.h" #include "Structure.h" #include "Rect.h" #include "Utilities.h" #include "SavableCityData.h" #include "BaseFrame.h" #include "ActorSystem.h" #include "ActorAids.h" //the size of each city const int citysize = 150; //the space between each city const int cityspacing = 250; int CityGen::BufferIndex(GameTile* tile,int x, int y) { return 4 * (y*TILE_SIZE + x); } void CityGen::construct_road(GameTile* tile, vec3 start, vec3 end){ } void CityGen::construct_building(GameTile* tile, vec3 pos){ //BEGIN BUILDING DEMO //Load building floors (note lack of extension) Structure * bottomFloor = Structure::LoadStructure("teststructures/testfloor30x10"); Structure * transitionFloor = Structure::LoadStructure("teststructures/testfloor30x10to20x10"); Structure * topFloor = Structure::LoadStructure("teststructures/testfloor20x10"); //Randomize the number of floors a bit //Obviously more varied randomization would have to be done //for more variation in buildings int numberOfBaseFloors = rand() % 3; int numberOfTopFloors = rand() % 3; //A Building is used to construct a structure by stacking other structures (floors) together Building newBuilding; //Stack bottom floors for (int i = 0; i < numberOfTopFloors; i++) newBuilding.Stack(bottomFloor); //Add an adapter floor newBuilding.Stack(transitionFloor); //Add the rest for (int i = 0; i < numberOfTopFloors; i++) newBuilding.Stack(topFloor); //At this point some sort of roof should have been added //but I didn't make one //When you're all done stacking floors //call construct once to internally prepare the structure //for use newBuilding.ConstructStructure(); //Then call PlaceStructure one or more times to place the structure //in whatever 2d positions you want //automatically compensates for terrain (no building voxels underneath the ground) newBuilding.PlaceStructure(tile,vec2(pos.x,pos.y)); } void CityGen::construct_city(GameTile * tile, vec3 pos) { //First create city points at even intervals const static float evenBuildingDistance = 20.0f; const static float buildingSize = 15.0f; ContiguousList<Rect> buildingPlacements; TileCell * cells = tile->Cells; vec3 tileOffset = vec3(tile->tile_x,tile->tile_y,0) * vec3(TILE_SIZE,TILE_SIZE,1.0); //Warning HACK //create savable city data here SavableCityData * cityData = new SavableCityData(); cityData->cityPosition = pos+tileOffset; cityData->ownedByPlayer = false; float originalCityHeight = cells[int((pos.y)*TILE_SIZE + pos.x)].height; //Generate lines //set<vec2> usedSpace; static const int lineCount = 30; static const int turretSkip = 6; static const int samples = 200; static const float anglePart = M_PI*2.0f/(float)lineCount; for (int p = 0; p < lineCount; p++) { vec2 lineDirection = glm::normalize(vec2(cos(anglePart*p),sin(anglePart*p))); float lineLength = citysize*1.5; float lineSection = lineLength/samples; if ((p % turretSkip) == 0) { //Place turret vec2 spos = glm::floor(lineDirection*(-lineLength/2.0f+samples/4*lineSection)) + vec2(pos); //raise the height around the turrent float newHeight = originalCityHeight +10.0f; for (int x = -1; x <= 0; x++) { for (int y = -1; y <= 0; y++) { vec2 absPos = spos+vec2(x,y); TileCell & cell = cells[int((absPos.y)*TILE_SIZE + absPos.x)]; cell.height = newHeight; } } cityData->gunAlive.push_back(true); cityData->gunPositions.push_back(tileOffset+vec3(spos,newHeight)); } //Generate the line by sampling along it for (int i = 0; i < samples; i++) { //Find the position vec2 spos = lineDirection*(-lineLength/2.0f+i*lineSection); spos = glm::floor(spos); //check that the position is within city limits if ((spos.x < -citysize/2.0) || (spos.y < -citysize/2.0)) continue; if ((spos.x > citysize/2.0) || (spos.y > citysize/2.0)) continue; //check that the position isn't too close to the center float len = glm::length(spos); if (len < 16) continue; //Place a line here float height = (len*len-15*15)*.0008+2; vec2 absPos = glm::floor(vec2(pos)+spos); TileCell & cell = cells[int((absPos.y)*TILE_SIZE + absPos.x)]; cell.height += height; //City is stronger than surrounding terrain cell.cellHealth = 25; cell.cellMaxHealth = 25; } } //Different heights in the spire int ringHeights[5] = { 30, 28, 24, 18, 10 }; //Place the spire for (float x = -4; x <= 4; x++) { for (float y = -4; y <= 4; y++) { float ring = max(abs(x),abs(y)); vec2 spos = vec2(x,y)+vec2(pos); TileCell & cell = cells[int((spos.y)*TILE_SIZE + spos.x)]; cell.height += ringHeights[(int)ring]*3/2; //The tower is made of tough stuff cell.cellHealth = 50; cell.cellMaxHealth = 50; //Register the center if (ring == 0) { cityData->cityCenterVoxel = spos+vec2(tileOffset); cityData->originalCityCenterVoxel = cell.height; } } } //flatten terrain //generate roads for (int y = -citysize / 2; y < citysize / 2; y++) { for (int x = -citysize / 2; x < citysize / 2; x++) { cells[int((pos.y + y)*TILE_SIZE + pos.x + x)].materialId = 2; } } //Super hack, transfer city data to ai Game()->Actors.Aids()->RegisterNewCity(cityData); } void CityGen::generatecitylocations(GameTile* tile){ //the amount to blur const int blur = 4; //analyze the terrain //We Differentiate the terrain and then blur it 4x to achieve the effect of inteligent city placement //this will store the differential blur of the terrain float * analysis = new float[TILE_SIZE*TILE_SIZE]; //This allows us to access the terrain values TileCell * cells = tile->Cells; //our operator ignores edges, so set them to be really high //This also helps keep cities off the edge of tiles because that breaks things for (int y = 0; y < TILE_SIZE; y++) { //left analysis[y*TILE_SIZE + 0] = 500; //right analysis[y*TILE_SIZE + TILE_SIZE - 1] = 500; } //check the x edge and normalize the height so it matches for (int x = 0; x < TILE_SIZE; x++) { //top analysis[0 * TILE_SIZE + x] = 500; //bottom analysis[(TILE_SIZE - 1)*TILE_SIZE + x] = 500; } //Get the slope using the Sobel Operator for (int y = 1; y < TILE_SIZE - 1; y++) { for (int x = 1; x < TILE_SIZE - 1; x++) { //directions don't actually matter, we just care about magnitude of change float bottomLeftIntensity = cells[TILE_SIZE*(y - 1) + x - 1].height; float topRightIntensity = cells[TILE_SIZE*(y + 1) + x + 1].height; float topLeftIntensity = cells[TILE_SIZE*(y + 1) + x - 1].height; float bottomRightIntensity = cells[TILE_SIZE*(y - 1) + x + 1].height; float leftIntensity = cells[TILE_SIZE*(y)+x - 1].height; float rightIntensity = cells[TILE_SIZE*(y)+x + 1].height; float bottomIntensity = cells[TILE_SIZE*(y - 1) + x].height; float topIntensity = cells[TILE_SIZE*(y + 1) + x].height; float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity; float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity; float mag = glm::length(vec2(h, v)); analysis[y*TILE_SIZE + x] = mag; } } //Apply Blur 4x for (int i = 0; i < blur; i++) { for (int y = 1; y < TILE_SIZE - 1; y++) { for (int x = 1; x < TILE_SIZE - 1; x++) { //directions don't actually matter, we just care about magnitude of change float bottomLeftIntensity = analysis[TILE_SIZE*(y - 1) + x - 1]; float topRightIntensity = analysis[TILE_SIZE*(y + 1) + x + 1]; float topLeftIntensity = analysis[TILE_SIZE*(y + 1) + x - 1]; float bottomRightIntensity = analysis[TILE_SIZE*(y - 1) + x + 1]; float leftIntensity = analysis[TILE_SIZE*(y)+x - 1]; float rightIntensity = analysis[TILE_SIZE*(y)+x + 1]; float bottomIntensity = analysis[TILE_SIZE*(y - 1) + x]; float topIntensity = analysis[TILE_SIZE*(y + 1) + x]; double top = topIntensity + topLeftIntensity + topRightIntensity; double middle = analysis[y*TILE_SIZE + x] + leftIntensity + rightIntensity; double bottom = bottomIntensity + bottomLeftIntensity + bottomRightIntensity; float average = (top + middle + bottom) / 9; analysis[y*TILE_SIZE + x] = average; } } } float minheight = 5000; vec3 citylocation; float noisetolerance = 3; float heighttolerance = 5; //figure out where to put the city but make sure it doesn't go off the edge for (int y = citysize/2+10; y < TILE_SIZE - (citysize/2+10); y++) { for (int x = citysize/2+10; x < TILE_SIZE - (citysize/2+10); x++) { if (analysis[y*TILE_SIZE + x] < noisetolerance) { //check if we're too close to another city bool tooclose = false; for (int i = 0; i < tile->Cities.size(); i++) { if (glm::length(vec2(tile->Cities[i].x - x, tile->Cities[i].y - y)) < cityspacing) tooclose = true; } if (!tooclose) { if (abs(cells[(y - citysize / 2)*TILE_SIZE + x - citysize / 2].height - cells[(y + citysize / 2)*TILE_SIZE + x - citysize / 2].height) < heighttolerance && abs(cells[(y - citysize / 2)*TILE_SIZE + x + citysize / 2].height - cells[(y + citysize / 2)*TILE_SIZE + x + citysize / 2].height) < heighttolerance && abs(cells[(y + citysize / 2)*TILE_SIZE + x + citysize / 2].height - cells[(y + citysize / 2)*TILE_SIZE + x - citysize / 2].height) < heighttolerance && abs(cells[(y - citysize / 2)*TILE_SIZE + x + citysize / 2].height - cells[(y - citysize / 2)*TILE_SIZE + x - citysize / 2].height) < heighttolerance ) { //make some cities tile->Cities.push_back(vec3(x, y, 0)); cout << "CITY PLACED AT:" << x << " , " << y << endl; } } } } } //Flatten Terrain for (int i = 0; i < tile->Cities.size(); i++) { vec3 pos = tile->Cities[i]; for (int y = -citysize / 2; y < citysize / 2; y++) { for (int x = -citysize / 2; x < citysize / 2; x++) { cells[int((pos.y + y)*TILE_SIZE + pos.x + x)].height = cells[int((pos.y)*TILE_SIZE + pos.x)].height; } } } // TODO : Blur city edges /* for (int i = 0; i < tile->Cities.size(); i++) { vec3 pos = tile->Cities[i]; //walk along the edge, for each edge walk outward and normalize for (int y = pos.y - citysize/2; y < pos.y + citysize/2; y++) { //left analysis[y*TILE_SIZE + TILE_SIZE - 1] = 500; //right analysis[y*TILE_SIZE + TILE_SIZE - 1] = 500; } for (int x = pos.x - citysize / 2; x < pos.x + citysize / 2; x++) { //top analysis[0 * TILE_SIZE + x] = 500; //bottom analysis[(TILE_SIZE - 1)*TILE_SIZE + x] = 500; } } */ delete [] analysis; } void CityGen::GenerateCities(GameTile * tile) { generatecitylocations(tile); for (int i = 0; i < tile->Cities.size(); i++) { construct_city(tile, tile->Cities[i]); } tile->UpdateTileSection(0, 0, TILE_SIZE, TILE_SIZE); } <commit_msg>changed spire color<commit_after>#include "stdafx.h" #include "CityGen.h" #include "Structure.h" #include "Rect.h" #include "Utilities.h" #include "SavableCityData.h" #include "BaseFrame.h" #include "ActorSystem.h" #include "ActorAids.h" //the size of each city const int citysize = 150; //the space between each city const int cityspacing = 250; int CityGen::BufferIndex(GameTile* tile,int x, int y) { return 4 * (y*TILE_SIZE + x); } void CityGen::construct_road(GameTile* tile, vec3 start, vec3 end){ } void CityGen::construct_building(GameTile* tile, vec3 pos){ //BEGIN BUILDING DEMO //Load building floors (note lack of extension) Structure * bottomFloor = Structure::LoadStructure("teststructures/testfloor30x10"); Structure * transitionFloor = Structure::LoadStructure("teststructures/testfloor30x10to20x10"); Structure * topFloor = Structure::LoadStructure("teststructures/testfloor20x10"); //Randomize the number of floors a bit //Obviously more varied randomization would have to be done //for more variation in buildings int numberOfBaseFloors = rand() % 3; int numberOfTopFloors = rand() % 3; //A Building is used to construct a structure by stacking other structures (floors) together Building newBuilding; //Stack bottom floors for (int i = 0; i < numberOfTopFloors; i++) newBuilding.Stack(bottomFloor); //Add an adapter floor newBuilding.Stack(transitionFloor); //Add the rest for (int i = 0; i < numberOfTopFloors; i++) newBuilding.Stack(topFloor); //At this point some sort of roof should have been added //but I didn't make one //When you're all done stacking floors //call construct once to internally prepare the structure //for use newBuilding.ConstructStructure(); //Then call PlaceStructure one or more times to place the structure //in whatever 2d positions you want //automatically compensates for terrain (no building voxels underneath the ground) newBuilding.PlaceStructure(tile,vec2(pos.x,pos.y)); } void CityGen::construct_city(GameTile * tile, vec3 pos) { //First create city points at even intervals const static float evenBuildingDistance = 20.0f; const static float buildingSize = 15.0f; ContiguousList<Rect> buildingPlacements; TileCell * cells = tile->Cells; vec3 tileOffset = vec3(tile->tile_x,tile->tile_y,0) * vec3(TILE_SIZE,TILE_SIZE,1.0); //Warning HACK //create savable city data here SavableCityData * cityData = new SavableCityData(); cityData->cityPosition = pos+tileOffset; cityData->ownedByPlayer = false; float originalCityHeight = cells[int((pos.y)*TILE_SIZE + pos.x)].height; //Generate lines //set<vec2> usedSpace; static const int lineCount = 30; static const int turretSkip = 6; static const int samples = 200; static const float anglePart = M_PI*2.0f/(float)lineCount; //flatten terrain //generate roads for (int y = -citysize / 2; y < citysize / 2; y++) { for (int x = -citysize / 2; x < citysize / 2; x++) { cells[int((pos.y + y)*TILE_SIZE + pos.x + x)].materialId = 2; } } for (int p = 0; p < lineCount; p++) { vec2 lineDirection = glm::normalize(vec2(cos(anglePart*p),sin(anglePart*p))); float lineLength = citysize*1.5; float lineSection = lineLength/samples; if ((p % turretSkip) == 0) { //Place turret vec2 spos = glm::floor(lineDirection*(-lineLength/2.0f+samples/4*lineSection)) + vec2(pos); //raise the height around the turrent float newHeight = originalCityHeight +10.0f; for (int x = -1; x <= 0; x++) { for (int y = -1; y <= 0; y++) { vec2 absPos = spos+vec2(x,y); TileCell & cell = cells[int((absPos.y)*TILE_SIZE + absPos.x)]; cell.height = newHeight; } } cityData->gunAlive.push_back(true); cityData->gunPositions.push_back(tileOffset+vec3(spos,newHeight)); } //Generate the line by sampling along it for (int i = 0; i < samples; i++) { //Find the position vec2 spos = lineDirection*(-lineLength/2.0f+i*lineSection); spos = glm::floor(spos); //check that the position is within city limits if ((spos.x < -citysize/2.0) || (spos.y < -citysize/2.0)) continue; if ((spos.x > citysize/2.0) || (spos.y > citysize/2.0)) continue; //check that the position isn't too close to the center float len = glm::length(spos); if (len < 16) continue; //Place a line here float height = (len*len-15*15)*.0008+2; vec2 absPos = glm::floor(vec2(pos)+spos); TileCell & cell = cells[int((absPos.y)*TILE_SIZE + absPos.x)]; cell.height += height; //City is stronger than surrounding terrain cell.cellHealth = 25; cell.cellMaxHealth = 25; } } //Different heights in the spire int ringHeights[5] = { 30, 28, 24, 18, 10 }; //Place the spire for (float x = -4; x <= 4; x++) { for (float y = -4; y <= 4; y++) { float ring = max(abs(x),abs(y)); vec2 spos = vec2(x,y)+vec2(pos); TileCell & cell = cells[int((spos.y)*TILE_SIZE + spos.x)]; cell.height += ringHeights[(int)ring]*3/2; //The tower is made of tough stuff cell.cellHealth = 50; cell.cellMaxHealth = 50; cell.materialId = 3; //Register the center if (ring == 0) { cityData->cityCenterVoxel = spos+vec2(tileOffset); cityData->originalCityCenterVoxel = cell.height; } } } //Super hack, transfer city data to ai Game()->Actors.Aids()->RegisterNewCity(cityData); } void CityGen::generatecitylocations(GameTile* tile){ //the amount to blur const int blur = 4; //analyze the terrain //We Differentiate the terrain and then blur it 4x to achieve the effect of inteligent city placement //this will store the differential blur of the terrain float * analysis = new float[TILE_SIZE*TILE_SIZE]; //This allows us to access the terrain values TileCell * cells = tile->Cells; //our operator ignores edges, so set them to be really high //This also helps keep cities off the edge of tiles because that breaks things for (int y = 0; y < TILE_SIZE; y++) { //left analysis[y*TILE_SIZE + 0] = 500; //right analysis[y*TILE_SIZE + TILE_SIZE - 1] = 500; } //check the x edge and normalize the height so it matches for (int x = 0; x < TILE_SIZE; x++) { //top analysis[0 * TILE_SIZE + x] = 500; //bottom analysis[(TILE_SIZE - 1)*TILE_SIZE + x] = 500; } //Get the slope using the Sobel Operator for (int y = 1; y < TILE_SIZE - 1; y++) { for (int x = 1; x < TILE_SIZE - 1; x++) { //directions don't actually matter, we just care about magnitude of change float bottomLeftIntensity = cells[TILE_SIZE*(y - 1) + x - 1].height; float topRightIntensity = cells[TILE_SIZE*(y + 1) + x + 1].height; float topLeftIntensity = cells[TILE_SIZE*(y + 1) + x - 1].height; float bottomRightIntensity = cells[TILE_SIZE*(y - 1) + x + 1].height; float leftIntensity = cells[TILE_SIZE*(y)+x - 1].height; float rightIntensity = cells[TILE_SIZE*(y)+x + 1].height; float bottomIntensity = cells[TILE_SIZE*(y - 1) + x].height; float topIntensity = cells[TILE_SIZE*(y + 1) + x].height; float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity; float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity; float mag = glm::length(vec2(h, v)); analysis[y*TILE_SIZE + x] = mag; } } //Apply Blur 4x for (int i = 0; i < blur; i++) { for (int y = 1; y < TILE_SIZE - 1; y++) { for (int x = 1; x < TILE_SIZE - 1; x++) { //directions don't actually matter, we just care about magnitude of change float bottomLeftIntensity = analysis[TILE_SIZE*(y - 1) + x - 1]; float topRightIntensity = analysis[TILE_SIZE*(y + 1) + x + 1]; float topLeftIntensity = analysis[TILE_SIZE*(y + 1) + x - 1]; float bottomRightIntensity = analysis[TILE_SIZE*(y - 1) + x + 1]; float leftIntensity = analysis[TILE_SIZE*(y)+x - 1]; float rightIntensity = analysis[TILE_SIZE*(y)+x + 1]; float bottomIntensity = analysis[TILE_SIZE*(y - 1) + x]; float topIntensity = analysis[TILE_SIZE*(y + 1) + x]; double top = topIntensity + topLeftIntensity + topRightIntensity; double middle = analysis[y*TILE_SIZE + x] + leftIntensity + rightIntensity; double bottom = bottomIntensity + bottomLeftIntensity + bottomRightIntensity; float average = (top + middle + bottom) / 9; analysis[y*TILE_SIZE + x] = average; } } } float minheight = 5000; vec3 citylocation; float noisetolerance = 3; float heighttolerance = 5; //figure out where to put the city but make sure it doesn't go off the edge for (int y = citysize/2+10; y < TILE_SIZE - (citysize/2+10); y++) { for (int x = citysize/2+10; x < TILE_SIZE - (citysize/2+10); x++) { if (analysis[y*TILE_SIZE + x] < noisetolerance) { //check if we're too close to another city bool tooclose = false; for (int i = 0; i < tile->Cities.size(); i++) { if (glm::length(vec2(tile->Cities[i].x - x, tile->Cities[i].y - y)) < cityspacing) tooclose = true; } if (!tooclose) { if (abs(cells[(y - citysize / 2)*TILE_SIZE + x - citysize / 2].height - cells[(y + citysize / 2)*TILE_SIZE + x - citysize / 2].height) < heighttolerance && abs(cells[(y - citysize / 2)*TILE_SIZE + x + citysize / 2].height - cells[(y + citysize / 2)*TILE_SIZE + x + citysize / 2].height) < heighttolerance && abs(cells[(y + citysize / 2)*TILE_SIZE + x + citysize / 2].height - cells[(y + citysize / 2)*TILE_SIZE + x - citysize / 2].height) < heighttolerance && abs(cells[(y - citysize / 2)*TILE_SIZE + x + citysize / 2].height - cells[(y - citysize / 2)*TILE_SIZE + x - citysize / 2].height) < heighttolerance ) { //make some cities tile->Cities.push_back(vec3(x, y, 0)); cout << "CITY PLACED AT:" << x << " , " << y << endl; } } } } } //Flatten Terrain for (int i = 0; i < tile->Cities.size(); i++) { vec3 pos = tile->Cities[i]; for (int y = -citysize / 2; y < citysize / 2; y++) { for (int x = -citysize / 2; x < citysize / 2; x++) { cells[int((pos.y + y)*TILE_SIZE + pos.x + x)].height = cells[int((pos.y)*TILE_SIZE + pos.x)].height; } } } // TODO : Blur city edges /* for (int i = 0; i < tile->Cities.size(); i++) { vec3 pos = tile->Cities[i]; //walk along the edge, for each edge walk outward and normalize for (int y = pos.y - citysize/2; y < pos.y + citysize/2; y++) { //left analysis[y*TILE_SIZE + TILE_SIZE - 1] = 500; //right analysis[y*TILE_SIZE + TILE_SIZE - 1] = 500; } for (int x = pos.x - citysize / 2; x < pos.x + citysize / 2; x++) { //top analysis[0 * TILE_SIZE + x] = 500; //bottom analysis[(TILE_SIZE - 1)*TILE_SIZE + x] = 500; } } */ delete [] analysis; } void CityGen::GenerateCities(GameTile * tile) { generatecitylocations(tile); for (int i = 0; i < tile->Cities.size(); i++) { construct_city(tile, tile->Cities[i]); } tile->UpdateTileSection(0, 0, TILE_SIZE, TILE_SIZE); } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2014 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 "cppparser.h" #include "cppdom.h" #include "cppobjfactory.h" #include "string-utils.h" #include <algorithm> #include <fstream> #include <vector> std::set<std::string> gMacroNames = {"DECLARE_MESSAGE_MAP", "DECLARE_DYNAMIC", "ACPL_DECLARE_MEMBERS", "DBSYMUTL_MAKE_GETSYMBOLID_FUNCTION", "DBSYMUTL_MAKE_HASSYMBOLID_FUNCTION", "DBSYMUTL_MAKE_HASSYMBOLNAME_FUNCTION"}; std::set<std::string> gKnownApiDecorNames = {"ODRX_ABSTRACT", "FIRSTDLL_EXPORT", "GE_DLLEXPIMPORT", "ADESK_NO_VTABLE"}; extern CppCompound* parseStream(char* stm, size_t stmSize); CppObjFactory* gObjFactory = nullptr; CppParser::CppParser(CppObjFactory* objFactory) : objFactory_(objFactory) { if (objFactory_ == nullptr) objFactory_ = new CppObjFactory; } void CppParser::addKnownMacro(std::string knownMacro) { gMacroNames.insert(std::move(knownMacro)); } void CppParser::addKnownMacros(const std::vector<std::string>& knownMacros) { for (auto& macro : knownMacros) gMacroNames.insert(macro); } void CppParser::addKnownApiDecor(std::string knownApiDecor) { gKnownApiDecorNames.insert(std::move(knownApiDecor)); } void CppParser::addKnownApiDecors(const std::vector<std::string>& knownApiDecor) { for (auto& apiDecor : knownApiDecor) gKnownApiDecorNames.insert(apiDecor); } CppCompound* CppParser::parseFile(const char* filename) { auto stm = readFile(filename); CppCompound* cppCompound = parseStream(stm.data(), stm.size()); if (cppCompound == NULL) return cppCompound; cppCompound->name_ = filename; return cppCompound; } CppCompound* CppParser::parseStream(char* stm, size_t stmSize) { if (stm == nullptr || stmSize == 0) return nullptr; gObjFactory = objFactory_; return ::parseStream(stm, stmSize); } CppProgram* CppParser::loadProgram(const char* szInputPath) { auto program = new CppProgram; loadProgram(szInputPath, *program); return program; } static void collectFiles(const bfs::path& path, std::vector<std::string>& files) { if (bfs::is_regular_file(path)) { files.push_back(path.string()); } else if (bfs::is_directory(path)) { for (bfs::directory_iterator dirItr(path); dirItr != bfs::directory_iterator(); ++dirItr) { collectFiles(*dirItr, files); } } } static std::vector<std::string> collectFiles(const bfs::path& path) { std::vector<std::string> files; collectFiles(path, files); if (!files.empty()) std::sort(files.begin(), files.end()); return files; } void CppParser::loadProgram(const bfs::path& path, CppProgram& program) { auto files = collectFiles(path); for (const auto& f : files) { auto cppDom = parseFile(f.c_str()); if (cppDom) program.addCppDom(cppDom); } } CppParser::ByteArray CppParser::readFile(const char* filename) { ByteArray contents; std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); size_t size = in.tellg(); contents.resize(size + 3); // For adding last 2 nulls and a new line. in.seekg(0, std::ios::beg); in.read(&contents[0], size); in.close(); auto len = stripChar(contents.data(), size, '\r'); assert(len <= size); contents.resize(len+3); contents[len] = '\n'; contents[len+1] = '\0'; contents[len+2] = '\0'; } return (contents); } <commit_msg>Adding a known arx macro.<commit_after>/* The MIT License (MIT) Copyright (c) 2014 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 "cppparser.h" #include "cppdom.h" #include "cppobjfactory.h" #include "string-utils.h" #include <algorithm> #include <fstream> #include <vector> std::set<std::string> gMacroNames = {"DECLARE_MESSAGE_MAP", "DECLARE_DYNAMIC", "ACPL_DECLARE_MEMBERS", "DBSYMUTL_MAKE_GETSYMBOLID_FUNCTION", "DBSYMUTL_MAKE_HASSYMBOLID_FUNCTION", "DBSYMUTL_MAKE_HASSYMBOLNAME_FUNCTION"}; std::set<std::string> gKnownApiDecorNames = {"ODRX_ABSTRACT", "FIRSTDLL_EXPORT", "GE_DLLEXPIMPORT", "ADESK_NO_VTABLE", "ACDBCORE2D_PORT", "ACBASE_PORT"}; extern CppCompound* parseStream(char* stm, size_t stmSize); CppObjFactory* gObjFactory = nullptr; CppParser::CppParser(CppObjFactory* objFactory) : objFactory_(objFactory) { if (objFactory_ == nullptr) objFactory_ = new CppObjFactory; } void CppParser::addKnownMacro(std::string knownMacro) { gMacroNames.insert(std::move(knownMacro)); } void CppParser::addKnownMacros(const std::vector<std::string>& knownMacros) { for (auto& macro : knownMacros) gMacroNames.insert(macro); } void CppParser::addKnownApiDecor(std::string knownApiDecor) { gKnownApiDecorNames.insert(std::move(knownApiDecor)); } void CppParser::addKnownApiDecors(const std::vector<std::string>& knownApiDecor) { for (auto& apiDecor : knownApiDecor) gKnownApiDecorNames.insert(apiDecor); } CppCompound* CppParser::parseFile(const char* filename) { auto stm = readFile(filename); CppCompound* cppCompound = parseStream(stm.data(), stm.size()); if (cppCompound == NULL) return cppCompound; cppCompound->name_ = filename; return cppCompound; } CppCompound* CppParser::parseStream(char* stm, size_t stmSize) { if (stm == nullptr || stmSize == 0) return nullptr; gObjFactory = objFactory_; return ::parseStream(stm, stmSize); } CppProgram* CppParser::loadProgram(const char* szInputPath) { auto program = new CppProgram; loadProgram(szInputPath, *program); return program; } static void collectFiles(const bfs::path& path, std::vector<std::string>& files) { if (bfs::is_regular_file(path)) { files.push_back(path.string()); } else if (bfs::is_directory(path)) { for (bfs::directory_iterator dirItr(path); dirItr != bfs::directory_iterator(); ++dirItr) { collectFiles(*dirItr, files); } } } static std::vector<std::string> collectFiles(const bfs::path& path) { std::vector<std::string> files; collectFiles(path, files); if (!files.empty()) std::sort(files.begin(), files.end()); return files; } void CppParser::loadProgram(const bfs::path& path, CppProgram& program) { auto files = collectFiles(path); for (const auto& f : files) { auto cppDom = parseFile(f.c_str()); if (cppDom) program.addCppDom(cppDom); } } CppParser::ByteArray CppParser::readFile(const char* filename) { ByteArray contents; std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); size_t size = in.tellg(); contents.resize(size + 3); // For adding last 2 nulls and a new line. in.seekg(0, std::ios::beg); in.read(&contents[0], size); in.close(); auto len = stripChar(contents.data(), size, '\r'); assert(len <= size); contents.resize(len + 3); contents[len] = '\n'; contents[len + 1] = '\0'; contents[len + 2] = '\0'; } return (contents); } <|endoftext|>
<commit_before>/* В языке С++ базовая работа с символами и строками аналогична C. Символы заключаются в одинарные кавычки 'a', '8', '&', ' ' Фактически, каждый символ представляет из себя некоторый знак: буквы, цифра, плюс, минус и прочие. Однако, в C/C++ некоторые символы состоят из нескольких знаков. Как пример, набор слеш-последовательностей: '\n' - символ новой строки. Сам символ - один, но представлен двумя знаками '\t' - символ табуляции. Аналогичный случай. Для работы с символами в C используется тип char char symb1 = '4', symb2 = 'a'; Для вывода символа на консоль осуществляется так: cout << symb1; // вывести переменную типа char на экран или так: cout.put(symb1); Получить символ с стандартного потока ввода можно так: cin >> symb2; // считать первый введённый символ в переменную symb2 или так: cin.get(symb2); и даже так: symb2 = cin.get(); // правда тут cin.get() возращает целое число типа int Каждому символу сопостовляется внутренний код - целое число. Поэтому с переменными типа char можно обращаться как с целочисленными величинами. Более того, порядок кодов символов неизменен, для примера - смотрите таблицу ASCII кодов в пособии. Из-за этого, символы могут принимать участие в арифметических операциях и операциях сравнения: char sym = '1'; sym += 1; // увеличит код символа на 1. В соответствии с таблицей ASCII // в переменной sym будет находится символ двойки: '2'; if ( sym > '5' ) { // сравниваем символы // не выполнится, потому что '2' раньше '5' } else { cout << "Else branch"; } int code = int( sym ); // получение целочисленного кода определённого символа с помощью приведения типов if ( sym >= '0' && sym <= '9' ) { // проверяем, что в переменной sym находится символ цифры ... } ************************************************************************************ Под строкой понимается набор символов, заключённых в двойные кавычки: "A simple string" "89983 - something important" "abcdefg" Для строк не введён специальный тип. Для их хранения используется массив типа char: char str[] = "Str1"; // В C++ такие строки называют "строками в стиле C". Выше определяется массив str типа char. Ему присваивается строка "Str1". Из-за особенностей массивов в C было принято, что последним символом должен обязательно идти символ конца строки - '\0'. Таким образом, str представляется в виде массива из 5 символов: ['S', 't', 'r', '1', '\0'] При том, что в исходной строке - всего 4 символа. Для C наличие символа конца строки очень важно, все функции обработки строк предполагают, что переданные им массивы будут содержать в себе этот символ последним элементом. Определение str может быть сделано в явном виде как обычный массив: char str[] = {'S', 't', 'r', '1', '\0'}; При этом, нельзя присваивать строку в двойных кавычках уже объявленным массивам: char word[10]; word = "true"; //Ошибка! Вывести строку на экран можно так: char word[] = "word"; cout << word; Ввод строки: char str[30]; cout << "Enter string:" << endl; cin.getline(str, 30); // 30 - размер массива. Максимально будет считано 29 символов и последним добавлен символ конца строки - '\0' // Если было введено менее 30 символов, то все они помещаются в sentence // и после последнего символа помещается символ конца строки. Но // в этом случае в строку попадает и символ переноса строки - '\n' Выше указанные функции ввода-вывода опеределены в <iostream> Также имеется набор функций из стандартной библиотеки C для работы со строками, определённых в <cstring>. Например: // Определяем строку, содержащую 32 символа. char str[] = "a_long_long_long_word_as_example"; // Размер массива str в данном случае - 33 символа // Функция strlen возращает количество символов в строке // без учёта символа конца строки ('\0') cout << "The size of str is " << strlen(str) << endl; // будет напечатано: "The size of str is 32" Другие примеры - непосредственно в программе. */ #include <iostream> #include <cstring> // strlen и другие функции работы со строками using namespace std; void print_eng_letters() { char sym = 'a'; // объявляем переменную типа char и присваиваем ей значение cout << "English lowercase letters:" << endl; // печатаем все цифры while ( sym <= 'z' ) { cout.put(sym); ++sym; // используем операцию инкремента для увеличения кода символа на единицу // тоже самое, что и sym += 1 } cout << endl; } int main() { print_eng_letters(); char letter = 'W'; // Печатаем букву 'W' и её целочисленный код cout << "The symbol and the code: " << letter << " : " << int( letter ) << endl; // Объявляем и инициализируем строку char first_str[] = "A very very important sentence"; // вычисляем количество элементов в массиве first_str unsigned int char_array_size = sizeof(first_str) / sizeof(first_str[0]); // Печатаем строку, её длину с помощью функции strlen, и длину массива first_arr // Последние два значения будут различаться на единицу. cout << "The string: " << first_str << endl; cout << "String size: " << strlen(first_str) << endl; cout << "Array size: " << char_array_size << endl << endl; /* Демонстрация функции strcmp из <string.h> Данная функция принимает два аргумента - две строки - и сравнивает из посимвольно. Возращает 0 : если все символы совпадают значение меньше 0 : если код первого несовпадающего символа в первой строке меньше кода символа во второй строке значение больше 0 : если код первого несовпадающего символа в первой строке больше кода символа во второй строке */ char secret_str[] = "just cat"; // задаём строку, при вводе которой будет прерван бесконечный цикл char buffer[80]; // массив для хранения введённой пользователем строки do { cout << "Guess secret string? "; // просим угадать выше определённую строку cin.getline(buffer, 80); // считываем введённую строку } while ( strcmp(secret_str, buffer) != 0 ); // проверяем результат функции сравнения строк cout << "Correct answer!" << endl; /* Пример функция strcpy и strncat из string.h */ char str1[20], str2[20], str3[] = "or not to be"; strcpy(str1, "To be "); // копируем вторую строку в первую. Даже если в str1 были какие-то символы, они замещаются // символами из второй строки strcpy(str2, str3); // копируем str3 в str2 strncat(str1, str2, 6); // добавляем первые 6 символов из str2 в str1 cout << str1; // печатаем ""To be or not" return 0; } <commit_msg>fix header name in base_strings_characters.cpp<commit_after>/* В языке С++ базовая работа с символами и строками аналогична C. Символы заключаются в одинарные кавычки 'a', '8', '&', ' ' Фактически, каждый символ представляет из себя некоторый знак: буквы, цифра, плюс, минус и прочие. Однако, в C/C++ некоторые символы состоят из нескольких знаков. Как пример, набор слеш-последовательностей: '\n' - символ новой строки. Сам символ - один, но представлен двумя знаками '\t' - символ табуляции. Аналогичный случай. Для работы с символами в C используется тип char char symb1 = '4', symb2 = 'a'; Для вывода символа на консоль осуществляется так: cout << symb1; // вывести переменную типа char на экран или так: cout.put(symb1); Получить символ с стандартного потока ввода можно так: cin >> symb2; // считать первый введённый символ в переменную symb2 или так: cin.get(symb2); и даже так: symb2 = cin.get(); // правда тут cin.get() возращает целое число типа int Каждому символу сопостовляется внутренний код - целое число. Поэтому с переменными типа char можно обращаться как с целочисленными величинами. Более того, порядок кодов символов неизменен, для примера - смотрите таблицу ASCII кодов в пособии. Из-за этого, символы могут принимать участие в арифметических операциях и операциях сравнения: char sym = '1'; sym += 1; // увеличит код символа на 1. В соответствии с таблицей ASCII // в переменной sym будет находится символ двойки: '2'; if ( sym > '5' ) { // сравниваем символы // не выполнится, потому что '2' раньше '5' } else { cout << "Else branch"; } int code = int( sym ); // получение целочисленного кода определённого символа с помощью приведения типов if ( sym >= '0' && sym <= '9' ) { // проверяем, что в переменной sym находится символ цифры ... } ************************************************************************************ Под строкой понимается набор символов, заключённых в двойные кавычки: "A simple string" "89983 - something important" "abcdefg" Для строк не введён специальный тип. Для их хранения используется массив типа char: char str[] = "Str1"; // В C++ такие строки называют "строками в стиле C". Выше определяется массив str типа char. Ему присваивается строка "Str1". Из-за особенностей массивов в C было принято, что последним символом должен обязательно идти символ конца строки - '\0'. Таким образом, str представляется в виде массива из 5 символов: ['S', 't', 'r', '1', '\0'] При том, что в исходной строке - всего 4 символа. Для C наличие символа конца строки очень важно, все функции обработки строк предполагают, что переданные им массивы будут содержать в себе этот символ последним элементом. Определение str может быть сделано в явном виде как обычный массив: char str[] = {'S', 't', 'r', '1', '\0'}; При этом, нельзя присваивать строку в двойных кавычках уже объявленным массивам: char word[10]; word = "true"; //Ошибка! Вывести строку на экран можно так: char word[] = "word"; cout << word; Ввод строки: char str[30]; cout << "Enter string:" << endl; cin.getline(str, 30); // 30 - размер массива. Максимально будет считано 29 символов и последним добавлен символ конца строки - '\0' // Если было введено менее 30 символов, то все они помещаются в sentence // и после последнего символа помещается символ конца строки. Но // в этом случае в строку попадает и символ переноса строки - '\n' Выше указанные функции ввода-вывода опеределены в <iostream> Также имеется набор функций из стандартной библиотеки C для работы со строками, определённых в <cstring>. Например: // Определяем строку, содержащую 32 символа. char str[] = "a_long_long_long_word_as_example"; // Размер массива str в данном случае - 33 символа // Функция strlen возращает количество символов в строке // без учёта символа конца строки ('\0') cout << "The size of str is " << strlen(str) << endl; // будет напечатано: "The size of str is 32" Другие примеры - непосредственно в программе. */ #include <iostream> #include <cstring> // strlen и другие функции работы со строками using namespace std; void print_eng_letters() { char sym = 'a'; // объявляем переменную типа char и присваиваем ей значение cout << "English lowercase letters:" << endl; // печатаем все цифры while ( sym <= 'z' ) { cout.put(sym); ++sym; // используем операцию инкремента для увеличения кода символа на единицу // тоже самое, что и sym += 1 } cout << endl; } int main() { print_eng_letters(); char letter = 'W'; // Печатаем букву 'W' и её целочисленный код cout << "The symbol and the code: " << letter << " : " << int( letter ) << endl; // Объявляем и инициализируем строку char first_str[] = "A very very important sentence"; // вычисляем количество элементов в массиве first_str unsigned int char_array_size = sizeof(first_str) / sizeof(first_str[0]); // Печатаем строку, её длину с помощью функции strlen, и длину массива first_arr // Последние два значения будут различаться на единицу. cout << "The string: " << first_str << endl; cout << "String size: " << strlen(first_str) << endl; cout << "Array size: " << char_array_size << endl << endl; /* Демонстрация функции strcmp из <cstring> Данная функция принимает два аргумента - две строки - и сравнивает из посимвольно. Возращает 0 : если все символы совпадают значение меньше 0 : если код первого несовпадающего символа в первой строке меньше кода символа во второй строке значение больше 0 : если код первого несовпадающего символа в первой строке больше кода символа во второй строке */ char secret_str[] = "just cat"; // задаём строку, при вводе которой будет прерван бесконечный цикл char buffer[80]; // массив для хранения введённой пользователем строки do { cout << "Guess secret string? "; // просим угадать выше определённую строку cin.getline(buffer, 80); // считываем введённую строку } while ( strcmp(secret_str, buffer) != 0 ); // проверяем результат функции сравнения строк cout << "Correct answer!" << endl; /* Пример функция strcpy и strncat из <cstring> */ char str1[20], str2[20], str3[] = "or not to be"; strcpy(str1, "To be "); // копируем вторую строку в первую. Даже если в str1 были какие-то символы, они замещаются // символами из второй строки strcpy(str2, str3); // копируем str3 в str2 strncat(str1, str2, 6); // добавляем первые 6 символов из str2 в str1 cout << str1; // печатаем ""To be or not" return 0; } <|endoftext|>
<commit_before>#ifndef __KD_TREE_HPP_ #define __KD_TREE_HPP_ #include <string> #include <iostream> #include <vector> //______________________________________________________________________________ class Point { public : // constructors Point(); Point(double x, double y, double z); Point(const Point& other); bool operator==(const Point& other) const; virtual ~Point(); // getters double X() const {return fX;} double Y() const {return fY;} double Z() const {return fZ;} // setters void SetX(double x){fX=x;} void SetY(double y){fY=y;} void SetZ(double z){fZ=z;} std::string ToString() const; double DistanceTo(const Point& point) const; double SquaredDistanceTo(const Point& point) const; private: double fX,fY,fZ; }; class sortX { public: bool operator() (Point *a, Point *b) { return ((*a).X() < (*b).X());} }; class sortY { public: bool operator() (Point *a, Point *b) { return ((*a).Y() < (*b).Y());} }; class sortZ { public: bool operator() (Point *a, Point *b) { return ((*a).Z() < (*b).Z());} }; //______________________________________________________________________________ class KDTreeNode { public: KDTreeNode(); KDTreeNode(const KDTreeNode& other); virtual ~KDTreeNode(); void SetDepth(int depth) {fDepth = depth;} void SetPoint(Point* otherPoint) {fPoint = otherPoint;} void SetParent(KDTreeNode* other) {fParent = other;} void SetLeftChild(KDTreeNode* otherLeft) {fLeft = otherLeft;} void SetRightChild(KDTreeNode* otherRight) {fRight = otherRight;} int GetDepth() const {return fDepth;} const Point& GetPoint() const {return *fPoint;} const KDTreeNode* GetParent() const {return fParent;} const KDTreeNode* GetLeftChild() const {return fLeft;} const KDTreeNode* GetRightChild() const {return fRight;} const KDTreeNode& FindNodeContaining(const Point& point) const; const KDTreeNode& CheckParentForCloserNodes(const Point& point, const KDTreeNode& best) const; void OutputGraphViz(std::ostream& out) const; private: int fDepth; Point* fPoint; KDTreeNode *fParent; KDTreeNode *fLeft; KDTreeNode *fRight; bool CheckOtherSideofSplittingPlane(const Point& point, const double radius) const; const KDTreeNode& SearchChildren(const Point& point, const KDTreeNode& currentBest) const; bool IsCloserToPoint(const Point& point, const KDTreeNode& currentBest) const; }; //______________________________________________________________________________ class KDTree { public: KDTree(std::vector<Point*>& pointList); KDTree(const KDTree& other); virtual ~KDTree(); const Point& NearestNeighbour(const Point& point) const; void OutputGraphViz(std::ostream& out) const; private: KDTreeNode *fRoot; KDTreeNode* BuildNode(std::vector<Point*>& pointList, KDTreeNode* parent, int depth=0); }; #endif <commit_msg>Levelled up an int to unsigned int<commit_after>#ifndef __KD_TREE_HPP_ #define __KD_TREE_HPP_ #include <string> #include <iostream> #include <vector> //______________________________________________________________________________ class Point { public : // constructors Point(); Point(double x, double y, double z); Point(const Point& other); bool operator==(const Point& other) const; virtual ~Point(); // getters double X() const {return fX;} double Y() const {return fY;} double Z() const {return fZ;} // setters void SetX(double x){fX=x;} void SetY(double y){fY=y;} void SetZ(double z){fZ=z;} std::string ToString() const; double DistanceTo(const Point& point) const; double SquaredDistanceTo(const Point& point) const; private: double fX,fY,fZ; }; class sortX { public: bool operator() (Point *a, Point *b) { return ((*a).X() < (*b).X());} }; class sortY { public: bool operator() (Point *a, Point *b) { return ((*a).Y() < (*b).Y());} }; class sortZ { public: bool operator() (Point *a, Point *b) { return ((*a).Z() < (*b).Z());} }; //______________________________________________________________________________ class KDTreeNode { public: KDTreeNode(); KDTreeNode(const KDTreeNode& other); virtual ~KDTreeNode(); void SetDepth(int depth) {fDepth = depth;} void SetPoint(Point* otherPoint) {fPoint = otherPoint;} void SetParent(KDTreeNode* other) {fParent = other;} void SetLeftChild(KDTreeNode* otherLeft) {fLeft = otherLeft;} void SetRightChild(KDTreeNode* otherRight) {fRight = otherRight;} int GetDepth() const {return fDepth;} const Point& GetPoint() const {return *fPoint;} const KDTreeNode* GetParent() const {return fParent;} const KDTreeNode* GetLeftChild() const {return fLeft;} const KDTreeNode* GetRightChild() const {return fRight;} const KDTreeNode& FindNodeContaining(const Point& point) const; const KDTreeNode& CheckParentForCloserNodes(const Point& point, const KDTreeNode& best) const; void OutputGraphViz(std::ostream& out) const; private: unsigned int fDepth; Point* fPoint; KDTreeNode *fParent; KDTreeNode *fLeft; KDTreeNode *fRight; bool CheckOtherSideofSplittingPlane(const Point& point, const double radius) const; const KDTreeNode& SearchChildren(const Point& point, const KDTreeNode& currentBest) const; bool IsCloserToPoint(const Point& point, const KDTreeNode& currentBest) const; }; //______________________________________________________________________________ class KDTree { public: KDTree(std::vector<Point*>& pointList); KDTree(const KDTree& other); virtual ~KDTree(); const Point& NearestNeighbour(const Point& point) const; void OutputGraphViz(std::ostream& out) const; private: KDTreeNode *fRoot; KDTreeNode* BuildNode(std::vector<Point*>& pointList, KDTreeNode* parent, int depth=0); }; #endif <|endoftext|>
<commit_before>#include <seqan/basic.h> #include <seqan/seq_io.h> #include <seqan/sequence.h> using namespace seqan; int main(int argc, char ** argv) { CharString path = SEQAN_TEMP_FILENAME(); append(path, ".fa"); // Open file and check for errors. SequenceStream seqStream(toCString(path), SequenceStream::WRITE); if (!isGood(seqStream)) { std::cerr << "ERROR: Could not open " << path << " for writing.\n"; return 1; } // Write two sequences to the file. if (writeRecord(seqStream, "one", "CGAT") != 0 || writeRecord(seqStream, "two", "ASDF") != 0) { std::cerr << "ERROR: Problem writing to " << path << "\n"; return 1; } return 0; } <commit_msg>[INTERNAL] SequenceFile: updated writing demo<commit_after>#include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/seq_io.h> using namespace seqan; int main(int argc, char ** argv) { CharString path = SEQAN_TEMP_FILENAME(); append(path, ".fa"); SequenceFile<Output> file(toCString(path)); CharString meta = "chr1"; CharString seq = "ACGT"; write(file, meta, seq); close(file); return 0; } <|endoftext|>
<commit_before>#ifndef SELECTION_BOILERPLATE_HPP #define SELECTION_BOILERPLATE_HPP #include <atomic> #include <libnest2d/libnest2d.hpp> namespace libnest2d { namespace selections { template<class RawShape> class SelectionBoilerplate { public: using ShapeType = RawShape; using Item = _Item<RawShape>; using ItemGroup = _ItemGroup<RawShape>; using PackGroup = _PackGroup<RawShape>; inline const PackGroup& getResult() const { return packed_bins_; } inline void progressIndicator(ProgressFunction fn) { progress_ = fn; } inline void stopCondition(StopCondition cond) { stopcond_ = cond; } inline void clear() { packed_bins_.clear(); } protected: template<class Placer, class Container, class Bin, class PCfg> void remove_unpackable_items(Container &c, const Bin &bin, const PCfg& pcfg) { // Safety test: try to pack each item into an empty bin. If it fails // then it should be removed from the list auto it = c.begin(); while (it != c.end() && !stopcond_()) { Placer p{bin}; p.configure(pcfg); const Item& itm = *it; Item cpy{itm}; if (!p.pack(cpy)) it = c.erase(it); else it++; } } PackGroup packed_bins_; ProgressFunction progress_ = [](unsigned){}; StopCondition stopcond_ = [](){ return false; }; }; } } #endif // SELECTION_BOILERPLATE_HPP <commit_msg>Fix arrange crash with ASAN<commit_after>#ifndef SELECTION_BOILERPLATE_HPP #define SELECTION_BOILERPLATE_HPP #include <atomic> #include <libnest2d/libnest2d.hpp> namespace libnest2d { namespace selections { template<class RawShape> class SelectionBoilerplate { public: using ShapeType = RawShape; using Item = _Item<RawShape>; using ItemGroup = _ItemGroup<RawShape>; using PackGroup = _PackGroup<RawShape>; inline const PackGroup& getResult() const { return packed_bins_; } inline void progressIndicator(ProgressFunction fn) { progress_ = fn; } inline void stopCondition(StopCondition cond) { stopcond_ = cond; } inline void clear() { packed_bins_.clear(); } protected: template<class Placer, class Container, class Bin, class PCfg> void remove_unpackable_items(Container &c, const Bin &bin, const PCfg& pcfg) { // Safety test: try to pack each item into an empty bin. If it fails // then it should be removed from the list auto it = c.begin(); while (it != c.end() && !stopcond_()) { // WARNING: The copy of itm needs to be created before Placer. // Placer is working with references and its destructor still // manipulates the item this is why the order of stack creation // matters here. const Item& itm = *it; Item cpy{itm}; Placer p{bin}; p.configure(pcfg); if (!p.pack(cpy)) it = c.erase(it); else it++; } } PackGroup packed_bins_; ProgressFunction progress_ = [](unsigned){}; StopCondition stopcond_ = [](){ return false; }; }; } } #endif // SELECTION_BOILERPLATE_HPP <|endoftext|>
<commit_before>//===---- LiveRangeCalc.cpp - Calculate live ranges -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implementation of the LiveRangeCalc class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "LiveRangeCalc.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineRegisterInfo.h" using namespace llvm; void LiveRangeCalc::reset(const MachineFunction *MF, SlotIndexes *SI, MachineDominatorTree *MDT, VNInfo::Allocator *VNIA) { MRI = &MF->getRegInfo(); Indexes = SI; DomTree = MDT; Alloc = VNIA; unsigned N = MF->getNumBlockIDs(); Seen.clear(); Seen.resize(N); LiveOut.resize(N); LiveIn.clear(); } void LiveRangeCalc::createDeadDefs(LiveInterval *LI, unsigned Reg) { assert(MRI && Indexes && "call reset() first"); // Visit all def operands. If the same instruction has multiple defs of Reg, // LI->createDeadDef() will deduplicate. for (MachineRegisterInfo::def_iterator I = MRI->def_begin(Reg), E = MRI->def_end(); I != E; ++I) { const MachineInstr *MI = &*I; // Find the corresponding slot index. SlotIndex Idx; if (MI->isPHI()) // PHI defs begin at the basic block start index. Idx = Indexes->getMBBStartIdx(MI->getParent()); else // Instructions are either normal 'r', or early clobber 'e'. Idx = Indexes->getInstructionIndex(MI) .getRegSlot(I.getOperand().isEarlyClobber()); // Create the def in LI. This may find an existing def. LI->createDeadDef(Idx, *Alloc); } } void LiveRangeCalc::extendToUses(LiveInterval *LI, unsigned Reg) { assert(MRI && Indexes && "call reset() first"); // Visit all operands that read Reg. This may include partial defs. for (MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(Reg), E = MRI->reg_nodbg_end(); I != E; ++I) { const MachineOperand &MO = I.getOperand(); if (!MO.readsReg()) continue; // MI is reading Reg. We may have visited MI before if it happens to be // reading Reg multiple times. That is OK, extend() is idempotent. const MachineInstr *MI = &*I; // Find the SlotIndex being read. SlotIndex Idx; if (MI->isPHI()) { assert(!MO.isDef() && "Cannot handle PHI def of partial register."); // PHI operands are paired: (Reg, PredMBB). // Extend the live range to be live-out from PredMBB. Idx = Indexes->getMBBEndIdx(MI->getOperand(I.getOperandNo()+1).getMBB()); } else { // This is a normal instruction. Idx = Indexes->getInstructionIndex(MI).getRegSlot(); // Check for early-clobber redefs. unsigned DefIdx; if (MO.isDef()) { if (MO.isEarlyClobber()) Idx = Idx.getRegSlot(true); } else if (MI->isRegTiedToDefOperand(I.getOperandNo(), &DefIdx)) { // FIXME: This would be a lot easier if tied early-clobber uses also // had an early-clobber flag. if (MI->getOperand(DefIdx).isEarlyClobber()) Idx = Idx.getRegSlot(true); } } extend(LI, Idx, Reg); } } // Transfer information from the LiveIn vector to the live ranges. void LiveRangeCalc::updateLiveIns(VNInfo *OverrideVNI) { for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(), E = LiveIn.end(); I != E; ++I) { if (!I->DomNode) continue; MachineBasicBlock *MBB = I->DomNode->getBlock(); VNInfo *VNI = OverrideVNI ? OverrideVNI : I->Value; assert(VNI && "No live-in value found"); SlotIndex Start, End; tie(Start, End) = Indexes->getMBBRange(MBB); if (I->Kill.isValid()) I->LI->addRange(LiveRange(Start, I->Kill, VNI)); else { I->LI->addRange(LiveRange(Start, End, VNI)); // The value is live-through, update LiveOut as well. Defer the Domtree // lookup until it is needed. assert(Seen.test(MBB->getNumber())); LiveOut[MBB] = LiveOutPair(VNI, (MachineDomTreeNode *)0); } } LiveIn.clear(); } void LiveRangeCalc::extend(LiveInterval *LI, SlotIndex Kill, unsigned PhysReg) { assert(LI && "Missing live range"); assert(Kill.isValid() && "Invalid SlotIndex"); assert(Indexes && "Missing SlotIndexes"); assert(DomTree && "Missing dominator tree"); MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot()); assert(KillMBB && "No MBB at Kill"); // Is there a def in the same MBB we can extend? if (LI->extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill)) return; // Find the single reaching def, or determine if Kill is jointly dominated by // multiple values, and we may need to create even more phi-defs to preserve // VNInfo SSA form. Perform a search for all predecessor blocks where we // know the dominating VNInfo. VNInfo *VNI = findReachingDefs(LI, KillMBB, Kill, PhysReg); // When there were multiple different values, we may need new PHIs. if (!VNI) updateSSA(); updateLiveIns(VNI); } // This function is called by a client after using the low-level API to add // live-out and live-in blocks. The unique value optimization is not // available, SplitEditor::transferValues handles that case directly anyway. void LiveRangeCalc::calculateValues() { assert(Indexes && "Missing SlotIndexes"); assert(DomTree && "Missing dominator tree"); updateSSA(); updateLiveIns(0); } VNInfo *LiveRangeCalc::findReachingDefs(LiveInterval *LI, MachineBasicBlock *KillMBB, SlotIndex Kill, unsigned PhysReg) { // Blocks where LI should be live-in. SmallVector<MachineBasicBlock*, 16> WorkList(1, KillMBB); // Remember if we have seen more than one value. bool UniqueVNI = true; VNInfo *TheVNI = 0; // Using Seen as a visited set, perform a BFS for all reaching defs. for (unsigned i = 0; i != WorkList.size(); ++i) { MachineBasicBlock *MBB = WorkList[i]; #ifndef NDEBUG if (MBB->pred_empty()) { MBB->getParent()->verify(); llvm_unreachable("Use not jointly dominated by defs."); } if (TargetRegisterInfo::isPhysicalRegister(PhysReg) && !MBB->isLiveIn(PhysReg)) { MBB->getParent()->verify(); errs() << "The register needs to be live in to BB#" << MBB->getNumber() << ", but is missing from the live-in list.\n"; llvm_unreachable("Invalid global physical register"); } #endif for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) { MachineBasicBlock *Pred = *PI; // Is this a known live-out block? if (Seen.test(Pred->getNumber())) { if (VNInfo *VNI = LiveOut[Pred].first) { if (TheVNI && TheVNI != VNI) UniqueVNI = false; TheVNI = VNI; } continue; } SlotIndex Start, End; tie(Start, End) = Indexes->getMBBRange(Pred); // First time we see Pred. Try to determine the live-out value, but set // it as null if Pred is live-through with an unknown value. VNInfo *VNI = LI->extendInBlock(Start, End); setLiveOutValue(Pred, VNI); if (VNI) { if (TheVNI && TheVNI != VNI) UniqueVNI = false; TheVNI = VNI; continue; } // No, we need a live-in value for Pred as well if (Pred != KillMBB) WorkList.push_back(Pred); else // Loopback to KillMBB, so value is really live through. Kill = SlotIndex(); } } // Transfer WorkList to LiveInBlocks in reverse order. // This ordering works best with updateSSA(). LiveIn.clear(); LiveIn.reserve(WorkList.size()); while(!WorkList.empty()) addLiveInBlock(LI, DomTree->getNode(WorkList.pop_back_val())); // The kill block may not be live-through. assert(LiveIn.back().DomNode->getBlock() == KillMBB); LiveIn.back().Kill = Kill; return UniqueVNI ? TheVNI : 0; } // This is essentially the same iterative algorithm that SSAUpdater uses, // except we already have a dominator tree, so we don't have to recompute it. void LiveRangeCalc::updateSSA() { assert(Indexes && "Missing SlotIndexes"); assert(DomTree && "Missing dominator tree"); // Interate until convergence. unsigned Changes; do { Changes = 0; // Propagate live-out values down the dominator tree, inserting phi-defs // when necessary. for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(), E = LiveIn.end(); I != E; ++I) { MachineDomTreeNode *Node = I->DomNode; // Skip block if the live-in value has already been determined. if (!Node) continue; MachineBasicBlock *MBB = Node->getBlock(); MachineDomTreeNode *IDom = Node->getIDom(); LiveOutPair IDomValue; // We need a live-in value to a block with no immediate dominator? // This is probably an unreachable block that has survived somehow. bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber()); // IDom dominates all of our predecessors, but it may not be their // immediate dominator. Check if any of them have live-out values that are // properly dominated by IDom. If so, we need a phi-def here. if (!needPHI) { IDomValue = LiveOut[IDom->getBlock()]; // Cache the DomTree node that defined the value. if (IDomValue.first && !IDomValue.second) LiveOut[IDom->getBlock()].second = IDomValue.second = DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def)); for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) { LiveOutPair &Value = LiveOut[*PI]; if (!Value.first || Value.first == IDomValue.first) continue; // Cache the DomTree node that defined the value. if (!Value.second) Value.second = DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def)); // This predecessor is carrying something other than IDomValue. // It could be because IDomValue hasn't propagated yet, or it could be // because MBB is in the dominance frontier of that value. if (DomTree->dominates(IDom, Value.second)) { needPHI = true; break; } } } // The value may be live-through even if Kill is set, as can happen when // we are called from extendRange. In that case LiveOutSeen is true, and // LiveOut indicates a foreign or missing value. LiveOutPair &LOP = LiveOut[MBB]; // Create a phi-def if required. if (needPHI) { ++Changes; assert(Alloc && "Need VNInfo allocator to create PHI-defs"); SlotIndex Start, End; tie(Start, End) = Indexes->getMBBRange(MBB); VNInfo *VNI = I->LI->getNextValue(Start, *Alloc); I->Value = VNI; // This block is done, we know the final value. I->DomNode = 0; // Add liveness since updateLiveIns now skips this node. if (I->Kill.isValid()) I->LI->addRange(LiveRange(Start, I->Kill, VNI)); else { I->LI->addRange(LiveRange(Start, End, VNI)); LOP = LiveOutPair(VNI, Node); } } else if (IDomValue.first) { // No phi-def here. Remember incoming value. I->Value = IDomValue.first; // If the IDomValue is killed in the block, don't propagate through. if (I->Kill.isValid()) continue; // Propagate IDomValue if it isn't killed: // MBB is live-out and doesn't define its own value. if (LOP.first == IDomValue.first) continue; ++Changes; LOP = IDomValue; } } } while (Changes); } <commit_msg>Clear kill flags while computing live ranges.<commit_after>//===---- LiveRangeCalc.cpp - Calculate live ranges -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implementation of the LiveRangeCalc class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "LiveRangeCalc.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineRegisterInfo.h" using namespace llvm; void LiveRangeCalc::reset(const MachineFunction *MF, SlotIndexes *SI, MachineDominatorTree *MDT, VNInfo::Allocator *VNIA) { MRI = &MF->getRegInfo(); Indexes = SI; DomTree = MDT; Alloc = VNIA; unsigned N = MF->getNumBlockIDs(); Seen.clear(); Seen.resize(N); LiveOut.resize(N); LiveIn.clear(); } void LiveRangeCalc::createDeadDefs(LiveInterval *LI, unsigned Reg) { assert(MRI && Indexes && "call reset() first"); // Visit all def operands. If the same instruction has multiple defs of Reg, // LI->createDeadDef() will deduplicate. for (MachineRegisterInfo::def_iterator I = MRI->def_begin(Reg), E = MRI->def_end(); I != E; ++I) { const MachineInstr *MI = &*I; // Find the corresponding slot index. SlotIndex Idx; if (MI->isPHI()) // PHI defs begin at the basic block start index. Idx = Indexes->getMBBStartIdx(MI->getParent()); else // Instructions are either normal 'r', or early clobber 'e'. Idx = Indexes->getInstructionIndex(MI) .getRegSlot(I.getOperand().isEarlyClobber()); // Create the def in LI. This may find an existing def. LI->createDeadDef(Idx, *Alloc); } } void LiveRangeCalc::extendToUses(LiveInterval *LI, unsigned Reg) { assert(MRI && Indexes && "call reset() first"); // Visit all operands that read Reg. This may include partial defs. for (MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(Reg), E = MRI->reg_nodbg_end(); I != E; ++I) { MachineOperand &MO = I.getOperand(); // Clear all kill flags. They will be reinserted after register allocation // by LiveIntervalAnalysis::addKillFlags(). if (MO.isUse()) MO.setIsKill(false); if (!MO.readsReg()) continue; // MI is reading Reg. We may have visited MI before if it happens to be // reading Reg multiple times. That is OK, extend() is idempotent. const MachineInstr *MI = &*I; // Find the SlotIndex being read. SlotIndex Idx; if (MI->isPHI()) { assert(!MO.isDef() && "Cannot handle PHI def of partial register."); // PHI operands are paired: (Reg, PredMBB). // Extend the live range to be live-out from PredMBB. Idx = Indexes->getMBBEndIdx(MI->getOperand(I.getOperandNo()+1).getMBB()); } else { // This is a normal instruction. Idx = Indexes->getInstructionIndex(MI).getRegSlot(); // Check for early-clobber redefs. unsigned DefIdx; if (MO.isDef()) { if (MO.isEarlyClobber()) Idx = Idx.getRegSlot(true); } else if (MI->isRegTiedToDefOperand(I.getOperandNo(), &DefIdx)) { // FIXME: This would be a lot easier if tied early-clobber uses also // had an early-clobber flag. if (MI->getOperand(DefIdx).isEarlyClobber()) Idx = Idx.getRegSlot(true); } } extend(LI, Idx, Reg); } } // Transfer information from the LiveIn vector to the live ranges. void LiveRangeCalc::updateLiveIns(VNInfo *OverrideVNI) { for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(), E = LiveIn.end(); I != E; ++I) { if (!I->DomNode) continue; MachineBasicBlock *MBB = I->DomNode->getBlock(); VNInfo *VNI = OverrideVNI ? OverrideVNI : I->Value; assert(VNI && "No live-in value found"); SlotIndex Start, End; tie(Start, End) = Indexes->getMBBRange(MBB); if (I->Kill.isValid()) I->LI->addRange(LiveRange(Start, I->Kill, VNI)); else { I->LI->addRange(LiveRange(Start, End, VNI)); // The value is live-through, update LiveOut as well. Defer the Domtree // lookup until it is needed. assert(Seen.test(MBB->getNumber())); LiveOut[MBB] = LiveOutPair(VNI, (MachineDomTreeNode *)0); } } LiveIn.clear(); } void LiveRangeCalc::extend(LiveInterval *LI, SlotIndex Kill, unsigned PhysReg) { assert(LI && "Missing live range"); assert(Kill.isValid() && "Invalid SlotIndex"); assert(Indexes && "Missing SlotIndexes"); assert(DomTree && "Missing dominator tree"); MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot()); assert(KillMBB && "No MBB at Kill"); // Is there a def in the same MBB we can extend? if (LI->extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill)) return; // Find the single reaching def, or determine if Kill is jointly dominated by // multiple values, and we may need to create even more phi-defs to preserve // VNInfo SSA form. Perform a search for all predecessor blocks where we // know the dominating VNInfo. VNInfo *VNI = findReachingDefs(LI, KillMBB, Kill, PhysReg); // When there were multiple different values, we may need new PHIs. if (!VNI) updateSSA(); updateLiveIns(VNI); } // This function is called by a client after using the low-level API to add // live-out and live-in blocks. The unique value optimization is not // available, SplitEditor::transferValues handles that case directly anyway. void LiveRangeCalc::calculateValues() { assert(Indexes && "Missing SlotIndexes"); assert(DomTree && "Missing dominator tree"); updateSSA(); updateLiveIns(0); } VNInfo *LiveRangeCalc::findReachingDefs(LiveInterval *LI, MachineBasicBlock *KillMBB, SlotIndex Kill, unsigned PhysReg) { // Blocks where LI should be live-in. SmallVector<MachineBasicBlock*, 16> WorkList(1, KillMBB); // Remember if we have seen more than one value. bool UniqueVNI = true; VNInfo *TheVNI = 0; // Using Seen as a visited set, perform a BFS for all reaching defs. for (unsigned i = 0; i != WorkList.size(); ++i) { MachineBasicBlock *MBB = WorkList[i]; #ifndef NDEBUG if (MBB->pred_empty()) { MBB->getParent()->verify(); llvm_unreachable("Use not jointly dominated by defs."); } if (TargetRegisterInfo::isPhysicalRegister(PhysReg) && !MBB->isLiveIn(PhysReg)) { MBB->getParent()->verify(); errs() << "The register needs to be live in to BB#" << MBB->getNumber() << ", but is missing from the live-in list.\n"; llvm_unreachable("Invalid global physical register"); } #endif for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) { MachineBasicBlock *Pred = *PI; // Is this a known live-out block? if (Seen.test(Pred->getNumber())) { if (VNInfo *VNI = LiveOut[Pred].first) { if (TheVNI && TheVNI != VNI) UniqueVNI = false; TheVNI = VNI; } continue; } SlotIndex Start, End; tie(Start, End) = Indexes->getMBBRange(Pred); // First time we see Pred. Try to determine the live-out value, but set // it as null if Pred is live-through with an unknown value. VNInfo *VNI = LI->extendInBlock(Start, End); setLiveOutValue(Pred, VNI); if (VNI) { if (TheVNI && TheVNI != VNI) UniqueVNI = false; TheVNI = VNI; continue; } // No, we need a live-in value for Pred as well if (Pred != KillMBB) WorkList.push_back(Pred); else // Loopback to KillMBB, so value is really live through. Kill = SlotIndex(); } } // Transfer WorkList to LiveInBlocks in reverse order. // This ordering works best with updateSSA(). LiveIn.clear(); LiveIn.reserve(WorkList.size()); while(!WorkList.empty()) addLiveInBlock(LI, DomTree->getNode(WorkList.pop_back_val())); // The kill block may not be live-through. assert(LiveIn.back().DomNode->getBlock() == KillMBB); LiveIn.back().Kill = Kill; return UniqueVNI ? TheVNI : 0; } // This is essentially the same iterative algorithm that SSAUpdater uses, // except we already have a dominator tree, so we don't have to recompute it. void LiveRangeCalc::updateSSA() { assert(Indexes && "Missing SlotIndexes"); assert(DomTree && "Missing dominator tree"); // Interate until convergence. unsigned Changes; do { Changes = 0; // Propagate live-out values down the dominator tree, inserting phi-defs // when necessary. for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(), E = LiveIn.end(); I != E; ++I) { MachineDomTreeNode *Node = I->DomNode; // Skip block if the live-in value has already been determined. if (!Node) continue; MachineBasicBlock *MBB = Node->getBlock(); MachineDomTreeNode *IDom = Node->getIDom(); LiveOutPair IDomValue; // We need a live-in value to a block with no immediate dominator? // This is probably an unreachable block that has survived somehow. bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber()); // IDom dominates all of our predecessors, but it may not be their // immediate dominator. Check if any of them have live-out values that are // properly dominated by IDom. If so, we need a phi-def here. if (!needPHI) { IDomValue = LiveOut[IDom->getBlock()]; // Cache the DomTree node that defined the value. if (IDomValue.first && !IDomValue.second) LiveOut[IDom->getBlock()].second = IDomValue.second = DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def)); for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) { LiveOutPair &Value = LiveOut[*PI]; if (!Value.first || Value.first == IDomValue.first) continue; // Cache the DomTree node that defined the value. if (!Value.second) Value.second = DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def)); // This predecessor is carrying something other than IDomValue. // It could be because IDomValue hasn't propagated yet, or it could be // because MBB is in the dominance frontier of that value. if (DomTree->dominates(IDom, Value.second)) { needPHI = true; break; } } } // The value may be live-through even if Kill is set, as can happen when // we are called from extendRange. In that case LiveOutSeen is true, and // LiveOut indicates a foreign or missing value. LiveOutPair &LOP = LiveOut[MBB]; // Create a phi-def if required. if (needPHI) { ++Changes; assert(Alloc && "Need VNInfo allocator to create PHI-defs"); SlotIndex Start, End; tie(Start, End) = Indexes->getMBBRange(MBB); VNInfo *VNI = I->LI->getNextValue(Start, *Alloc); I->Value = VNI; // This block is done, we know the final value. I->DomNode = 0; // Add liveness since updateLiveIns now skips this node. if (I->Kill.isValid()) I->LI->addRange(LiveRange(Start, I->Kill, VNI)); else { I->LI->addRange(LiveRange(Start, End, VNI)); LOP = LiveOutPair(VNI, Node); } } else if (IDomValue.first) { // No phi-def here. Remember incoming value. I->Value = IDomValue.first; // If the IDomValue is killed in the block, don't propagate through. if (I->Kill.isValid()) continue; // Propagate IDomValue if it isn't killed: // MBB is live-out and doesn't define its own value. if (LOP.first == IDomValue.first) continue; ++Changes; LOP = IDomValue; } } } while (Changes); } <|endoftext|>
<commit_before>//===--- MinGWToolChain.cpp - MinGWToolChain Implementation ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ToolChains.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Options.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" using namespace clang::diag; using namespace clang::driver; using namespace clang::driver::toolchains; using namespace clang; using namespace llvm::opt; namespace { // Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple. bool findGccVersion(StringRef LibDir, std::string &GccLibDir, std::string &Ver) { Generic_GCC::GCCVersion Version = Generic_GCC::GCCVersion::Parse("0.0.0"); std::error_code EC; for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef VersionText = llvm::sys::path::filename(LI->path()); Generic_GCC::GCCVersion CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText); if (CandidateVersion.Major == -1) continue; if (CandidateVersion <= Version) continue; Ver = VersionText; GccLibDir = LI->path(); } return Ver.size(); } } void MinGW::findGccLibDir() { llvm::SmallVector<llvm::SmallString<32>, 2> Archs; Archs.emplace_back(getTriple().getArchName()); Archs[0] += "-w64-mingw32"; Archs.emplace_back("mingw32"); Arch = Archs[0].str(); // lib: Arch Linux, Ubuntu, Windows // lib64: openSUSE Linux for (StringRef CandidateLib : {"lib", "lib64"}) { for (StringRef CandidateArch : Archs) { llvm::SmallString<1024> LibDir(Base); llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateArch); if (findGccVersion(LibDir, GccLibDir, Ver)) { Arch = CandidateArch; return; } } } } MinGW::MinGW(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args) { getProgramPaths().push_back(getDriver().getInstalledDir()); // In Windows there aren't any standard install locations, we search // for gcc on the PATH. In Linux the base is always /usr. #ifdef LLVM_ON_WIN32 if (getDriver().SysRoot.size()) Base = getDriver().SysRoot; else if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName("gcc")) Base = llvm::sys::path::parent_path( llvm::sys::path::parent_path(GPPName.get())); else Base = llvm::sys::path::parent_path(getDriver().getInstalledDir()); #else if (getDriver().SysRoot.size()) Base = getDriver().SysRoot; else Base = "/usr"; #endif Base += llvm::sys::path::get_separator(); findGccLibDir(); // GccLibDir must precede Base/lib so that the // correct crtbegin.o ,cetend.o would be found. getFilePaths().push_back(GccLibDir); getFilePaths().push_back( (Base + Arch + llvm::sys::path::get_separator() + "lib").str()); getFilePaths().push_back(Base + "lib"); // openSUSE getFilePaths().push_back(Base + Arch + "/sys-root/mingw/lib"); } bool MinGW::IsIntegratedAssemblerDefault() const { return true; } Tool *MinGW::getTool(Action::ActionClass AC) const { switch (AC) { case Action::PreprocessJobClass: if (!Preprocessor) Preprocessor.reset(new tools::gcc::Preprocessor(*this)); return Preprocessor.get(); case Action::CompileJobClass: if (!Compiler) Compiler.reset(new tools::gcc::Compiler(*this)); return Compiler.get(); default: return ToolChain::getTool(AC); } } Tool *MinGW::buildAssembler() const { return new tools::MinGW::Assembler(*this); } Tool *MinGW::buildLinker() const { return new tools::MinGW::Linker(*this); } bool MinGW::IsUnwindTablesDefault() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::isPICDefault() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::isPIEDefault() const { return false; } bool MinGW::isPICDefaultForced() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::UseSEHExceptions() const { return getArch() == llvm::Triple::x86_64; } void MinGW::AddCudaIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args); } void MinGW::printVerboseInfo(raw_ostream &OS) const { CudaInstallation.print(OS); } // Include directories for various hosts: // Windows, mingw.org // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++ // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward // c:\mingw\lib\gcc\mingw32\4.8.1\include // c:\mingw\include // c:\mingw\lib\gcc\mingw32\4.8.1\include-fixed // c:\mingw\mingw32\include // Windows, mingw-w64 mingw-builds // c:\mingw32\lib\gcc\i686-w64-mingw32\4.9.1\include // c:\mingw32\lib\gcc\i686-w64-mingw32\4.9.1\include-fixed // c:\mingw32\i686-w64-mingw32\include // c:\mingw32\i686-w64-mingw32\include\c++ // c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32 // c:\mingw32\i686-w64-mingw32\include\c++\backward // Windows, mingw-w64 msys2 // c:\msys64\mingw32\lib\gcc\i686-w64-mingw32\4.9.2\include // c:\msys64\mingw32\include // c:\msys64\mingw32\lib\gcc\i686-w64-mingw32\4.9.2\include-fixed // c:\msys64\mingw32\i686-w64-mingw32\include // c:\msys64\mingw32\include\c++\4.9.2 // c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32 // c:\msys64\mingw32\include\c++\4.9.2\backward // openSUSE // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++ // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include-fixed // /usr/x86_64-w64-mingw32/sys-root/mingw/include // Arch Linux // /usr/i686-w64-mingw32/include/c++/5.1.0 // /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32 // /usr/i686-w64-mingw32/include/c++/5.1.0/backward // /usr/lib/gcc/i686-w64-mingw32/5.1.0/include // /usr/lib/gcc/i686-w64-mingw32/5.1.0/include-fixed // /usr/i686-w64-mingw32/include // Ubuntu // /usr/include/c++/4.8 // /usr/include/c++/4.8/x86_64-w64-mingw32 // /usr/include/c++/4.8/backward // /usr/lib/gcc/x86_64-w64-mingw32/4.8/include // /usr/lib/gcc/x86_64-w64-mingw32/4.8/include-fixed // /usr/x86_64-w64-mingw32/include void MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc)) return; if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { SmallString<1024> P(getDriver().ResourceDir); llvm::sys::path::append(P, "include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } if (DriverArgs.hasArg(options::OPT_nostdlibinc)) return; if (GetRuntimeLibType(DriverArgs) == ToolChain::RLT_Libgcc) { llvm::SmallString<1024> IncludeDir(GccLibDir); llvm::sys::path::append(IncludeDir, "include"); addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str()); IncludeDir += "-fixed"; // openSUSE addSystemInclude(DriverArgs, CC1Args, Base + Arch + "/sys-root/mingw/include"); addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str()); } addSystemInclude(DriverArgs, CC1Args, Base + Arch + llvm::sys::path::get_separator() + "include"); addSystemInclude(DriverArgs, CC1Args, Base + "include"); } void MinGW::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdlibinc) || DriverArgs.hasArg(options::OPT_nostdincxx)) return; switch (GetCXXStdlibType(DriverArgs)) { case ToolChain::CST_Libcxx: addSystemInclude(DriverArgs, CC1Args, Base + "include" + llvm::sys::path::get_separator() + "c++" + llvm::sys::path::get_separator() + "v1"); break; case ToolChain::CST_Libstdcxx: llvm::SmallVector<llvm::SmallString<1024>, 4> CppIncludeBases; CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[0], Arch, "include", "c++"); CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[1], Arch, "include", "c++", Ver); CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver); CppIncludeBases.emplace_back(GccLibDir); llvm::sys::path::append(CppIncludeBases[3], "include", "c++"); for (auto &CppIncludeBase : CppIncludeBases) { addSystemInclude(DriverArgs, CC1Args, CppIncludeBase); CppIncludeBase += llvm::sys::path::get_separator(); addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + Arch); addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward"); } break; } } <commit_msg>[ToolChains] Use "static" instead of an anonymous namespace for a function. NFC<commit_after>//===--- MinGWToolChain.cpp - MinGWToolChain Implementation ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ToolChains.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Options.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" using namespace clang::diag; using namespace clang::driver; using namespace clang::driver::toolchains; using namespace clang; using namespace llvm::opt; // Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple. static bool findGccVersion(StringRef LibDir, std::string &GccLibDir, std::string &Ver) { Generic_GCC::GCCVersion Version = Generic_GCC::GCCVersion::Parse("0.0.0"); std::error_code EC; for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef VersionText = llvm::sys::path::filename(LI->path()); Generic_GCC::GCCVersion CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText); if (CandidateVersion.Major == -1) continue; if (CandidateVersion <= Version) continue; Ver = VersionText; GccLibDir = LI->path(); } return Ver.size(); } void MinGW::findGccLibDir() { llvm::SmallVector<llvm::SmallString<32>, 2> Archs; Archs.emplace_back(getTriple().getArchName()); Archs[0] += "-w64-mingw32"; Archs.emplace_back("mingw32"); Arch = Archs[0].str(); // lib: Arch Linux, Ubuntu, Windows // lib64: openSUSE Linux for (StringRef CandidateLib : {"lib", "lib64"}) { for (StringRef CandidateArch : Archs) { llvm::SmallString<1024> LibDir(Base); llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateArch); if (findGccVersion(LibDir, GccLibDir, Ver)) { Arch = CandidateArch; return; } } } } MinGW::MinGW(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args) { getProgramPaths().push_back(getDriver().getInstalledDir()); // In Windows there aren't any standard install locations, we search // for gcc on the PATH. In Linux the base is always /usr. #ifdef LLVM_ON_WIN32 if (getDriver().SysRoot.size()) Base = getDriver().SysRoot; else if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName("gcc")) Base = llvm::sys::path::parent_path( llvm::sys::path::parent_path(GPPName.get())); else Base = llvm::sys::path::parent_path(getDriver().getInstalledDir()); #else if (getDriver().SysRoot.size()) Base = getDriver().SysRoot; else Base = "/usr"; #endif Base += llvm::sys::path::get_separator(); findGccLibDir(); // GccLibDir must precede Base/lib so that the // correct crtbegin.o ,cetend.o would be found. getFilePaths().push_back(GccLibDir); getFilePaths().push_back( (Base + Arch + llvm::sys::path::get_separator() + "lib").str()); getFilePaths().push_back(Base + "lib"); // openSUSE getFilePaths().push_back(Base + Arch + "/sys-root/mingw/lib"); } bool MinGW::IsIntegratedAssemblerDefault() const { return true; } Tool *MinGW::getTool(Action::ActionClass AC) const { switch (AC) { case Action::PreprocessJobClass: if (!Preprocessor) Preprocessor.reset(new tools::gcc::Preprocessor(*this)); return Preprocessor.get(); case Action::CompileJobClass: if (!Compiler) Compiler.reset(new tools::gcc::Compiler(*this)); return Compiler.get(); default: return ToolChain::getTool(AC); } } Tool *MinGW::buildAssembler() const { return new tools::MinGW::Assembler(*this); } Tool *MinGW::buildLinker() const { return new tools::MinGW::Linker(*this); } bool MinGW::IsUnwindTablesDefault() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::isPICDefault() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::isPIEDefault() const { return false; } bool MinGW::isPICDefaultForced() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::UseSEHExceptions() const { return getArch() == llvm::Triple::x86_64; } void MinGW::AddCudaIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args); } void MinGW::printVerboseInfo(raw_ostream &OS) const { CudaInstallation.print(OS); } // Include directories for various hosts: // Windows, mingw.org // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++ // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward // c:\mingw\lib\gcc\mingw32\4.8.1\include // c:\mingw\include // c:\mingw\lib\gcc\mingw32\4.8.1\include-fixed // c:\mingw\mingw32\include // Windows, mingw-w64 mingw-builds // c:\mingw32\lib\gcc\i686-w64-mingw32\4.9.1\include // c:\mingw32\lib\gcc\i686-w64-mingw32\4.9.1\include-fixed // c:\mingw32\i686-w64-mingw32\include // c:\mingw32\i686-w64-mingw32\include\c++ // c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32 // c:\mingw32\i686-w64-mingw32\include\c++\backward // Windows, mingw-w64 msys2 // c:\msys64\mingw32\lib\gcc\i686-w64-mingw32\4.9.2\include // c:\msys64\mingw32\include // c:\msys64\mingw32\lib\gcc\i686-w64-mingw32\4.9.2\include-fixed // c:\msys64\mingw32\i686-w64-mingw32\include // c:\msys64\mingw32\include\c++\4.9.2 // c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32 // c:\msys64\mingw32\include\c++\4.9.2\backward // openSUSE // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++ // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include-fixed // /usr/x86_64-w64-mingw32/sys-root/mingw/include // Arch Linux // /usr/i686-w64-mingw32/include/c++/5.1.0 // /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32 // /usr/i686-w64-mingw32/include/c++/5.1.0/backward // /usr/lib/gcc/i686-w64-mingw32/5.1.0/include // /usr/lib/gcc/i686-w64-mingw32/5.1.0/include-fixed // /usr/i686-w64-mingw32/include // Ubuntu // /usr/include/c++/4.8 // /usr/include/c++/4.8/x86_64-w64-mingw32 // /usr/include/c++/4.8/backward // /usr/lib/gcc/x86_64-w64-mingw32/4.8/include // /usr/lib/gcc/x86_64-w64-mingw32/4.8/include-fixed // /usr/x86_64-w64-mingw32/include void MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc)) return; if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { SmallString<1024> P(getDriver().ResourceDir); llvm::sys::path::append(P, "include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } if (DriverArgs.hasArg(options::OPT_nostdlibinc)) return; if (GetRuntimeLibType(DriverArgs) == ToolChain::RLT_Libgcc) { llvm::SmallString<1024> IncludeDir(GccLibDir); llvm::sys::path::append(IncludeDir, "include"); addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str()); IncludeDir += "-fixed"; // openSUSE addSystemInclude(DriverArgs, CC1Args, Base + Arch + "/sys-root/mingw/include"); addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str()); } addSystemInclude(DriverArgs, CC1Args, Base + Arch + llvm::sys::path::get_separator() + "include"); addSystemInclude(DriverArgs, CC1Args, Base + "include"); } void MinGW::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdlibinc) || DriverArgs.hasArg(options::OPT_nostdincxx)) return; switch (GetCXXStdlibType(DriverArgs)) { case ToolChain::CST_Libcxx: addSystemInclude(DriverArgs, CC1Args, Base + "include" + llvm::sys::path::get_separator() + "c++" + llvm::sys::path::get_separator() + "v1"); break; case ToolChain::CST_Libstdcxx: llvm::SmallVector<llvm::SmallString<1024>, 4> CppIncludeBases; CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[0], Arch, "include", "c++"); CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[1], Arch, "include", "c++", Ver); CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver); CppIncludeBases.emplace_back(GccLibDir); llvm::sys::path::append(CppIncludeBases[3], "include", "c++"); for (auto &CppIncludeBase : CppIncludeBases) { addSystemInclude(DriverArgs, CC1Args, CppIncludeBase); CppIncludeBase += llvm::sys::path::get_separator(); addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + Arch); addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward"); } break; } } <|endoftext|>
<commit_before>/***************************************************************************** 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. See NOTICE file for details. *****************************************************************************/ #include <algorithm> #include "jpype.h" #include "jp_method.h" #include "jp_methoddispatch.h" JPMethodDispatch::JPMethodDispatch(JPClass* clazz, const string& name, JPMethodList& overloads, jint modifiers) : m_Name(name) { m_Class = clazz; m_Overloads = overloads; m_Modifiers = modifiers; m_LastCache.m_Cache = -1; } JPMethodDispatch::~JPMethodDispatch() { } const string& JPMethodDispatch::getName() const { return m_Name; } bool JPMethodDispatch::findOverload(JPJavaFrame& frame, JPMethodMatch &bestMatch, JPPyObjectVector& arg, bool callInstance, bool raise) { JP_TRACE_IN("JPMethodDispatch::findOverload"); JP_TRACE("Checking overload", m_Name); JP_TRACE("Got overloads to check", m_Overloads.size()); JPMethodList ambiguous; JPMethodMatch match = bestMatch; // Check cache to see if we already resolved this if (m_LastCache.m_Cache == match.m_Cache) { bestMatch.m_Overload = m_LastCache.m_Overload; bestMatch.m_Overload->matches(frame, bestMatch, callInstance, arg); if (bestMatch.m_Type > JPMatch::_explicit) return true; } for (JPMethodList::iterator it = m_Overloads.begin(); it != m_Overloads.end(); ++it) { JPMethod* current = *it; // This would be hidden as we have a match with a more specific overload // already and it can't be exact. if (bestMatch.m_Type == JPMatch::_implicit && bestMatch.m_Overload->checkMoreSpecificThan(current)) continue; JP_TRACE("Trying to match", current->toString()); current->matches(frame, match, callInstance, arg); JP_TRACE(" match ended", match.m_Type); if (match.m_Type == JPMatch::_exact) { bestMatch = match; m_LastCache = match; return true; } if (match.m_Type < JPMatch::_implicit) continue; // If this is the first match then make it the best. if (bestMatch.m_Overload == 0) { bestMatch = match; continue; } // If the best does not hide the other, than we have ambiguity. if (!(bestMatch.m_Overload->checkMoreSpecificThan(current))) { // See if we can match based on instance if (callInstance == !current->isStatic()) { // if current matches instance and best does not switch if (callInstance == bestMatch.m_Overload->isStatic()) { bestMatch = match; continue; } } else { // if best matches instance and current does not, no ambiguity if (callInstance == !bestMatch.m_Overload->isStatic()) { continue; } } JP_TRACE("Adding to ambiguous list"); ambiguous.push_back(*it); } } // If we have an ambiguous overload report an error. if (!ambiguous.empty()) { if (!raise) return false; ambiguous.push_back(bestMatch.m_Overload); // We have two possible overloads so we declare an error std::stringstream ss; if (JPModifier::isConstructor(m_Modifiers)) ss << "Ambiguous overloads found for constructor " << m_Class->getCanonicalName() << "("; else ss << "Ambiguous overloads found for " << m_Class->getCanonicalName() << "." << getName() << "("; size_t start = callInstance ? 1 : 0; for (size_t i = start; i < arg.size(); ++i) { if (i != start) ss << ","; ss << Py_TYPE(arg[i])->tp_name; } ss << ")" << " between:" << std::endl; for (vector<JPMethod*>::iterator it = ambiguous.begin(); it != ambiguous.end(); ++it) { ss << "\t" << (*it)->toString() << std::endl; } JP_RAISE(PyExc_TypeError, ss.str()); JP_TRACE(ss.str()); } // If we can't find a matching overload throw an error. if (!bestMatch.m_Overload) { if (!raise) return false; std::stringstream ss; if (JPModifier::isConstructor(m_Modifiers)) ss << "No matching overloads found for constructor " << m_Class->getCanonicalName() << "("; else ss << "No matching overloads found for " << m_Class->getCanonicalName() << "." << getName() << "("; size_t start = callInstance ? 1 : 0; for (size_t i = start; i < arg.size(); ++i) { if (i != start) ss << ","; ss << Py_TYPE(arg[i])->tp_name; } ss << ")" << ", options are:" << std::endl; for (JPMethodList::iterator it = m_Overloads.begin(); it != m_Overloads.end(); ++it) { JPMethod* current = *it; ss << "\t" << current->toString(); ss << std::endl; } JP_RAISE(PyExc_TypeError, ss.str()); } // Set up a cache to bypass repeated calls. if (bestMatch.m_Type == JPMatch::_implicit) { m_LastCache = bestMatch; } JP_TRACE("Best match", bestMatch.m_Overload->toString()); return true; JP_TRACE_OUT; } JPPyObject JPMethodDispatch::invoke(JPJavaFrame& frame, JPPyObjectVector& args, bool instance) { JP_TRACE_IN("JPMethodDispatch::invoke"); JPMethodMatch match(frame, args, instance); findOverload(frame, match, args, instance, true); return match.m_Overload->invoke(frame, match, args, instance); JP_TRACE_OUT; } JPValue JPMethodDispatch::invokeConstructor(JPJavaFrame& frame, JPPyObjectVector& args) { JP_TRACE_IN("JPMethodDispatch::invokeConstructor"); JPMethodMatch match(frame, args, false); findOverload(frame, match, args, false, true); return match.m_Overload->invokeConstructor(frame, match, args); JP_TRACE_OUT; } bool JPMethodDispatch::matches(JPJavaFrame& frame, JPPyObjectVector& args, bool instance) { JP_TRACE_IN("JPMethodDispatch::invoke"); JPMethodMatch match(frame, args, instance); return findOverload(frame, match, args, instance, false); JP_TRACE_OUT; // GCOVR_EXCL_LINE } string JPMethodDispatch::matchReport(JPPyObjectVector& args) { stringstream res; res << "Match report for method " << m_Name << ", has " << m_Overloads.size() << " overloads." << endl; for (JPMethodList::iterator cur = m_Overloads.begin(); cur != m_Overloads.end(); cur++) { JPMethod* current = *cur; res << " " << current->matchReport(args); } return res.str(); } <commit_msg>Fix caching. Disable cache for Varargs.<commit_after>/***************************************************************************** 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. See NOTICE file for details. *****************************************************************************/ #include <algorithm> #include "jpype.h" #include "jp_method.h" #include "jp_methoddispatch.h" JPMethodDispatch::JPMethodDispatch(JPClass* clazz, const string& name, JPMethodList& overloads, jint modifiers) : m_Name(name) { m_Class = clazz; m_Overloads = overloads; m_Modifiers = modifiers; m_LastCache.m_Cache = -1; } JPMethodDispatch::~JPMethodDispatch() { } const string& JPMethodDispatch::getName() const { return m_Name; } bool JPMethodDispatch::findOverload(JPJavaFrame& frame, JPMethodMatch &bestMatch, JPPyObjectVector& arg, bool callInstance, bool raise) { JP_TRACE_IN("JPMethodDispatch::findOverload"); JP_TRACE("Checking overload", m_Name); JP_TRACE("Got overloads to check", m_Overloads.size()); JPMethodList ambiguous; JPMethodMatch match = bestMatch; // Check cache to see if we already resolved this if (m_LastCache.m_Cache == match.m_Cache && !m_LastCache.m_Overload->isVarArgs()) { bestMatch.m_Overload = m_LastCache.m_Overload; bestMatch.m_Overload->matches(frame, bestMatch, callInstance, arg); if (bestMatch.m_Type > JPMatch::_explicit) return true; } for (JPMethodList::iterator it = m_Overloads.begin(); it != m_Overloads.end(); ++it) { JPMethod* current = *it; JP_TRACE("Trying to match", current->toString()); current->matches(frame, match, callInstance, arg); JP_TRACE(" match ended", match.m_Type); if (match.m_Type == JPMatch::_exact) { bestMatch = match; m_LastCache = match; return true; } if (match.m_Type < JPMatch::_implicit) continue; // If this is the first match then make it the best. if (bestMatch.m_Overload == 0) { bestMatch = match; continue; } // If the best does not hide the other, than we have ambiguity. if (!(bestMatch.m_Overload->checkMoreSpecificThan(current))) { // See if we can match based on instance if (callInstance == !current->isStatic()) { // if current matches instance and best does not switch if (callInstance == bestMatch.m_Overload->isStatic()) { bestMatch = match; continue; } } else { // if best matches instance and current does not, no ambiguity if (callInstance == !bestMatch.m_Overload->isStatic()) { continue; } } JP_TRACE("Adding to ambiguous list"); ambiguous.push_back(*it); } } // If we have an ambiguous overload report an error. if (!ambiguous.empty()) { if (!raise) return false; ambiguous.push_back(bestMatch.m_Overload); // We have two possible overloads so we declare an error std::stringstream ss; if (JPModifier::isConstructor(m_Modifiers)) ss << "Ambiguous overloads found for constructor " << m_Class->getCanonicalName() << "("; else ss << "Ambiguous overloads found for " << m_Class->getCanonicalName() << "." << getName() << "("; size_t start = callInstance ? 1 : 0; for (size_t i = start; i < arg.size(); ++i) { if (i != start) ss << ","; ss << Py_TYPE(arg[i])->tp_name; } ss << ")" << " between:" << std::endl; for (vector<JPMethod*>::iterator it = ambiguous.begin(); it != ambiguous.end(); ++it) { ss << "\t" << (*it)->toString() << std::endl; } JP_RAISE(PyExc_TypeError, ss.str()); JP_TRACE(ss.str()); } // If we can't find a matching overload throw an error. if (!bestMatch.m_Overload) { if (!raise) return false; std::stringstream ss; if (JPModifier::isConstructor(m_Modifiers)) ss << "No matching overloads found for constructor " << m_Class->getCanonicalName() << "("; else ss << "No matching overloads found for " << m_Class->getCanonicalName() << "." << getName() << "("; size_t start = callInstance ? 1 : 0; for (size_t i = start; i < arg.size(); ++i) { if (i != start) ss << ","; ss << Py_TYPE(arg[i])->tp_name; } ss << ")" << ", options are:" << std::endl; for (JPMethodList::iterator it = m_Overloads.begin(); it != m_Overloads.end(); ++it) { JPMethod* current = *it; ss << "\t" << current->toString(); ss << std::endl; } JP_RAISE(PyExc_TypeError, ss.str()); } // Set up a cache to bypass repeated calls. if (bestMatch.m_Type == JPMatch::_implicit) { m_LastCache = bestMatch; } JP_TRACE("Best match", bestMatch.m_Overload->toString()); return true; JP_TRACE_OUT; } JPPyObject JPMethodDispatch::invoke(JPJavaFrame& frame, JPPyObjectVector& args, bool instance) { JP_TRACE_IN("JPMethodDispatch::invoke"); JPMethodMatch match(frame, args, instance); findOverload(frame, match, args, instance, true); return match.m_Overload->invoke(frame, match, args, instance); JP_TRACE_OUT; } JPValue JPMethodDispatch::invokeConstructor(JPJavaFrame& frame, JPPyObjectVector& args) { JP_TRACE_IN("JPMethodDispatch::invokeConstructor"); JPMethodMatch match(frame, args, false); findOverload(frame, match, args, false, true); return match.m_Overload->invokeConstructor(frame, match, args); JP_TRACE_OUT; } bool JPMethodDispatch::matches(JPJavaFrame& frame, JPPyObjectVector& args, bool instance) { JP_TRACE_IN("JPMethodDispatch::invoke"); JPMethodMatch match(frame, args, instance); return findOverload(frame, match, args, instance, false); JP_TRACE_OUT; // GCOVR_EXCL_LINE } string JPMethodDispatch::matchReport(JPPyObjectVector& args) { stringstream res; res << "Match report for method " << m_Name << ", has " << m_Overloads.size() << " overloads." << endl; for (JPMethodList::iterator cur = m_Overloads.begin(); cur != m_Overloads.end(); cur++) { JPMethod* current = *cur; res << " " << current->matchReport(args); } return res.str(); } <|endoftext|>
<commit_before>/* * This file is part of OpenModelica. * * Copyright (c) 1998-CurrentYear, Linköping University, * Department of Computer and Information Science, * SE-58183 Linköping, Sweden. * * All rights reserved. * * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 * AND THIS OSMC PUBLIC LICENSE (OSMC-PL). * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S * ACCEPTANCE OF THE OSMC PUBLIC LICENSE. * * The OpenModelica software and the Open Source Modelica * Consortium (OSMC) Public License (OSMC-PL) are obtained * from Linköping University, either from the above address, * from the URLs: http://www.ida.liu.se/projects/OpenModelica or * http://www.openmodelica.org, and in the OpenModelica distribution. * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. * * This program is distributed WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS * OF OSMC-PL. * * See the full OSMC Public License conditions for more details. * */ /* * HopsanGUI * Fluid and Mechatronic Systems, Department of Management and Engineering, Linköping University * Main Authors 2009-2010: Robert Braun, Björn Eriksson, Peter Nordin * Contributors 2009-2010: Mikael Axin, Alessandro Dell'Amico, Karl Pettersson, Ingo Staack */ //$Id$ #include "GUIPort.h" #include "plotwidget.h" #include "mainwindow.h" #include <QtGui> //! Constructor. //! @param portName The name of the port //! @param x the x-coord. of where the port should be placed. //! @param y the y-coord. of where the port should be placed. //! @param rot how the port should be rotated. //! @param iconPath a string with the path to the svg-figure representing the port. //! @param parent the port's parent, the component it is a part of. GUIPort::GUIPort(QString portName, qreal xpos, qreal ypos, PortAppearance* pPortAppearance, GUIObject *pParent, GUIRootSystem *pGUIRootSystem) : QGraphicsSvgItem(pPortAppearance->iconPath, pParent) { mpParentGraphicsView = pParent->mpParentGraphicsView; mpParentGuiObject = pParent; mpPortAppearance = pPortAppearance; mpGUIRootSystem = pGUIRootSystem; //Use this to indicate system port this->name = portName; //setTransformOriginPoint(boundingRect().width()/2,boundingRect().height()/2); setTransformOriginPoint(boundingRect().center()); mXpos = xpos; mYpos = ypos; updatePosition(); // pRectParent = parent; this->setAcceptHoverEvents(true); //QBrush brush(Qt::green); //this->setBrush(brush); mpPortLabel = new QGraphicsTextItem(this); QString label("<p><span style=\"background-color:lightyellow\">"); label.append(this->getName()).append("</span></p>"); mpPortLabel->setHtml(label); mpPortLabel->setTextInteractionFlags(Qt::NoTextInteraction); mpPortLabel->setPos(7.0,7.0); mpPortLabel->hide(); //! @todo this kind of harcoded stuff should not be here, fix the problem in some other way if(this->getPortType() == "POWERPORT") { this->setRotation(0.0); mpPortLabel->setRotation(0.0); } else { this->setRotation(mpPortAppearance->rot); mpPortLabel->setRotation(-mpPortAppearance->rot); } mMag = 1.6180339887; mIsMag = false; isConnected = false; MainWindow *pMainWindow = mpParentGuiObject->mpParentGraphicsScene->mpParentProjectTab->mpParentProjectTabWidget->mpParentMainWindow; connect(this,SIGNAL(portClicked(GUIPort*)),this->getParentView(),SLOT(addConnector(GUIPort*))); connect(pMainWindow->hidePortsAction,SIGNAL(triggered(bool)),this, SLOT(hideIfNotConnected(bool))); //connect(pMainWindow->showPortsAction,SIGNAL(triggered()),this, SLOT(showIfNotConnected())); } GUIPort::~GUIPort() { } //! Magnify the port with a class mebmer factor 'mMag'. Is used i.e. at hovering over disconnected port. //! @param blowup says if the port should be magnified or not. void GUIPort::magnify(bool blowup) { if ((!blowup) && (mIsMag)) { this->moveBy((mMag-1)*boundingRect().width()/2, (mMag-1)*boundingRect().height()/2); this->scale(1/mMag,1/mMag); this->mpPortLabel->scale(mMag,mMag); mIsMag = false; } else if ((blowup) && (!mIsMag)) { this->scale(mMag, mMag); this->moveBy(-(mMag-1)*boundingRect().width()/2, -(mMag-1)*boundingRect().height()/2); this->mpPortLabel->scale(1/mMag,1/mMag); mIsMag = true; } } //! Defines what happens when mouse cursor begins to hover a port. //! @param *event defines the mouse event. void GUIPort::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsSvgItem::hoverEnterEvent(event); this->setCursor(Qt::CrossCursor); QBrush brush(Qt::blue); std::cout << "GUIPort.cpp: " << "hovering over port" << std::endl; magnify(true); mpPortLabel->setRotation(-this->mpParentGuiObject->rotation()-this->rotation()); //qDebug() << "label: " << mpPortLabel->rotation() << " this: " << this->rotation(); this->setZValue(1.0); mpPortLabel->show(); } void GUIPort::updatePosition() { if(mpParentGuiObject->rotation() == 0) setPos(mXpos-this->boundingRect().width()/2.0, mYpos-this->boundingRect().height()/2.0); else if(mpParentGuiObject->rotation() == 90) setPos(mXpos-this->boundingRect().width()/2.0, mYpos+this->boundingRect().height()/2.0); else if(mpParentGuiObject->rotation() == 180) setPos(mXpos+this->boundingRect().width()/2.0, mYpos+this->boundingRect().height()/2.0); else setPos(mXpos+this->boundingRect().width()/2.0, mYpos-this->boundingRect().height()/2.0); } //! Defines what happens when mouse cursor stops hovering a port. //! @param *event defines the mouse event. void GUIPort::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsSvgItem::hoverLeaveEvent(event); QBrush brush(Qt::green); //this->setBrush(brush); this->setCursor(Qt::ArrowCursor); magnify(false); mpPortLabel->hide(); this->setZValue(0.0); } //! Defines what happens when clicking on a port. //! @param *event defines the mouse event. void GUIPort::mousePressEvent(QGraphicsSceneMouseEvent *event) { //QGraphicsItem::mousePressEvent(event); //Don't work if this is called if (event->button() == Qt::LeftButton) { std::cout << "GUIPort.cpp: " << "portClick emitted\n"; emit portClicked(this); } else if (event->button() == Qt::RightButton) { std::cout << "GUIPort.cpp: " << "RightClick" << std::endl; } magnify(false); } void GUIPort::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { std::cout << "GUIPort.cpp: " << "contextMenuEvent" << std::endl; if ((!this->isConnected) || (this->mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getTimeVector(getGUIComponentName(), this->getName()).empty())) { event->ignore(); } else { QMenu menu; //! @todo this bellow is complete madness. hardcoded hopsan specific stuff, must be rewritten, not sure if it should even be here //! @todo we do not need hardcoded stuff we can ask the core about what variables are available if (this->getNodeType() =="NodeHydraulic") { QAction *plotPressureAction = menu.addAction("Plot pressure"); QAction *plotFlowAction = menu.addAction("Plot flow"); QAction *selectedAction = menu.exec(event->screenPos()); if (selectedAction == plotFlowAction) { plot("MassFlow"); } if (selectedAction == plotPressureAction) { plot("Pressure"); } } if (this->getNodeType() =="NodeMechanic") { QAction *plotVelocityAction = menu.addAction("Plot velocity"); QAction *plotForceAction = menu.addAction("Plot force"); QAction *plotPositionAction = menu.addAction("Plot position"); QAction *selectedAction = menu.exec(event->screenPos()); if (selectedAction == plotVelocityAction) { plot("Velocity"); } if (selectedAction == plotForceAction) { plot("Force"); } if (selectedAction == plotPositionAction) { plot("Position"); } } if (this->getNodeType() =="NodeSignal") { QAction *plotSignalAction = menu.addAction("Plot signal value"); QAction *selectedAction = menu.exec(event->screenPos()); if (selectedAction == plotSignalAction) { plot("Value"); } } } } //! Returns a pointer to the GraphicsView that the port belongs to. GraphicsView *GUIPort::getParentView() { return mpParentGraphicsView; } //! Returns a pointer to the GUIComponent the port belongs to. GUIObject *GUIPort::getGuiObject() { return mpParentGuiObject; } //! Plots the varable number 'nVar' in the node the port is connected to. //! @param nVar tells which variable to plot. //! @todo If dataUnit not supplied no unit will be shown, we should maybe lookup the unit if not supplid, or allways look it up, or demand that it is supplied void GUIPort::plot(QString dataName, QString dataUnit) //En del vansinne i denna metoden... { std::cout << "GUIPort.cpp: " << "Plot()" << std::endl; QVector<double> time = QVector<double>::fromStdVector(mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getTimeVector(getGUIComponentName(), this->getName())); QVector<double> y; mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getPlotData(getGUIComponentName(), this->getName(), dataName, y); qDebug() << "Time size: " << time.size() << " last time: " << *time.end() << " " << "y.size(): " << y.size(); qDebug() << "time[0]: " << time[0] << " time[last-1]: " << time[time.size()-2] << " time[last]: " << time[time.size()-1]; for (int i = 0; i<time.size(); ++i) { //qDebug() << time[i]; } qDebug() << "y[0]: " << y[0] << " y[last-1]: " << y[y.size()-2] << " y[last]: " << y[y.size()-1]; QString title; QString xlabel; QString ylabel; title.append(dataName); ylabel.append(dataName + ", [" + dataUnit + "]"); //! @todo need to comment this out for now fix later //title.append(" at component: ").append(QString::fromStdString(mpParentComponent->mpCoreComponent->getName())).append(", port: ").append(QString::fromStdString(mpCorePort->getPortName())); xlabel.append("Time, [s]"); //PlotWidget *newPlot = new PlotWidget(time,y,mpParentGuiObject->mpParentGraphicsView); PlotWidget *newPlot = new PlotWidget(time,y,mpParentGuiObject->mpParentGraphicsView->mpParentProjectTab->mpParentProjectTabWidget->mpParentMainWindow); //newPlot->mpVariablePlot->setTitle(title); newPlot->mpCurve->setTitle(title); newPlot->mpVariablePlot->setAxisTitle(VariablePlot::yLeft, ylabel); newPlot->mpVariablePlot->setAxisTitle(VariablePlot::xBottom, xlabel); newPlot->mpVariablePlot->insertLegend(new QwtLegend(), QwtPlot::TopLegend); newPlot->show(); } //! Returns the number of the port by calling the equivalent function in the parent component. int GUIPort::getPortNumber() { return this->getGuiObject()->getPortNumber(this); } //! Wrapper for the Core getPortTypeString() function QString GUIPort::getPortType() { return this->mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getPortType(getGUIComponentName(), this->getName()); } //! Wrapper for the Core getNodeType() function QString GUIPort::getNodeType() { return this->mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getNodeType(getGUIComponentName(), this->getName()); } PortAppearance::portDirectionType GUIPort::getPortDirection() { return mpPortAppearance->direction; } void GUIPort::setPortDirection(PortAppearance::portDirectionType direction) { mpPortAppearance->direction = direction; } QString GUIPort::getName() { return this->name; } void GUIPort::setDisplayName(const QString name) { this->name = name; QString label("<p><span style=\"background-color:lightyellow\">"); label.append(this->name).append("</span></p>"); mpPortLabel->setHtml(label); } //! Get the name of the GUIComponent or GUISubsystem that the port is connected to, This is not necessarily the same as the parent GUIObject name (SystemPorts) //! @todo this is a very ugly way of handeling system ports should try to think of something better QString GUIPort::getGUIComponentName() { qDebug() << "apa"; if (mpGUIRootSystem == 0) { qDebug() << "apa2"; qDebug() << "return guiobject name: " << mpParentGuiObject->getName(); return mpParentGuiObject->getName(); } else { qDebug() << "apa3"; qDebug() << "return root name: " << mpGUIRootSystem->getName(); return mpGUIRootSystem->getName(); } } void GUIPort::hideIfNotConnected(bool justDoIt) { if(!isConnected and justDoIt) { this->hide(); } else if(!isConnected and !justDoIt) { this->show(); } } <commit_msg>Cleared some "apa"-debugs<commit_after>/* * This file is part of OpenModelica. * * Copyright (c) 1998-CurrentYear, Linköping University, * Department of Computer and Information Science, * SE-58183 Linköping, Sweden. * * All rights reserved. * * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 * AND THIS OSMC PUBLIC LICENSE (OSMC-PL). * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S * ACCEPTANCE OF THE OSMC PUBLIC LICENSE. * * The OpenModelica software and the Open Source Modelica * Consortium (OSMC) Public License (OSMC-PL) are obtained * from Linköping University, either from the above address, * from the URLs: http://www.ida.liu.se/projects/OpenModelica or * http://www.openmodelica.org, and in the OpenModelica distribution. * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. * * This program is distributed WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS * OF OSMC-PL. * * See the full OSMC Public License conditions for more details. * */ /* * HopsanGUI * Fluid and Mechatronic Systems, Department of Management and Engineering, Linköping University * Main Authors 2009-2010: Robert Braun, Björn Eriksson, Peter Nordin * Contributors 2009-2010: Mikael Axin, Alessandro Dell'Amico, Karl Pettersson, Ingo Staack */ //$Id$ #include "GUIPort.h" #include "plotwidget.h" #include "mainwindow.h" #include <QtGui> //! Constructor. //! @param portName The name of the port //! @param x the x-coord. of where the port should be placed. //! @param y the y-coord. of where the port should be placed. //! @param rot how the port should be rotated. //! @param iconPath a string with the path to the svg-figure representing the port. //! @param parent the port's parent, the component it is a part of. GUIPort::GUIPort(QString portName, qreal xpos, qreal ypos, PortAppearance* pPortAppearance, GUIObject *pParent, GUIRootSystem *pGUIRootSystem) : QGraphicsSvgItem(pPortAppearance->iconPath, pParent) { mpParentGraphicsView = pParent->mpParentGraphicsView; mpParentGuiObject = pParent; mpPortAppearance = pPortAppearance; mpGUIRootSystem = pGUIRootSystem; //Use this to indicate system port this->name = portName; //setTransformOriginPoint(boundingRect().width()/2,boundingRect().height()/2); setTransformOriginPoint(boundingRect().center()); mXpos = xpos; mYpos = ypos; updatePosition(); // pRectParent = parent; this->setAcceptHoverEvents(true); //QBrush brush(Qt::green); //this->setBrush(brush); mpPortLabel = new QGraphicsTextItem(this); QString label("<p><span style=\"background-color:lightyellow\">"); label.append(this->getName()).append("</span></p>"); mpPortLabel->setHtml(label); mpPortLabel->setTextInteractionFlags(Qt::NoTextInteraction); mpPortLabel->setPos(7.0,7.0); mpPortLabel->hide(); //! @todo this kind of harcoded stuff should not be here, fix the problem in some other way if(this->getPortType() == "POWERPORT") { this->setRotation(0.0); mpPortLabel->setRotation(0.0); } else { this->setRotation(mpPortAppearance->rot); mpPortLabel->setRotation(-mpPortAppearance->rot); } mMag = 1.6180339887; mIsMag = false; isConnected = false; MainWindow *pMainWindow = mpParentGuiObject->mpParentGraphicsScene->mpParentProjectTab->mpParentProjectTabWidget->mpParentMainWindow; connect(this,SIGNAL(portClicked(GUIPort*)),this->getParentView(),SLOT(addConnector(GUIPort*))); connect(pMainWindow->hidePortsAction,SIGNAL(triggered(bool)),this, SLOT(hideIfNotConnected(bool))); //connect(pMainWindow->showPortsAction,SIGNAL(triggered()),this, SLOT(showIfNotConnected())); } GUIPort::~GUIPort() { } //! Magnify the port with a class mebmer factor 'mMag'. Is used i.e. at hovering over disconnected port. //! @param blowup says if the port should be magnified or not. void GUIPort::magnify(bool blowup) { if ((!blowup) && (mIsMag)) { this->moveBy((mMag-1)*boundingRect().width()/2, (mMag-1)*boundingRect().height()/2); this->scale(1/mMag,1/mMag); this->mpPortLabel->scale(mMag,mMag); mIsMag = false; } else if ((blowup) && (!mIsMag)) { this->scale(mMag, mMag); this->moveBy(-(mMag-1)*boundingRect().width()/2, -(mMag-1)*boundingRect().height()/2); this->mpPortLabel->scale(1/mMag,1/mMag); mIsMag = true; } } //! Defines what happens when mouse cursor begins to hover a port. //! @param *event defines the mouse event. void GUIPort::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsSvgItem::hoverEnterEvent(event); this->setCursor(Qt::CrossCursor); QBrush brush(Qt::blue); std::cout << "GUIPort.cpp: " << "hovering over port" << std::endl; magnify(true); mpPortLabel->setRotation(-this->mpParentGuiObject->rotation()-this->rotation()); //qDebug() << "label: " << mpPortLabel->rotation() << " this: " << this->rotation(); this->setZValue(1.0); mpPortLabel->show(); } void GUIPort::updatePosition() { if(mpParentGuiObject->rotation() == 0) setPos(mXpos-this->boundingRect().width()/2.0, mYpos-this->boundingRect().height()/2.0); else if(mpParentGuiObject->rotation() == 90) setPos(mXpos-this->boundingRect().width()/2.0, mYpos+this->boundingRect().height()/2.0); else if(mpParentGuiObject->rotation() == 180) setPos(mXpos+this->boundingRect().width()/2.0, mYpos+this->boundingRect().height()/2.0); else setPos(mXpos+this->boundingRect().width()/2.0, mYpos-this->boundingRect().height()/2.0); } //! Defines what happens when mouse cursor stops hovering a port. //! @param *event defines the mouse event. void GUIPort::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsSvgItem::hoverLeaveEvent(event); QBrush brush(Qt::green); //this->setBrush(brush); this->setCursor(Qt::ArrowCursor); magnify(false); mpPortLabel->hide(); this->setZValue(0.0); } //! Defines what happens when clicking on a port. //! @param *event defines the mouse event. void GUIPort::mousePressEvent(QGraphicsSceneMouseEvent *event) { //QGraphicsItem::mousePressEvent(event); //Don't work if this is called if (event->button() == Qt::LeftButton) { std::cout << "GUIPort.cpp: " << "portClick emitted\n"; emit portClicked(this); } else if (event->button() == Qt::RightButton) { std::cout << "GUIPort.cpp: " << "RightClick" << std::endl; } magnify(false); } void GUIPort::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { std::cout << "GUIPort.cpp: " << "contextMenuEvent" << std::endl; if ((!this->isConnected) || (this->mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getTimeVector(getGUIComponentName(), this->getName()).empty())) { event->ignore(); } else { QMenu menu; //! @todo this bellow is complete madness. hardcoded hopsan specific stuff, must be rewritten, not sure if it should even be here //! @todo we do not need hardcoded stuff we can ask the core about what variables are available if (this->getNodeType() =="NodeHydraulic") { QAction *plotPressureAction = menu.addAction("Plot pressure"); QAction *plotFlowAction = menu.addAction("Plot flow"); QAction *selectedAction = menu.exec(event->screenPos()); if (selectedAction == plotFlowAction) { plot("MassFlow"); } if (selectedAction == plotPressureAction) { plot("Pressure"); } } if (this->getNodeType() =="NodeMechanic") { QAction *plotVelocityAction = menu.addAction("Plot velocity"); QAction *plotForceAction = menu.addAction("Plot force"); QAction *plotPositionAction = menu.addAction("Plot position"); QAction *selectedAction = menu.exec(event->screenPos()); if (selectedAction == plotVelocityAction) { plot("Velocity"); } if (selectedAction == plotForceAction) { plot("Force"); } if (selectedAction == plotPositionAction) { plot("Position"); } } if (this->getNodeType() =="NodeSignal") { QAction *plotSignalAction = menu.addAction("Plot signal value"); QAction *selectedAction = menu.exec(event->screenPos()); if (selectedAction == plotSignalAction) { plot("Value"); } } } } //! Returns a pointer to the GraphicsView that the port belongs to. GraphicsView *GUIPort::getParentView() { return mpParentGraphicsView; } //! Returns a pointer to the GUIComponent the port belongs to. GUIObject *GUIPort::getGuiObject() { return mpParentGuiObject; } //! Plots the varable number 'nVar' in the node the port is connected to. //! @param nVar tells which variable to plot. //! @todo If dataUnit not supplied no unit will be shown, we should maybe lookup the unit if not supplid, or allways look it up, or demand that it is supplied void GUIPort::plot(QString dataName, QString dataUnit) //En del vansinne i denna metoden... { std::cout << "GUIPort.cpp: " << "Plot()" << std::endl; QVector<double> time = QVector<double>::fromStdVector(mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getTimeVector(getGUIComponentName(), this->getName())); QVector<double> y; mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getPlotData(getGUIComponentName(), this->getName(), dataName, y); qDebug() << "Time size: " << time.size() << " last time: " << *time.end() << " " << "y.size(): " << y.size(); qDebug() << "time[0]: " << time[0] << " time[last-1]: " << time[time.size()-2] << " time[last]: " << time[time.size()-1]; for (int i = 0; i<time.size(); ++i) { //qDebug() << time[i]; } qDebug() << "y[0]: " << y[0] << " y[last-1]: " << y[y.size()-2] << " y[last]: " << y[y.size()-1]; QString title; QString xlabel; QString ylabel; title.append(dataName); ylabel.append(dataName + ", [" + dataUnit + "]"); //! @todo need to comment this out for now fix later //title.append(" at component: ").append(QString::fromStdString(mpParentComponent->mpCoreComponent->getName())).append(", port: ").append(QString::fromStdString(mpCorePort->getPortName())); xlabel.append("Time, [s]"); //PlotWidget *newPlot = new PlotWidget(time,y,mpParentGuiObject->mpParentGraphicsView); PlotWidget *newPlot = new PlotWidget(time,y,mpParentGuiObject->mpParentGraphicsView->mpParentProjectTab->mpParentProjectTabWidget->mpParentMainWindow); //newPlot->mpVariablePlot->setTitle(title); newPlot->mpCurve->setTitle(title); newPlot->mpVariablePlot->setAxisTitle(VariablePlot::yLeft, ylabel); newPlot->mpVariablePlot->setAxisTitle(VariablePlot::xBottom, xlabel); newPlot->mpVariablePlot->insertLegend(new QwtLegend(), QwtPlot::TopLegend); newPlot->show(); } //! Returns the number of the port by calling the equivalent function in the parent component. int GUIPort::getPortNumber() { return this->getGuiObject()->getPortNumber(this); } //! Wrapper for the Core getPortTypeString() function QString GUIPort::getPortType() { return this->mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getPortType(getGUIComponentName(), this->getName()); } //! Wrapper for the Core getNodeType() function QString GUIPort::getNodeType() { return this->mpParentGraphicsView->mpParentProjectTab->mGUIRootSystem.getNodeType(getGUIComponentName(), this->getName()); } PortAppearance::portDirectionType GUIPort::getPortDirection() { return mpPortAppearance->direction; } void GUIPort::setPortDirection(PortAppearance::portDirectionType direction) { mpPortAppearance->direction = direction; } QString GUIPort::getName() { return this->name; } void GUIPort::setDisplayName(const QString name) { this->name = name; QString label("<p><span style=\"background-color:lightyellow\">"); label.append(this->name).append("</span></p>"); mpPortLabel->setHtml(label); } //! Get the name of the GUIComponent or GUISubsystem that the port is connected to, This is not necessarily the same as the parent GUIObject name (SystemPorts) //! @todo this is a very ugly way of handeling system ports should try to think of something better QString GUIPort::getGUIComponentName() { if (mpGUIRootSystem == 0) { qDebug() << "return guiobject name: " << mpParentGuiObject->getName(); return mpParentGuiObject->getName(); } else { qDebug() << "return root name: " << mpGUIRootSystem->getName(); return mpGUIRootSystem->getName(); } } void GUIPort::hideIfNotConnected(bool justDoIt) { if(!isConnected and justDoIt) { this->hide(); } else if(!isConnected and !justDoIt) { this->show(); } } <|endoftext|>
<commit_before>#include "Tle.h" #include <cassert> #include <cstdlib> Tle::Tle(const std::string& line_one, const std::string& line_two) { name_.erase(); line_one_ = line_one; line_two_ = line_two; Initialize(); } Tle::Tle(const std::string& name, const std::string& line_one, const std::string& line_two) { name_ = name; line_one_ = line_one; line_two_ = line_two; Initialize(); } Tle::Tle(const Tle& tle) { name_ = tle.name_; line_one_ = tle.line_one_; line_two_ = tle.line_two_; norad_number_ = tle.norad_number_; international_designator_ = tle.international_designator_; epoch_ = tle.epoch_; mean_motion_dot_ = tle.mean_motion_dot_; mean_motion_dot2_ = tle.mean_motion_dot2_; bstar_ = tle.bstar_; inclination_ = tle.inclination_; right_ascending_node_ = tle.right_ascending_node_; eccentricity_ = tle.eccentricity_; argument_perigee_ = tle.argument_perigee_; mean_anomaly_ = tle.mean_anomaly_; mean_motion_ = tle.mean_motion_; orbit_number_ = tle.orbit_number_; } Tle::~Tle() { } /* * convert a tle raw string into an exponent string */ std::string Tle::ExpToDecimal(const std::string& str) { static const int START_SIGN = 0; static const int LENGTH_SIGN = 1; static const int START_MANTISSA = 1; static const int LENGTH_MANTISSA = 5; static const int START_EXP = 6; static const int LENGTH_EXP = 2; assert(8 == str.length()); std::string value = str.substr(START_SIGN, LENGTH_SIGN); value += "."; value += str.substr(START_MANTISSA, LENGTH_MANTISSA); value += "e"; value += str.substr(START_EXP, LENGTH_EXP); return value; } /* * extract all variables */ void Tle::Initialize() { std::string temp; /* * trim whitespace */ TrimLeft(name_); TrimRight(name_); TrimLeft(line_one_); TrimRight(line_one_); TrimLeft(line_two_); TrimRight(line_two_); /* * check the two lines are valid */ assert(IsValidPair(line_one_, line_two_)); /* * line 1 */ temp = line_one_.substr(TLE1_COL_NORADNUM, TLE1_LEN_NORADNUM).c_str(); norad_number_ = atoi(temp.c_str()); /* * if blank use norad number */ if (name_.empty()) name_ = temp; international_designator_ = line_one_.substr(TLE1_COL_INTLDESC_A, TLE1_LEN_INTLDESC_A + TLE1_LEN_INTLDESC_B + TLE1_LEN_INTLDESC_C); int year = atoi(line_one_.substr(TLE1_COL_EPOCH_A, TLE1_LEN_EPOCH_A).c_str()); double day = atof(line_one_.substr(TLE1_COL_EPOCH_B, TLE1_LEN_EPOCH_B).c_str()); /* * generate julian date for epoch */ if (year < 57) year += 2000; else year += 1900; epoch_ = Julian(year, day); if (line_one_[TLE1_COL_MEANMOTIONDT] == '-') { temp = "-0"; } else temp = "0"; temp += line_one_.substr(TLE1_COL_MEANMOTIONDT + 1, TLE1_LEN_MEANMOTIONDT); mean_motion_dot_ = atof(temp.c_str()); temp = ExpToDecimal(line_one_.substr(TLE1_COL_MEANMOTIONDT2, TLE1_LEN_MEANMOTIONDT2)); mean_motion_dot2_ = atof(temp.c_str()); temp = ExpToDecimal(line_one_.substr(TLE1_COL_BSTAR, TLE1_LEN_BSTAR).c_str()); bstar_ = atof(temp.c_str()); /* * line 2 */ temp = line_two_.substr(TLE2_COL_INCLINATION, TLE2_LEN_INCLINATION); TrimLeft(temp); inclination_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_RAASCENDNODE, TLE2_LEN_RAASCENDNODE); TrimLeft(temp); right_ascending_node_ = atof(temp.c_str()); temp = "0."; temp += line_two_.substr(TLE2_COL_ECCENTRICITY, TLE2_LEN_ECCENTRICITY); eccentricity_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_ARGPERIGEE, TLE2_LEN_ARGPERIGEE); TrimLeft(temp); argument_perigee_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_MEANANOMALY, TLE2_LEN_MEANANOMALY); TrimLeft(temp); mean_anomaly_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_MEANMOTION, TLE2_LEN_MEANMOTION); TrimLeft(temp); mean_motion_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_REVATEPOCH, TLE2_LEN_REVATEPOCH); TrimLeft(temp); orbit_number_ = atoi(temp.c_str()); } /* * check the two lines have matching norad numbers * and that the lines themselves are valid */ bool Tle::IsValidPair(const std::string& line1, const std::string& line2) { if (atoi(line1.substr(TLE1_COL_NORADNUM, TLE1_LEN_NORADNUM).c_str()) != atoi(line2.substr(TLE2_COL_NORADNUM, TLE2_LEN_NORADNUM).c_str())) return false; if (!IsValidLine(line1, 1)) return false; if (!IsValidLine(line2, 2)) return false; return true; } /* * validate a line */ bool Tle::IsValidLine(const std::string& str, const unsigned char line_number) { static const std::string line1_pattern = "1 NNNNNC NNNNAAAA NNNNN.NNNNNNNN +.NNNNNNNN +NNNNN-N +NNNNN-N N NNNNN"; static const std::string line2_pattern = "2 NNNNN NNN.NNNN NNN.NNNN NNNNNNN NNN.NNNN NNN.NNNN NN.NNNNNNNNNNNNNN"; /* * validate line against the pattern */ if (1 == line_number) { if (!ValidateLine(str, line1_pattern)) return false; } else if (2 == line_number) { if (!ValidateLine(str, line2_pattern)) return false; } /* * last char in string is modulo 10 checksum * edited out as checksum isnt consistent * * int chk = CheckSum(str); * if (chk != (str[TLE_LEN_LINE_DATA - 1] - '0')) * return false; */ return true; } /* * validate line given a pattern */ bool Tle::ValidateLine(const std::string& line, const std::string& pattern) { /* * check length of lines match */ if (line.length() < pattern.length()) { return false; } std::string::const_iterator pattern_itr = pattern.begin(); std::string::const_iterator line_itr = line.begin(); while (pattern_itr != pattern.end()) { if (isdigit(*pattern_itr) || *pattern_itr == ' ' || *pattern_itr == '.') { /* * these characters should match exactly */ if (*pattern_itr != *line_itr) return false; } else if (*pattern_itr == 'N') { /* * if pattern value is 'N' then either a number or a ' ' */ if (!isdigit(*line_itr) && *line_itr != ' ') return false; } else if (*pattern_itr == '+') { /* * if pattern value is '+' then either a '+' or a ' ' */ if (*line_itr != '+' && *line_itr != '-' && *line_itr != ' ') return false; } else if (*pattern_itr == '-') { /* * if pattern value is '+' or a '+' */ if (*line_itr != '+' && *line_itr != '-') return false; } pattern_itr++; line_itr++; } return true; } /* * compute checksum */ int Tle::CheckSum(const std::string& str) { size_t len = str.size() - 1; int xsum = 0; for (size_t i = 0; i < len; i++) { char ch = str[i]; if (isdigit(ch)) xsum += (ch - '0'); else if (ch == '-') xsum++; } return (xsum % 10); } /* * trim left of string */ void Tle::TrimLeft(std::string& str) { std::string whitespaces(" \t\f\n\r"); if (!str.empty()) { std::string::size_type pos = str.find_first_not_of(whitespaces); if (pos != std::string::npos) str.erase(0, pos); else str.clear(); } } /* * trim right of string */ void Tle::TrimRight(std::string& str) { std::string whitespaces(" \t\f\n\r"); if (!str.empty()) { std::string::size_type pos = str.find_last_not_of(whitespaces); if (pos != std::string::npos) str.erase(pos + 1); else str.clear(); } } <commit_msg>Changes to tle rules<commit_after>#include "Tle.h" #include <cassert> #include <cstdlib> Tle::Tle(const std::string& line_one, const std::string& line_two) { name_.erase(); line_one_ = line_one; line_two_ = line_two; Initialize(); } Tle::Tle(const std::string& name, const std::string& line_one, const std::string& line_two) { name_ = name; line_one_ = line_one; line_two_ = line_two; Initialize(); } Tle::Tle(const Tle& tle) { name_ = tle.name_; line_one_ = tle.line_one_; line_two_ = tle.line_two_; norad_number_ = tle.norad_number_; international_designator_ = tle.international_designator_; epoch_ = tle.epoch_; mean_motion_dot_ = tle.mean_motion_dot_; mean_motion_dot2_ = tle.mean_motion_dot2_; bstar_ = tle.bstar_; inclination_ = tle.inclination_; right_ascending_node_ = tle.right_ascending_node_; eccentricity_ = tle.eccentricity_; argument_perigee_ = tle.argument_perigee_; mean_anomaly_ = tle.mean_anomaly_; mean_motion_ = tle.mean_motion_; orbit_number_ = tle.orbit_number_; } Tle::~Tle() { } /* * convert a tle raw string into an exponent string */ std::string Tle::ExpToDecimal(const std::string& str) { static const int START_SIGN = 0; static const int LENGTH_SIGN = 1; static const int START_MANTISSA = 1; static const int LENGTH_MANTISSA = 5; static const int START_EXP = 6; static const int LENGTH_EXP = 2; assert(8 == str.length()); std::string value = str.substr(START_SIGN, LENGTH_SIGN); value += "."; value += str.substr(START_MANTISSA, LENGTH_MANTISSA); value += "e"; value += str.substr(START_EXP, LENGTH_EXP); return value; } /* * extract all variables */ void Tle::Initialize() { std::string temp; /* * trim whitespace */ TrimLeft(name_); TrimRight(name_); TrimLeft(line_one_); TrimRight(line_one_); TrimLeft(line_two_); TrimRight(line_two_); /* * check the two lines are valid */ assert(IsValidPair(line_one_, line_two_)); /* * line 1 */ temp = line_one_.substr(TLE1_COL_NORADNUM, TLE1_LEN_NORADNUM).c_str(); norad_number_ = atoi(temp.c_str()); /* * if blank use norad number */ if (name_.empty()) name_ = temp; international_designator_ = line_one_.substr(TLE1_COL_INTLDESC_A, TLE1_LEN_INTLDESC_A + TLE1_LEN_INTLDESC_B + TLE1_LEN_INTLDESC_C); int year = atoi(line_one_.substr(TLE1_COL_EPOCH_A, TLE1_LEN_EPOCH_A).c_str()); double day = atof(line_one_.substr(TLE1_COL_EPOCH_B, TLE1_LEN_EPOCH_B).c_str()); /* * generate julian date for epoch */ if (year < 57) year += 2000; else year += 1900; epoch_ = Julian(year, day); if (line_one_[TLE1_COL_MEANMOTIONDT] == '-') { temp = "-0"; } else temp = "0"; temp += line_one_.substr(TLE1_COL_MEANMOTIONDT + 1, TLE1_LEN_MEANMOTIONDT); mean_motion_dot_ = atof(temp.c_str()); temp = ExpToDecimal(line_one_.substr(TLE1_COL_MEANMOTIONDT2, TLE1_LEN_MEANMOTIONDT2)); mean_motion_dot2_ = atof(temp.c_str()); temp = ExpToDecimal(line_one_.substr(TLE1_COL_BSTAR, TLE1_LEN_BSTAR).c_str()); bstar_ = atof(temp.c_str()); /* * line 2 */ temp = line_two_.substr(TLE2_COL_INCLINATION, TLE2_LEN_INCLINATION); TrimLeft(temp); inclination_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_RAASCENDNODE, TLE2_LEN_RAASCENDNODE); TrimLeft(temp); right_ascending_node_ = atof(temp.c_str()); temp = "0."; temp += line_two_.substr(TLE2_COL_ECCENTRICITY, TLE2_LEN_ECCENTRICITY); eccentricity_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_ARGPERIGEE, TLE2_LEN_ARGPERIGEE); TrimLeft(temp); argument_perigee_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_MEANANOMALY, TLE2_LEN_MEANANOMALY); TrimLeft(temp); mean_anomaly_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_MEANMOTION, TLE2_LEN_MEANMOTION); TrimLeft(temp); mean_motion_ = atof(temp.c_str()); temp = line_two_.substr(TLE2_COL_REVATEPOCH, TLE2_LEN_REVATEPOCH); TrimLeft(temp); orbit_number_ = atoi(temp.c_str()); } /* * check the two lines have matching norad numbers * and that the lines themselves are valid */ bool Tle::IsValidPair(const std::string& line1, const std::string& line2) { if (!IsValidLine(line1, 1)) return false; if (!IsValidLine(line2, 2)) return false; if (atoi(line1.substr(TLE1_COL_NORADNUM, TLE1_LEN_NORADNUM).c_str()) != atoi(line2.substr(TLE2_COL_NORADNUM, TLE2_LEN_NORADNUM).c_str())) return false; return true; } /* * validate a line */ bool Tle::IsValidLine(const std::string& str, const unsigned char line_number) { static const std::string line1_pattern = "1 NNNNNC XXXXXXXX NNNNN.NNNNNNNN +.NNNNNNNN +NNNNN-N +NNNNN-N N NNNNN"; static const std::string line2_pattern = "2 NNNNN NNN.NNNN NNN.NNNN NNNNNNN NNN.NNNN NNN.NNNN NN.NNNNNNNNNNNNNN"; /* * validate line against the pattern */ if (1 == line_number) { if (!ValidateLine(str, line1_pattern)) return false; } else if (2 == line_number) { if (!ValidateLine(str, line2_pattern)) return false; } /* * last char in string is modulo 10 checksum * edited out as checksum isnt consistent * * int chk = CheckSum(str); * if (chk != (str[TLE_LEN_LINE_DATA - 1] - '0')) * return false; */ return true; } /* * validate line given a pattern */ bool Tle::ValidateLine(const std::string& line, const std::string& pattern) { /* * check length of lines match */ if (line.length() < pattern.length()) { return false; } std::string::const_iterator pattern_itr = pattern.begin(); std::string::const_iterator line_itr = line.begin(); while (pattern_itr != pattern.end()) { if (isdigit(*pattern_itr) || *pattern_itr == ' ' || *pattern_itr == '.') { /* * these characters should match exactly */ if (*pattern_itr != *line_itr) return false; } else if (*pattern_itr == 'N') { /* * if pattern value is 'N' then either a number or a ' ' */ if (!isdigit(*line_itr) && *line_itr != ' ') return false; } else if (*pattern_itr == '+') { /* * if pattern value is '+' then either a '+' or '-' or ' ' or '0' */ if (*line_itr != '+' && *line_itr != '-' && *line_itr != ' ' && *line_itr != '0') return false; } else if (*pattern_itr == '-') { /* * if pattern value is '+' or '-' */ if (*line_itr != '+' && *line_itr != '-') return false; } pattern_itr++; line_itr++; } return true; } /* * compute checksum */ int Tle::CheckSum(const std::string& str) { size_t len = str.size() - 1; int xsum = 0; for (size_t i = 0; i < len; i++) { char ch = str[i]; if (isdigit(ch)) xsum += (ch - '0'); else if (ch == '-') xsum++; } return (xsum % 10); } /* * trim left of string */ void Tle::TrimLeft(std::string& str) { std::string whitespaces(" \t\f\n\r"); if (!str.empty()) { std::string::size_type pos = str.find_first_not_of(whitespaces); if (pos != std::string::npos) str.erase(0, pos); else str.clear(); } } /* * trim right of string */ void Tle::TrimRight(std::string& str) { std::string whitespaces(" \t\f\n\r"); if (!str.empty()) { std::string::size_type pos = str.find_last_not_of(whitespaces); if (pos != std::string::npos) str.erase(pos + 1); else str.clear(); } } <|endoftext|>
<commit_before> // This work derives from Vittorio Romeo's code used for cppcon 2015 licensed under the Academic Free License. // His code is available here: https://github.com/SuperV1234/cppcon2015 #ifndef EC_MANAGER_HPP #define EC_MANAGER_HPP #define EC_INIT_ENTITIES_SIZE 256 #define EC_GROW_SIZE_AMOUNT 256 #include <cstddef> #include <vector> #include <tuple> #include <utility> #include "Meta/Combine.hpp" #include "Meta/Matching.hpp" #include "Bitset.hpp" namespace EC { template <typename ComponentsList, typename TagsList> struct Manager { public: using Combined = EC::Meta::Combine<ComponentsList, TagsList>; using BitsetType = EC::Bitset<ComponentsList, TagsList>; private: template <typename... Types> struct Storage { using type = std::tuple<std::vector<Types>... >; }; using ComponentsStorage = typename EC::Meta::Morph<ComponentsList, Storage<> >::type; // Entity: isAlive, dataIndex, ComponentsTags Info using EntitiesTupleType = std::tuple<bool, std::size_t, BitsetType>; using EntitiesType = std::vector<EntitiesTupleType>; EntitiesType entities; ComponentsStorage componentsStorage; std::size_t currentCapacity = 0; std::size_t currentSize = 0; public: Manager() { resize(EC_INIT_ENTITIES_SIZE); } private: void resize(std::size_t newCapacity) { if(currentCapacity >= newCapacity) { return; } EC::Meta::forEach<ComponentsList>([this, newCapacity] (auto t) { std::get<std::vector<decltype(t)> >(this->componentsStorage).resize(newCapacity); }); entities.resize(newCapacity); for(std::size_t i = currentCapacity; i < newCapacity; ++i) { entities[i] = std::make_tuple(false, i, BitsetType{}); } currentCapacity = newCapacity; } public: std::size_t addEntity() { if(currentSize == currentCapacity) { resize(currentCapacity + EC_GROW_SIZE_AMOUNT); } std::get<bool>(entities[currentSize]) = true; return currentSize++; } void deleteEntity(std::size_t index) { std::get<bool>(entities.at(index)) = false; } bool hasEntity(std::size_t index) const { return index < currentSize; } bool isAlive(std::size_t index) const { return hasEntity(index) && std::get<bool>(entities.at(index)); } const EntitiesTupleType& getEntityInfo(std::size_t index) const { return entities.at(index); } template <typename Component> Component& getEntityData(std::size_t index) { return std::get<std::vector<Component> >(componentsStorage).at(std::get<std::size_t>(entities.at(index))); } template <typename Component> bool hasComponent(std::size_t index) const { return std::get<BitsetType>(entities.at(index)).template getComponentBit<Component>(); } template <typename Tag> bool hasTag(std::size_t index) const { return std::get<BitsetType>(entities.at(index)).template getTagBit<Tag>(); } void cleanup() { if(currentSize == 0) { return; } std::size_t rhs = currentSize - 1; std::size_t lhs = 0; while(lhs < rhs) { while(!std::get<bool>(entities[rhs])) { if(rhs == 0) { currentSize = 0; return; } --rhs; } if(lhs >= rhs) { break; } else if(!std::get<bool>(entities[lhs])) { // lhs is marked for deletion // swap lhs entity with rhs entity std::swap(entities[lhs], entities.at(rhs)); // clear deleted bitset std::get<BitsetType>(entities[rhs]).reset(); // inc/dec pointers ++lhs; --rhs; } else { ++lhs; } } currentSize = rhs + 1; } template <typename Component, typename... Args> void addComponent(std::size_t entityID, Args&&... args) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } Component component(std::forward<Args>(args)...); std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = true; std::get<std::vector<Component> >(componentsStorage)[std::get<std::size_t>(entities[entityID])] = std::move(component); } template <typename Component> void removeComponent(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = false; } template <typename Tag> void addTag(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = true; } template <typename Tag> void removeTag(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = false; } private: template <typename... Types> struct ForMatchingSignatureHelper { template <typename CType, typename Function> static void call(std::size_t entityID, CType& ctype, Function&& function) { function( entityID, ctype.template getEntityData<Types>(entityID)... ); } }; public: template <typename Signature, typename Function> void forMatchingSignature(Function&& function) { using SignatureComponents = typename EC::Meta::Matching<Signature, ComponentsList>::type; using Helper = EC::Meta::Morph<SignatureComponents, ForMatchingSignatureHelper<> >; BitsetType signatureBitset = BitsetType::template generateBitset<Signature>(); for(std::size_t i = 0; i < currentSize; ++i) { if(!std::get<bool>(entities[i])) { continue; } if((signatureBitset & std::get<BitsetType>(entities[i])) == signatureBitset) { Helper::call(i, *this, std::forward<Function>(function)); } } } }; } #endif /*! \class EC::Manager \brief Manages an EntityComponent system. EC::Manager must be created with a list of all used Components and all used tags. Note that all components must have a default constructor. Example: \code{.cpp} EC::Manager<TypeList<C0, C1, C2>, TypeList<T0, T1>> manager; \endcode */ /*! \fn EC::Manager::Manager() \brief Initializes the manager with a default capacity. The default capacity is set with macro EC_INIT_ENTITIES_SIZE, and will grow by amounts of EC_GROW_SIZE_AMOUNT when needed. */ /*! \fn std::size_t EC::Manager::addEntity() \brief Adds an entity to the system, returning the ID of the entity. WARNING: The ID of an entity may change after calls to cleanup(). Usage of entity IDs should be safe during initialization. Otherwise, only use the ID given during usage of forMatchingSignature(). */ /*! \fn void EC::Manager::deleteEntity(std::size_t index) \brief Marks an entity for deletion. A deleted Entity is not actually deleted until cleanup() is called. While an Entity is "deleted" but still in the system, calls to forMatchingSignature() will ignore the Entity. */ /*! \fn bool EC::Manager::hasEntity(std::size_t index) const \brief Checks if the Entity with the given ID is in the system. Note that deleted Entities that haven't yet been cleaned up (via cleanup()) are considered still in the system. */ /*! \fn bool EC::Manager::isAlive(std::size_t index) const \brief Checks if the Entity is not marked as deleted. Note that invalid Entities (Entities where calls to hasEntity() returns false) will return false. */ /*! \fn const EntitiesTupleType& EC::Manager::getEntityInfo(std::size_t index) const \brief Returns a const reference to an Entity's info. An Entity's info is a std::tuple with a bool, std::size_t, and a bitset. \n The bool determines if the Entity is alive. \n The std::size_t is the ID to this Entity's data in the system. \n The bitset shows what Components and Tags belong to the Entity. */ /*! \fn Component& EC::Manager::getEntityData(std::size_t index) \brief Returns a reference to a component belonging to the given Entity. This function will return a reference to a Component regardless of whether or not the Entity actually owns the reference. If the Entity doesn't own the Component, changes to the Component will not affect any Entity. It is recommended to use hasComponent() to determine if the Entity actually owns that Component. */ /*! \fn bool EC::Manager::hasComponent(std::size_t index) const \brief Checks whether or not the given Entity has the given Component. Example: \code{.cpp} manager.hasComponent<C0>(entityID); \endcode */ /*! \fn bool EC::Manager::hasTag(std::size_t index) const \brief Checks whether or not the given Entity has the given Tag. Example: \code{.cpp} manager.hasTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::cleanup() \brief Does garbage collection on Entities. Does housekeeping on the vector containing Entities that will result in entity IDs changing if some Entities were marked for deletion. <b>This function should be called periodically to correctly handle deletion of entities.</b> */ /*! \fn void EC::Manager::addComponent(std::size_t entityID, Args&&... args) \brief Adds a component to the given Entity. Additional parameters given to this function will construct the Component with those parameters. Note that if the Entity already has the same component, then it will be overwritten by the newly created Component with the given arguments. Example: \code{.cpp} struct C0 { // constructor is compatible as a default constructor C0(int a = 0, char b = 'b') : a(a), b(b) {} int a; char b; } manager.addComponent<C0>(entityID, 10, 'd'); \endcode */ /*! \fn void EC::Manager::removeComponent(std::size_t entityID) \brief Removes the given Component from the given Entity. If the Entity does not have the Component given, nothing will change. Example: \code{.cpp} manager.removeComponent<C0>(entityID); \endcode */ /*! \fn void EC::Manager::addTag(std::size_t entityID) \brief Adds the given Tag to the given Entity. Example: \code{.cpp} manager.addTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::removeTag(std::size_t entityID) \brief Removes the given Tag from the given Entity. If the Entity does not have the Tag given, nothing will change. Example: \code{.cpp} manager.removeTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::forMatchingSignature(Function&& function) \brief Calls the given function on all Entities matching the given Signature. The function object given to this function must accept std::size_t as its first parameter and Component references for the rest of the parameters. Tags specified in the Signature are only used as filters and will not be given as a parameter to the function. Example: \code{.cpp} manager.forMatchingSignature<TypeList<C0, C1, T0>>([] (std::size_t ID, C0& component0, C1& component1) { // Lambda function contents here. }); \endcode Note, the ID given to the function is not permanent. An entity's ID may change when cleanup() is called. */ <commit_msg>Temporary(?) bugfix<commit_after> // This work derives from Vittorio Romeo's code used for cppcon 2015 licensed under the Academic Free License. // His code is available here: https://github.com/SuperV1234/cppcon2015 #ifndef EC_MANAGER_HPP #define EC_MANAGER_HPP #define EC_INIT_ENTITIES_SIZE 256 #define EC_GROW_SIZE_AMOUNT 256 #include <cstddef> #include <vector> #include <tuple> #include <utility> #include "Meta/Combine.hpp" #include "Meta/Matching.hpp" #include "Bitset.hpp" namespace EC { template <typename ComponentsList, typename TagsList> struct Manager { public: using Combined = EC::Meta::Combine<ComponentsList, TagsList>; using BitsetType = EC::Bitset<ComponentsList, TagsList>; private: template <typename... Types> struct Storage { using type = std::tuple<std::vector<Types>... >; }; using ComponentsStorage = typename EC::Meta::Morph<ComponentsList, Storage<> >::type; // Entity: isAlive, dataIndex, ComponentsTags Info using EntitiesTupleType = std::tuple<bool, std::size_t, BitsetType>; using EntitiesType = std::vector<EntitiesTupleType>; EntitiesType entities; ComponentsStorage componentsStorage; std::size_t currentCapacity = 0; std::size_t currentSize = 0; public: Manager() { resize(EC_INIT_ENTITIES_SIZE); } private: void resize(std::size_t newCapacity) { if(currentCapacity >= newCapacity) { return; } EC::Meta::forEach<ComponentsList>([this, newCapacity] (auto t) { std::get<std::vector<decltype(t)> >(this->componentsStorage).resize(newCapacity); }); entities.resize(newCapacity); for(std::size_t i = currentCapacity; i < newCapacity; ++i) { entities[i] = std::make_tuple(false, i, BitsetType{}); } currentCapacity = newCapacity; } public: std::size_t addEntity() { if(currentSize == currentCapacity) { resize(currentCapacity + EC_GROW_SIZE_AMOUNT); } std::get<bool>(entities[currentSize]) = true; // TODO This shouldn't be necessary, but there is a bug std::get<BitsetType>(entities[currentSize]).reset(); return currentSize++; } void deleteEntity(std::size_t index) { std::get<bool>(entities.at(index)) = false; } bool hasEntity(std::size_t index) const { return index < currentSize; } bool isAlive(std::size_t index) const { return hasEntity(index) && std::get<bool>(entities.at(index)); } const EntitiesTupleType& getEntityInfo(std::size_t index) const { return entities.at(index); } template <typename Component> Component& getEntityData(std::size_t index) { return std::get<std::vector<Component> >(componentsStorage).at(std::get<std::size_t>(entities.at(index))); } template <typename Component> bool hasComponent(std::size_t index) const { return std::get<BitsetType>(entities.at(index)).template getComponentBit<Component>(); } template <typename Tag> bool hasTag(std::size_t index) const { return std::get<BitsetType>(entities.at(index)).template getTagBit<Tag>(); } void cleanup() { if(currentSize == 0) { return; } std::size_t rhs = currentSize - 1; std::size_t lhs = 0; while(lhs < rhs) { while(!std::get<bool>(entities[rhs])) { if(rhs == 0) { currentSize = 0; return; } --rhs; } if(lhs >= rhs) { break; } else if(!std::get<bool>(entities[lhs])) { // lhs is marked for deletion // swap lhs entity with rhs entity std::swap(entities[lhs], entities.at(rhs)); // clear deleted bitset std::get<BitsetType>(entities[rhs]).reset(); // inc/dec pointers ++lhs; --rhs; } else { ++lhs; } } currentSize = rhs + 1; } template <typename Component, typename... Args> void addComponent(std::size_t entityID, Args&&... args) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } Component component(std::forward<Args>(args)...); std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = true; std::get<std::vector<Component> >(componentsStorage)[std::get<std::size_t>(entities[entityID])] = std::move(component); } template <typename Component> void removeComponent(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = false; } template <typename Tag> void addTag(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = true; } template <typename Tag> void removeTag(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = false; } private: template <typename... Types> struct ForMatchingSignatureHelper { template <typename CType, typename Function> static void call(std::size_t entityID, CType& ctype, Function&& function) { function( entityID, ctype.template getEntityData<Types>(entityID)... ); } }; public: template <typename Signature, typename Function> void forMatchingSignature(Function&& function) { using SignatureComponents = typename EC::Meta::Matching<Signature, ComponentsList>::type; using Helper = EC::Meta::Morph<SignatureComponents, ForMatchingSignatureHelper<> >; BitsetType signatureBitset = BitsetType::template generateBitset<Signature>(); for(std::size_t i = 0; i < currentSize; ++i) { if(!std::get<bool>(entities[i])) { continue; } if((signatureBitset & std::get<BitsetType>(entities[i])) == signatureBitset) { Helper::call(i, *this, std::forward<Function>(function)); } } } }; } #endif /*! \class EC::Manager \brief Manages an EntityComponent system. EC::Manager must be created with a list of all used Components and all used tags. Note that all components must have a default constructor. Example: \code{.cpp} EC::Manager<TypeList<C0, C1, C2>, TypeList<T0, T1>> manager; \endcode */ /*! \fn EC::Manager::Manager() \brief Initializes the manager with a default capacity. The default capacity is set with macro EC_INIT_ENTITIES_SIZE, and will grow by amounts of EC_GROW_SIZE_AMOUNT when needed. */ /*! \fn std::size_t EC::Manager::addEntity() \brief Adds an entity to the system, returning the ID of the entity. WARNING: The ID of an entity may change after calls to cleanup(). Usage of entity IDs should be safe during initialization. Otherwise, only use the ID given during usage of forMatchingSignature(). */ /*! \fn void EC::Manager::deleteEntity(std::size_t index) \brief Marks an entity for deletion. A deleted Entity is not actually deleted until cleanup() is called. While an Entity is "deleted" but still in the system, calls to forMatchingSignature() will ignore the Entity. */ /*! \fn bool EC::Manager::hasEntity(std::size_t index) const \brief Checks if the Entity with the given ID is in the system. Note that deleted Entities that haven't yet been cleaned up (via cleanup()) are considered still in the system. */ /*! \fn bool EC::Manager::isAlive(std::size_t index) const \brief Checks if the Entity is not marked as deleted. Note that invalid Entities (Entities where calls to hasEntity() returns false) will return false. */ /*! \fn const EntitiesTupleType& EC::Manager::getEntityInfo(std::size_t index) const \brief Returns a const reference to an Entity's info. An Entity's info is a std::tuple with a bool, std::size_t, and a bitset. \n The bool determines if the Entity is alive. \n The std::size_t is the ID to this Entity's data in the system. \n The bitset shows what Components and Tags belong to the Entity. */ /*! \fn Component& EC::Manager::getEntityData(std::size_t index) \brief Returns a reference to a component belonging to the given Entity. This function will return a reference to a Component regardless of whether or not the Entity actually owns the reference. If the Entity doesn't own the Component, changes to the Component will not affect any Entity. It is recommended to use hasComponent() to determine if the Entity actually owns that Component. */ /*! \fn bool EC::Manager::hasComponent(std::size_t index) const \brief Checks whether or not the given Entity has the given Component. Example: \code{.cpp} manager.hasComponent<C0>(entityID); \endcode */ /*! \fn bool EC::Manager::hasTag(std::size_t index) const \brief Checks whether or not the given Entity has the given Tag. Example: \code{.cpp} manager.hasTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::cleanup() \brief Does garbage collection on Entities. Does housekeeping on the vector containing Entities that will result in entity IDs changing if some Entities were marked for deletion. <b>This function should be called periodically to correctly handle deletion of entities.</b> */ /*! \fn void EC::Manager::addComponent(std::size_t entityID, Args&&... args) \brief Adds a component to the given Entity. Additional parameters given to this function will construct the Component with those parameters. Note that if the Entity already has the same component, then it will be overwritten by the newly created Component with the given arguments. Example: \code{.cpp} struct C0 { // constructor is compatible as a default constructor C0(int a = 0, char b = 'b') : a(a), b(b) {} int a; char b; } manager.addComponent<C0>(entityID, 10, 'd'); \endcode */ /*! \fn void EC::Manager::removeComponent(std::size_t entityID) \brief Removes the given Component from the given Entity. If the Entity does not have the Component given, nothing will change. Example: \code{.cpp} manager.removeComponent<C0>(entityID); \endcode */ /*! \fn void EC::Manager::addTag(std::size_t entityID) \brief Adds the given Tag to the given Entity. Example: \code{.cpp} manager.addTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::removeTag(std::size_t entityID) \brief Removes the given Tag from the given Entity. If the Entity does not have the Tag given, nothing will change. Example: \code{.cpp} manager.removeTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::forMatchingSignature(Function&& function) \brief Calls the given function on all Entities matching the given Signature. The function object given to this function must accept std::size_t as its first parameter and Component references for the rest of the parameters. Tags specified in the Signature are only used as filters and will not be given as a parameter to the function. Example: \code{.cpp} manager.forMatchingSignature<TypeList<C0, C1, T0>>([] (std::size_t ID, C0& component0, C1& component1) { // Lambda function contents here. }); \endcode Note, the ID given to the function is not permanent. An entity's ID may change when cleanup() is called. */ <|endoftext|>
<commit_before>/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved. ** ** This file is part of libebml. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact license@matroska.org if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id$ \author Steve Lhomme <robux4 @ users.sf.net> \author Julien Coloos <suiryc @ users.sf.net> */ #include <cassert> #include <string> #include "ebml/EbmlBinary.h" #include "ebml/StdIOCallback.h" START_LIBEBML_NAMESPACE EbmlBinary::EbmlBinary() :EbmlElement(0, false), Data(NULL) {} EbmlBinary::EbmlBinary(const EbmlBinary & ElementToClone) :EbmlElement(ElementToClone) { if (ElementToClone.Data == NULL) Data = NULL; else { Data = (binary *)malloc(GetSize() * sizeof(binary)); assert(Data != NULL); memcpy(Data, ElementToClone.Data, GetSize()); } } EbmlBinary::~EbmlBinary(void) { if(Data) free(Data); } EbmlBinary::operator const binary &() const {return *Data;} filepos_t EbmlBinary::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */) { output.writeFully(Data,GetSize()); return GetSize(); } /*! \note no Default binary value handled */ uint64 EbmlBinary::UpdateSize(bool /* bWithDefault */, bool /* bForceRender */) { return GetSize(); } filepos_t EbmlBinary::ReadData(IOCallback & input, ScopeMode ReadFully) { if (Data != NULL) free(Data); if (ReadFully == SCOPE_NO_DATA) { Data = NULL; return GetSize(); } Data = (binary *)malloc(GetSize()); if (Data == NULL) throw CRTError(std::string("Error allocating data")); SetValueIsSet(); return input.read(Data, GetSize()); } bool EbmlBinary::operator==(const EbmlBinary & ElementToCompare) const { return ((GetSize() == ElementToCompare.GetSize()) && (GetSize() == 0 || !memcmp(Data, ElementToCompare.Data, GetSize()))); } END_LIBEBML_NAMESPACE <commit_msg>EbmlBinary: don't do I/O with a size of 0<commit_after>/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved. ** ** This file is part of libebml. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact license@matroska.org if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id$ \author Steve Lhomme <robux4 @ users.sf.net> \author Julien Coloos <suiryc @ users.sf.net> */ #include <cassert> #include <string> #include "ebml/EbmlBinary.h" #include "ebml/StdIOCallback.h" START_LIBEBML_NAMESPACE EbmlBinary::EbmlBinary() :EbmlElement(0, false), Data(NULL) {} EbmlBinary::EbmlBinary(const EbmlBinary & ElementToClone) :EbmlElement(ElementToClone) { if (ElementToClone.Data == NULL) Data = NULL; else { Data = (binary *)malloc(GetSize() * sizeof(binary)); assert(Data != NULL); memcpy(Data, ElementToClone.Data, GetSize()); } } EbmlBinary::~EbmlBinary(void) { if(Data) free(Data); } EbmlBinary::operator const binary &() const {return *Data;} filepos_t EbmlBinary::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */) { output.writeFully(Data,GetSize()); return GetSize(); } /*! \note no Default binary value handled */ uint64 EbmlBinary::UpdateSize(bool /* bWithDefault */, bool /* bForceRender */) { return GetSize(); } filepos_t EbmlBinary::ReadData(IOCallback & input, ScopeMode ReadFully) { if (Data != NULL) free(Data); if (ReadFully == SCOPE_NO_DATA) { Data = NULL; return GetSize(); } if (!GetSize()) { SetValueIsSet(); Data = NULL; return 0; } Data = (binary *)malloc(GetSize()); if (Data == NULL) throw CRTError(std::string("Error allocating data")); SetValueIsSet(); return input.read(Data, GetSize()); } bool EbmlBinary::operator==(const EbmlBinary & ElementToCompare) const { return ((GetSize() == ElementToCompare.GetSize()) && (GetSize() == 0 || !memcmp(Data, ElementToCompare.Data, GetSize()))); } END_LIBEBML_NAMESPACE <|endoftext|>
<commit_before> #include "density_clustering_opencl.hpp" #include "tools.hpp" #define __CL_ENABLE_EXCEPTIONS #include <utility> #include <CL/cl.hpp> #include <CL/opencl.h> #include <omp.h> #include <iostream> #include <string> #include <fstream> #include <map> #include <tuple> namespace DC_OpenCL { std::tuple<cl::Context, cl::Kernel, cl::CommandQueue> setup_cl(std::string kernel_name, std::string src) { std::vector<cl::Platform> platforms; std::vector<cl::Device> devices; cl::Program program; cl::Context context; cl::CommandQueue q; cl::Kernel kernel; try { // create platform cl::Platform::get(&platforms); platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices); // create context context = cl::Context(devices); // create cmd queue // TODO: if that stuff works, scale to multiple devices q = cl::CommandQueue(context, devices[0]); // setup kernel source cl::Program::Sources source(1, std::make_pair(src.c_str(), src.length() + 1)); // create program program = cl::Program(context, source); program.build(devices); // load kernel kernel = cl::Kernel(program, kernel_name.c_str()); } catch (cl::Error e) { std::cout << e.what() << " : " << e.err() << std::endl; if (e.err() == CL_BUILD_PROGRAM_FAILURE) { cl::STRING_CLASS buildlog; program.getBuildInfo(devices[0], (cl_program_build_info)CL_PROGRAM_BUILD_LOG, &buildlog); std::cerr << buildlog << std::endl; } exit(EXIT_FAILURE); } return std::make_tuple(context, kernel, q); } std::vector<std::size_t> calculate_populations(const float* coords, const std::size_t n_rows, const std::size_t n_cols, const float radius) { ASSUME_ALIGNED(coords); // vector for final results std::vector<std::size_t> pops(n_rows); // kernel calculates population of frame i // by comparing distances to all frames j. // population is stored in integer-array of length n_rows. // every field of the array gets a zero if j is not in // range of i and a one if it is. // to get the total population of i, reduce array with a simple // sum on the host. std::string src = "__kernel void pop_i (__global float* coords,\n" " ulong n_cols,\n" " float rad2,\n" " __global uint* in_range,\n" " ulong i) {\n" " ulong j = get_global_id(0);\n" " float dist = 0.0f;\n" " float d;\n" " ulong k;\n" " for (k=0; k < n_cols; ++k) {\n" " d = coords[i*n_cols+k] - coords[j*n_cols+k];\n" " dist += d*d;\n" " }\n" " in_range[j] = dist < rad2 ? 1 : 0;\n" "}\n" ; try { auto cl_context_kernel_queue = setup_cl("pop_i", src); cl::Context context = std::get<0>(cl_context_kernel_queue); cl::Kernel kernel = std::get<1>(cl_context_kernel_queue); cl::CommandQueue q = std::get<2>(cl_context_kernel_queue); ulong ulong_n_cols = (ulong) n_cols; ulong ulong_n_rows = (ulong) n_rows; // setup buffers on device cl::Buffer d_coords(context, CL_MEM_READ_ONLY, sizeof(float) * ulong_n_rows * ulong_n_cols, NULL, NULL); cl::Buffer d_in_range(context, CL_MEM_WRITE_ONLY, sizeof(uint) * ulong_n_rows, NULL, NULL); // transmit coords to device q.enqueueWriteBuffer(d_coords, CL_TRUE, 0, sizeof(float) * ulong_n_rows * ulong_n_cols, coords, NULL, NULL); q.finish(); // set common arguments float rad2 = radius*radius; kernel.setArg(0, d_coords); kernel.setArg(1, ulong_n_cols); kernel.setArg(2, rad2); kernel.setArg(3, d_in_range); // screen all frames i for (ulong i=0; i < ulong_n_rows; ++i) { kernel.setArg(4, i); // run kernel q.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(ulong_n_rows), cl::NullRange, NULL, NULL); // wait for completion q.finish(); std::vector<uint> buf(ulong_n_rows); q.enqueueReadBuffer(d_in_range, CL_TRUE, 0, sizeof(uint) * ulong_n_rows, buf.data(), NULL, NULL); //TODO: run reduction on device instead of host std::size_t j; std::size_t pop_i = 0; #pragma omp parallel for default(none) \ private(j) \ firstprivate(n_rows) \ shared(pops,buf) \ reduction(+:pop_i) for (j=0; j < n_rows; ++j) { pop_i += buf[j]; } pops[i] = pop_i; } } catch (cl::Error e) { std::cout << e.what() << " : " << e.err() << std::endl; exit(EXIT_FAILURE); } return pops; } } // end namespace DC_OpenCL <commit_msg>refactoring OpenCL code (unfinished)<commit_after> #include "density_clustering_opencl.hpp" #include "tools.hpp" #define __CL_ENABLE_EXCEPTIONS #include <utility> #include <CL/cl.hpp> #include <CL/opencl.h> #include <omp.h> #include <iostream> #include <string> #include <fstream> #include <map> #include <tuple> namespace DC_OpenCL { namespace { std::map<std::string, cl::Kernel> kernels; // device buffer for coordinates cl::Buffer d_coords; std::vector<cl::Platform> platforms; cl::Context context; std::vector<cl::Device> devices; std::vector<cl::CommandQueue> queues; void setup_context() { try { // create platform cl::Platform::get(&platforms); platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices); // create context context = cl::Context(devices); // create cmd queue // TODO: if that stuff works, scale to multiple devices qs.push_back(cl::CommandQueue(context, devices[0])); catch (cl::Error e) { std::cerr << "error during OpenCL setup" << std::endl; std::cerr << e.what() << " : " << e.err() << std::endl; exit(EXIT_FAILURE); } } void upload_coords(const float* coords, const std::size_t n_rows, const std::size_t n_cols) { // setup buffers on device cl::Buffer d_coords(context, CL_MEM_READ_ONLY, sizeof(float) * n_rows * n_cols, NULL, NULL); // transmit coords to device q.enqueueWriteBuffer(d_coords, CL_TRUE, 0, sizeof(float) * n_rows * n_cols, coords, NULL, NULL); q.finish(); } void build_kernel(std::string name, std::string src) { cl::Program program; try { // setup kernel source cl::Program::Sources source(1, std::make_pair(src.c_str(), src.length() + 1)); // create program program = cl::Program(context, source); program.build(devices); // load kernel kernel[name] = cl::Kernel(program, name.c_str()); } catch (cl::Error e) { std::cout << e.what() << " : " << e.err() << std::endl; if (e.err() == CL_BUILD_PROGRAM_FAILURE) { cl::STRING_CLASS buildlog; program.getBuildInfo(devices[0], (cl_program_build_info)CL_PROGRAM_BUILD_LOG, &buildlog); std::cerr << buildlog << std::endl; } exit(EXIT_FAILURE); } } void setup_kernels() { std::string src; //// pop_i // // kernel calculates population of frame i // by comparing distances to all frames j. // population is stored in integer-array of length n_rows. // every field of the array gets a zero if j is not in // range of i and a one if it is. src = "__kernel void pop_i (__global float* coords,\n" " ulong n_cols,\n" " float rad2,\n" " __global uint* in_range,\n" " ulong i) {\n" " ulong j = get_global_id(0);\n" " float dist = 0.0f;\n" " float d;\n" " ulong k;\n" " for (k=0; k < n_cols; ++k) {\n" " d = coords[i*n_cols+k] - coords[j*n_cols+k];\n" " dist += d*d;\n" " }\n" " in_range[j] = dist < rad2 ? 1 : 0;\n" "}\n" ; build_kernel("pop_i", src); //// sum_uints (single task kernel) // // kernel calculates total sum of unsigned integer array. src = "__kernel void sum_uints (__global uint* uints,\n" " ulong n_rows,\n" " __global ulong* result) {\n" " ulong r=0;\n" " for(ulong i=0; i < n_rows; ++i) {\n" " r += uints[i]\n" " }\n" " *result = r;\n" "}\n" build_kernel("sum_uints", src); } } // end local namespace void setup(const float* coords, const std::size_t n_rows, const std::size_t n_cols) { } std::vector<std::size_t> calculate_populations(const float radius) { // vector for final results std::vector<std::size_t> pops(n_rows); try { ulong ulong_n_cols = (ulong) n_cols; ulong ulong_n_rows = (ulong) n_rows; cl::Buffer d_in_range(context, CL_MEM_WRITE_ONLY, sizeof(uint) * ulong_n_rows, NULL, NULL); // set common arguments float rad2 = radius*radius; kernel.setArg(0, d_coords); kernel.setArg(1, ulong_n_cols); kernel.setArg(2, rad2); kernel.setArg(3, d_in_range); // screen all frames i for (ulong i=0; i < ulong_n_rows; ++i) { kernel.setArg(4, i); // run kernel q.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(ulong_n_rows), cl::NullRange, NULL, NULL); // wait for completion q.finish(); std::vector<uint> buf(ulong_n_rows); q.enqueueReadBuffer(d_in_range, CL_TRUE, 0, sizeof(uint) * ulong_n_rows, buf.data(), NULL, NULL); //TODO: run reduction on device instead of host std::size_t j; std::size_t pop_i = 0; #pragma omp parallel for default(none) \ private(j) \ firstprivate(n_rows) \ shared(pops,buf) \ reduction(+:pop_i) for (j=0; j < n_rows; ++j) { pop_i += buf[j]; } pops[i] = pop_i; } } catch (cl::Error e) { std::cout << e.what() << " : " << e.err() << std::endl; exit(EXIT_FAILURE); } return pops; } } // end namespace DC_OpenCL <|endoftext|>
<commit_before>#include "ofApp.h" // Configuration int imgcount = 326; bool usePort = false; bool fullscreen = false; int maxDistance = 1000; int sleepMillis = 100; // Serial port, for reading distance from ultrasonic sensor. // Optional. ofSerial serialPort; // Images that make up the animation sequence std::map<int, ofImage> images; // App state, you should not touch these; int currentDistance = 0; long previousMillis = 0; int frame = 0; float period = 1; float distanceOfFrame = maxDistance / imgcount; int loadTime = -1; int destinationFrame = frame; // HUD ofTrueTypeFont f; //-------------------------------------------------------------- void ofApp::setup(){ //Set screen frame rate ofSetFrameRate( 60 ); ofSetFullscreen(fullscreen); ofSetDataPathRoot("../Resources/data/"); // FIXME: draws all shapes with smooth edges. if (usePort) { // FIXME: serialPort = new Serial(this, "/dev/tty.usbmodem1411", 9600); // FIXME: serialPort.bufferUntil('\n'); // Trigger a SerialEvent on new line } if (!usePort) { currentDistance = maxDistance; // fake initial distance for simulation } assert(f.loadFont("verdana.ttf", 16, true, true)); f.setLineHeight(18.0f); f.setLetterSpacing(1.037); } //-------------------------------------------------------------- void ofApp::update(){ currentDistance = ofClamp(currentDistance, 0, maxDistance); calculateFrame(); } ofImage *ofApp::getImage(const int i) { if (images.end() == images.find(i)) { ofImage img; assert(img.loadImage(ofToString(i) + ".jpg")); images[i] = img; } return &images[i]; } // Frame for current distance // Note that this is not the actual frame that will be animated. // Instead will start to animate towards this frame. int ofApp::frameForDistance() const { int result = imgcount - int(currentDistance / distanceOfFrame); if (result < 0) { result = 0; } if (result >= imgcount - 1) { result = imgcount - 1; } return result; } void ofApp::calculateFrame() { long now = ofGetElapsedTimef(); long timePassed = now - previousMillis; destinationFrame = frameForDistance(); if (timePassed > sleepMillis) { // move towards destination if (destinationFrame > frame) { frame = frame + 1; } else if (destinationFrame > frame) { frame = frame + 1; } else { // User is not moving, attempt some random stuff int r = int(ofRandom(4)); if (r == 0) { r = int(ofRandom(3)); if (0 == r) { frame = frame + 1; } else { frame = frame - 1; } } } previousMillis = now; } if (frame < 0) { frame = 0; } else if (frame >= imgcount) { frame = imgcount - 1; } } //-------------------------------------------------------------- void ofApp::draw(){ // Update HUD f.drawString("distance=" + ofToString(currentDistance), 10, 40); f.drawString("max=" + ofToString(maxDistance), 210, 40); f.drawString("framelen=" + ofToString(distanceOfFrame), 410, 40); f.drawString("frame=" + ofToString(frame) + "/" + ofToString(imgcount), 610, 40); f.drawString("destination=" + ofToString(destinationFrame), 810, 40); // Draw the current animation frame ofImage *img = getImage(frame); assert(img); img->draw( 0, 60, ofGetWidth(), ofGetHeight() - 60 ); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>fix timing<commit_after>#include "ofApp.h" // Configuration int imgcount = 326; bool usePort = false; bool fullscreen = false; int maxDistance = 1000; int sleepMillis = 100; // Serial port, for reading distance from ultrasonic sensor. // Optional. ofSerial serialPort; // Images that make up the animation sequence std::map<int, ofImage> images; // App state, you should not touch these; int currentDistance = 0; long previousMillis = 0; int frame = 0; float period = 1; float distanceOfFrame = maxDistance / imgcount; int loadTime = -1; int destinationFrame = frame; // HUD ofTrueTypeFont f; //-------------------------------------------------------------- void ofApp::setup(){ //Set screen frame rate ofSetFrameRate( 60 ); ofSetFullscreen(fullscreen); ofSetDataPathRoot("../Resources/data/"); // FIXME: draws all shapes with smooth edges. if (usePort) { // FIXME: serialPort = new Serial(this, "/dev/tty.usbmodem1411", 9600); // FIXME: serialPort.bufferUntil('\n'); // Trigger a SerialEvent on new line } if (!usePort) { currentDistance = maxDistance; // fake initial distance for simulation } assert(f.loadFont("verdana.ttf", 16, true, true)); f.setLineHeight(18.0f); f.setLetterSpacing(1.037); } //-------------------------------------------------------------- void ofApp::update(){ currentDistance = ofClamp(currentDistance, 0, maxDistance); calculateFrame(); } ofImage *ofApp::getImage(const int i) { if (images.end() == images.find(i)) { ofImage img; assert(img.loadImage(ofToString(i) + ".jpg")); images[i] = img; } return &images[i]; } // Frame for current distance // Note that this is not the actual frame that will be animated. // Instead will start to animate towards this frame. int ofApp::frameForDistance() const { int result = imgcount - int(currentDistance / distanceOfFrame); if (result < 0) { result = 0; } if (result >= imgcount - 1) { result = imgcount - 1; } return result; } void ofApp::calculateFrame() { long now = ofGetElapsedTimeMillis(); long timePassed = now - previousMillis; destinationFrame = frameForDistance(); if (timePassed > sleepMillis) { // move towards destination if (destinationFrame > frame) { frame = frame + 1; } else if (destinationFrame > frame) { frame = frame + 1; } else { // User is not moving, attempt some random stuff int r = int(ofRandom(4)); if (r == 0) { r = int(ofRandom(3)); if (0 == r) { frame = frame + 1; } else { frame = frame - 1; } } } previousMillis = now; } if (frame < 0) { frame = 0; } else if (frame >= imgcount) { frame = imgcount - 1; } } //-------------------------------------------------------------- void ofApp::draw(){ // Update HUD f.drawString("distance=" + ofToString(currentDistance), 10, 40); f.drawString("max=" + ofToString(maxDistance), 210, 40); f.drawString("framelen=" + ofToString(distanceOfFrame), 410, 40); f.drawString("frame=" + ofToString(frame) + "/" + ofToString(imgcount), 610, 40); f.drawString("destination=" + ofToString(destinationFrame), 810, 40); // Draw the current animation frame ofImage *img = getImage(frame); assert(img); img->draw( 0, 60, ofGetWidth(), ofGetHeight() - 60 ); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>/** * @file device_properties.hxx * @author Muhammad Osama (mosama@ucdavis.edu) * @brief * @version 0.1 * @date 2020-10-05 * * @copyright Copyright (c) 2020 * */ #pragma once #include <iostream> #include <gunrock/cuda/device.hxx> #include <gunrock/error.hxx> namespace gunrock { namespace cuda { typedef cudaDeviceProp device_properties_t; typedef struct { unsigned major; unsigned minor; constexpr unsigned as_combined_number() const { return major * 10 + minor; } constexpr bool operator==(int i) { return (int)as_combined_number() == i; } constexpr bool operator!=(int i) { return (int)as_combined_number() != i; } constexpr bool operator>(int i) { return (int)as_combined_number() > i; } constexpr bool operator<(int i) { return (int)as_combined_number() < i; } constexpr bool operator>=(int i) { return (int)as_combined_number() >= i; } constexpr bool operator<=(int i) { return (int)as_combined_number() <= i; } } compute_capability_t; /** * @brief Make compute capability from major and minor versions. * @param major Compute capability major version * @param minor Compute capability minor version * \return compute_capability_t */ constexpr compute_capability_t make_compute_capability(unsigned major, unsigned minor) { return compute_capability_t{major, minor}; } /** * @brief Make compute capability from combined major and minor version. * @param combined Combined major and minor value, e.g. 86 for 8.6 * \return compute_capability_t */ constexpr compute_capability_t make_compute_capability(unsigned combined) { return compute_capability_t{combined / 10, combined % 10}; } /** * @brief Get compute capability from SM_TARGET macro. * \return compute_capabilty_t */ constexpr compute_capability_t get_compute_capability() { return make_compute_capability(SM_TARGET); } /** * @namespace properties * C++ based CUDA device properties. */ namespace properties { /** * @brief Enums for units used by device property values. */ enum : size_t { KiB = 1024, K = 1024 }; /** * @brief Architecture name based on compute capability. * https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capability * @param capability Compute capability from which to get the result * \return const char* architecture name or nullptr if capability is invalid */ inline constexpr const char* arch_name(compute_capability_t capability) { return (capability.major == 8) ? "Ampere" : (capability.major == 7 && capability.minor == 5) ? "Turing" : (capability.major == 7) ? "Volta" : (capability.major == 6) ? "Pascal" : (capability.major == 5) ? "Maxwell" : (capability.major == 3) ? "Kepler" : nullptr ; } // Device properties retrieved from: // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications /** * @brief Maximum number of threads per block. * \return unsigned */ inline constexpr unsigned cta_max_threads() { return 1 << 10; // 1024 threads per CTA } /** * @brief Warp size (has always been 32, but is subject to change). * \return unsigned */ inline constexpr unsigned warp_max_threads() { return 1 << 5; } /** * @brief Maximum number of resident blocks per SM. * @param capability Compute capability from which to get the result * \return unsigned */ inline constexpr unsigned sm_max_ctas(compute_capability_t capability) { return (capability >= 86) ? 16 : // SM86+ (capability >= 80) ? 32 : // SM80 (capability >= 75) ? 16 : // SM75 (capability >= 50) ? 32 : // SM50-SM72 16 ; // SM30-SM37 } /** * @brief Maximum number of resident threads per SM. * @param capability Compute capability from which to get the result * \return unsigned */ inline constexpr unsigned sm_max_threads(compute_capability_t capability) { return (capability >= 86) ? 1536 : // SM86+ (capability >= 80) ? 2048 : // SM80 (capability >= 75) ? 1024 : // SM75 2048 ; // SM30-SM72 } /** * @brief Number of 32-bit registers per SM. * @param capability Compute capability from which to get the result * \return unsigned */ inline constexpr unsigned sm_registers(compute_capability_t capability) { return (capability >= 50) ? 64 * K : // SM50+ (capability >= 37) ? 128 * K : // SM37 64 * K ; // SM30-SM35 } /** * @brief Maximum amount of shared memory per SM. * @tparam sm3XCacheConfig cudaFuncCache enum representing the shared data * cache configuration used when called on compute * capability 3.x * @param capability Compute capability from which to get the result * \return unsigned * @todo Test if this function can be resolved at compile time */ template<enum cudaFuncCache sm3XCacheConfig = cudaFuncCachePreferNone> inline constexpr unsigned sm_max_shared_memory_bytes( compute_capability_t capability ) { unsigned sm3XConfiguredSmem = (sm3XCacheConfig == cudaFuncCachePreferNone) ? 48 * KiB : (sm3XCacheConfig == cudaFuncCachePreferShared) ? 48 * KiB : (sm3XCacheConfig == cudaFuncCachePreferL1) ? 16 * KiB : (sm3XCacheConfig == cudaFuncCachePreferEqual) ? 32 * KiB : 48 * KiB ; return (capability >= 86) ? 100 * KiB : // SM86+ (capability >= 80) ? 164 * KiB : // SM80 (capability >= 75) ? 64 * KiB : // SM75 (capability >= 70) ? 96 * KiB : // SM70-SM72 (capability >= 62) ? 64 * KiB : // SM62 (capability >= 61) ? 96 * KiB : // SM61 (capability >= 53) ? 64 * KiB : // SM53 (capability >= 52) ? 96 * KiB : // SM52 (capability >= 50) ? 64 * KiB : // SM50 (capability >= 37) ? 64 * KiB + sm3XConfiguredSmem : // SM37 sm3XConfiguredSmem ; // SM30-SM35 } /** * @brief Number of shared memory banks. * \return unsigned */ inline constexpr unsigned shared_memory_banks() { return 1 << 5; // 32 memory banks per SM } /** * @brief Stride length (number of bytes per word) of shared memory in bytes. * @tparam sm3XSmemConfig cudaSharedMemConfig enum representing the shared * memory bank size (stride) used when called on compute * capability 3.x * \return unsigned */ template<enum cudaSharedMemConfig sm3XSmemConfig = cudaSharedMemBankSizeDefault> inline constexpr unsigned shared_memory_bank_stride() { // The default config on 3.x is the same constant value for later archs // Only let 3.x be configurable if stride later becomes dependent on arch return (sm3XSmemConfig == cudaSharedMemBankSizeDefault) ? 1 << 2 : (sm3XSmemConfig == cudaSharedMemBankSizeFourByte) ? 1 << 2 : (sm3XSmemConfig == cudaSharedMemBankSizeEightByte) ? 1 << 3 : 1 << 2 ; } void print(device_properties_t& prop) { device_id_t ordinal; cudaGetDevice(&ordinal); size_t freeMem, totalMem; error::error_t status = cudaMemGetInfo(&freeMem, &totalMem); error::throw_if_exception(status); double memBandwidth = (prop.memoryClockRate * 1000.0) * (prop.memoryBusWidth / 8 * 2) / 1.0e9; std::cout << prop.name << " : " << prop.clockRate / 1000.0 << " Mhz " << "(Ordinal " << ordinal << ")" << std::endl; std::cout << "FreeMem: " << (int)(freeMem / (1 << 20)) << " MB " << "TotalMem: " << (int)(totalMem / (1 << 20)) << " MB " << ((int)8 * sizeof(int*)) << "-bit pointers." << std::endl; std::cout << prop.multiProcessorCount << " SMs enabled, Compute Capability sm_" << prop.major << prop.minor << std::endl; std::cout << "Mem Clock: " << prop.memoryClockRate / 1000.0 << " Mhz x " << prop.memoryBusWidth << " bits (" << memBandwidth << " GB/s)" << std::endl; std::cout << "ECC " << (prop.ECCEnabled ? "Enabled" : "Disabled") << std::endl; } } // namespace properties } // namespace cuda } // namespace gunrock <commit_msg>Rename function<commit_after>/** * @file device_properties.hxx * @author Muhammad Osama (mosama@ucdavis.edu) * @brief * @version 0.1 * @date 2020-10-05 * * @copyright Copyright (c) 2020 * */ #pragma once #include <iostream> #include <gunrock/cuda/device.hxx> #include <gunrock/error.hxx> namespace gunrock { namespace cuda { typedef cudaDeviceProp device_properties_t; typedef struct { unsigned major; unsigned minor; constexpr unsigned as_combined_number() const { return major * 10 + minor; } constexpr bool operator==(int i) { return (int)as_combined_number() == i; } constexpr bool operator!=(int i) { return (int)as_combined_number() != i; } constexpr bool operator>(int i) { return (int)as_combined_number() > i; } constexpr bool operator<(int i) { return (int)as_combined_number() < i; } constexpr bool operator>=(int i) { return (int)as_combined_number() >= i; } constexpr bool operator<=(int i) { return (int)as_combined_number() <= i; } } compute_capability_t; /** * @brief Make compute capability from major and minor versions. * @param major Compute capability major version * @param minor Compute capability minor version * \return compute_capability_t */ constexpr compute_capability_t make_compute_capability(unsigned major, unsigned minor) { return compute_capability_t{major, minor}; } /** * @brief Make compute capability from combined major and minor version. * @param combined Combined major and minor value, e.g. 86 for 8.6 * \return compute_capability_t */ constexpr compute_capability_t make_compute_capability(unsigned combined) { return compute_capability_t{combined / 10, combined % 10}; } /** * @brief Fetch compute capability from SM_TARGET macro. * \return compute_capabilty_t */ constexpr compute_capability_t fetch_compute_capability() { return make_compute_capability(SM_TARGET); } /** * @namespace properties * C++ based CUDA device properties. */ namespace properties { /** * @brief Enums for units used by device property values. */ enum : size_t { KiB = 1024, K = 1024 }; /** * @brief Architecture name based on compute capability. * https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capability * @param capability Compute capability from which to get the result * \return const char* architecture name or nullptr if capability is invalid */ inline constexpr const char* arch_name(compute_capability_t capability) { return (capability.major == 8) ? "Ampere" : (capability.major == 7 && capability.minor == 5) ? "Turing" : (capability.major == 7) ? "Volta" : (capability.major == 6) ? "Pascal" : (capability.major == 5) ? "Maxwell" : (capability.major == 3) ? "Kepler" : nullptr ; } // Device properties retrieved from: // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications /** * @brief Maximum number of threads per block. * \return unsigned */ inline constexpr unsigned cta_max_threads() { return 1 << 10; // 1024 threads per CTA } /** * @brief Warp size (has always been 32, but is subject to change). * \return unsigned */ inline constexpr unsigned warp_max_threads() { return 1 << 5; } /** * @brief Maximum number of resident blocks per SM. * @param capability Compute capability from which to get the result * \return unsigned */ inline constexpr unsigned sm_max_ctas(compute_capability_t capability) { return (capability >= 86) ? 16 : // SM86+ (capability >= 80) ? 32 : // SM80 (capability >= 75) ? 16 : // SM75 (capability >= 50) ? 32 : // SM50-SM72 16 ; // SM30-SM37 } /** * @brief Maximum number of resident threads per SM. * @param capability Compute capability from which to get the result * \return unsigned */ inline constexpr unsigned sm_max_threads(compute_capability_t capability) { return (capability >= 86) ? 1536 : // SM86+ (capability >= 80) ? 2048 : // SM80 (capability >= 75) ? 1024 : // SM75 2048 ; // SM30-SM72 } /** * @brief Number of 32-bit registers per SM. * @param capability Compute capability from which to get the result * \return unsigned */ inline constexpr unsigned sm_registers(compute_capability_t capability) { return (capability >= 50) ? 64 * K : // SM50+ (capability >= 37) ? 128 * K : // SM37 64 * K ; // SM30-SM35 } /** * @brief Maximum amount of shared memory per SM. * @tparam sm3XCacheConfig cudaFuncCache enum representing the shared data * cache configuration used when called on compute * capability 3.x * @param capability Compute capability from which to get the result * \return unsigned * @todo Test if this function can be resolved at compile time */ template<enum cudaFuncCache sm3XCacheConfig = cudaFuncCachePreferNone> inline constexpr unsigned sm_max_shared_memory_bytes( compute_capability_t capability ) { unsigned sm3XConfiguredSmem = (sm3XCacheConfig == cudaFuncCachePreferNone) ? 48 * KiB : (sm3XCacheConfig == cudaFuncCachePreferShared) ? 48 * KiB : (sm3XCacheConfig == cudaFuncCachePreferL1) ? 16 * KiB : (sm3XCacheConfig == cudaFuncCachePreferEqual) ? 32 * KiB : 48 * KiB ; return (capability >= 86) ? 100 * KiB : // SM86+ (capability >= 80) ? 164 * KiB : // SM80 (capability >= 75) ? 64 * KiB : // SM75 (capability >= 70) ? 96 * KiB : // SM70-SM72 (capability >= 62) ? 64 * KiB : // SM62 (capability >= 61) ? 96 * KiB : // SM61 (capability >= 53) ? 64 * KiB : // SM53 (capability >= 52) ? 96 * KiB : // SM52 (capability >= 50) ? 64 * KiB : // SM50 (capability >= 37) ? 64 * KiB + sm3XConfiguredSmem : // SM37 sm3XConfiguredSmem ; // SM30-SM35 } /** * @brief Number of shared memory banks. * \return unsigned */ inline constexpr unsigned shared_memory_banks() { return 1 << 5; // 32 memory banks per SM } /** * @brief Stride length (number of bytes per word) of shared memory in bytes. * @tparam sm3XSmemConfig cudaSharedMemConfig enum representing the shared * memory bank size (stride) used when called on compute * capability 3.x * \return unsigned */ template<enum cudaSharedMemConfig sm3XSmemConfig = cudaSharedMemBankSizeDefault> inline constexpr unsigned shared_memory_bank_stride() { // The default config on 3.x is the same constant value for later archs // Only let 3.x be configurable if stride later becomes dependent on arch return (sm3XSmemConfig == cudaSharedMemBankSizeDefault) ? 1 << 2 : (sm3XSmemConfig == cudaSharedMemBankSizeFourByte) ? 1 << 2 : (sm3XSmemConfig == cudaSharedMemBankSizeEightByte) ? 1 << 3 : 1 << 2 ; } void print(device_properties_t& prop) { device_id_t ordinal; cudaGetDevice(&ordinal); size_t freeMem, totalMem; error::error_t status = cudaMemGetInfo(&freeMem, &totalMem); error::throw_if_exception(status); double memBandwidth = (prop.memoryClockRate * 1000.0) * (prop.memoryBusWidth / 8 * 2) / 1.0e9; std::cout << prop.name << " : " << prop.clockRate / 1000.0 << " Mhz " << "(Ordinal " << ordinal << ")" << std::endl; std::cout << "FreeMem: " << (int)(freeMem / (1 << 20)) << " MB " << "TotalMem: " << (int)(totalMem / (1 << 20)) << " MB " << ((int)8 * sizeof(int*)) << "-bit pointers." << std::endl; std::cout << prop.multiProcessorCount << " SMs enabled, Compute Capability sm_" << prop.major << prop.minor << std::endl; std::cout << "Mem Clock: " << prop.memoryClockRate / 1000.0 << " Mhz x " << prop.memoryBusWidth << " bits (" << memBandwidth << " GB/s)" << std::endl; std::cout << "ECC " << (prop.ECCEnabled ? "Enabled" : "Disabled") << std::endl; } } // namespace properties } // namespace cuda } // namespace gunrock <|endoftext|>
<commit_before>// FbTime.cc for FbTk - Fluxbox Toolkit // Copyright (c) 2012 Mathias Gumz (akira at fluxbox dot org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "FbTime.hh" #include <cstdlib> #include <sys/time.h> #ifdef HAVE_CLOCK_GETTIME // linux|*bsd|solaris #include <time.h> namespace { uint64_t _mono() { uint64_t t = 0L; timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { t = (ts.tv_sec * FbTk::FbTime::IN_SECONDS) + (ts.tv_nsec / 1000L); } return t; } } #endif // HAVE_CLOCK_GETTIME #ifdef HAVE_MACH_ABSOLUTE_TIME // macosx // http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x // https://github.com/ThomasHabets/monotonic_clock/blob/master/src/monotonic_mach.c // http://shiftedbits.org/2008/10/01/mach_absolute_time-on-the-iphone/ #include <mach/mach_time.h> namespace { uint64_t _mono() { // mach_absolute_time() * info.numer / info.denom yields // nanoseconds. static double micro_scale = 0.001; // 1000ms == 1ns static bool initial = true; if (initial) { initial = false; mach_timebase_info_data_t info; if (mach_timebase_info(&info) == 0) { micro_scale *= static_cast<double>(info.numer) / static_cast<double>(info.denom); } } return static_cast<uint64_t>(mach_absolute_time() * micro_scale); } } #endif // HAVE_MACH_ABSOLUTE_TIME uint64_t FbTk::FbTime::mono() { return ::_mono(); } uint64_t FbTk::FbTime::system() { static timeval v; gettimeofday(&v, NULL); return (v.tv_sec * FbTk::FbTime::IN_SECONDS) + v.tv_usec; } <commit_msg>FbTk::FbTime::mono() yields microseconds since fluxbox started<commit_after>// FbTime.cc for FbTk - Fluxbox Toolkit // Copyright (c) 2012 Mathias Gumz (akira at fluxbox dot org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "FbTime.hh" #include <cstdlib> #include <sys/time.h> #ifdef HAVE_CLOCK_GETTIME // linux|*bsd|solaris #include <time.h> namespace { uint64_t _mono() { uint64_t t = 0L; timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { t = (ts.tv_sec * FbTk::FbTime::IN_SECONDS) + (ts.tv_nsec / 1000L); } return t; } } #endif // HAVE_CLOCK_GETTIME #ifdef HAVE_MACH_ABSOLUTE_TIME // macosx // http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x // https://github.com/ThomasHabets/monotonic_clock/blob/master/src/monotonic_mach.c // http://shiftedbits.org/2008/10/01/mach_absolute_time-on-the-iphone/ #include <mach/mach_time.h> namespace { uint64_t _mono() { // mach_absolute_time() * info.numer / info.denom yields // nanoseconds. static double micro_scale = 0.001; // 1000ms == 1ns static bool initial = true; if (initial) { initial = false; mach_timebase_info_data_t info; if (mach_timebase_info(&info) == 0) { micro_scale *= static_cast<double>(info.numer) / static_cast<double>(info.denom); } } return static_cast<uint64_t>(mach_absolute_time() * micro_scale); } } #endif // HAVE_MACH_ABSOLUTE_TIME static uint64_t start = ::_mono(); uint64_t FbTk::FbTime::mono() { return ::_mono() - start; } uint64_t FbTk::FbTime::system() { static timeval v; gettimeofday(&v, NULL); return (v.tv_sec * FbTk::FbTime::IN_SECONDS) + v.tv_usec; } <|endoftext|>
<commit_before>#include "Filesystem.h" #include <fstream> #include <utility> namespace tigl { auto readFile(const boost::filesystem::path& filename) -> std::string { std::ifstream existingFile(filename.string()); if (!existingFile) return{}; // read file to string existingFile.seekg(0, std::ifstream::end); const auto length = existingFile.tellg(); existingFile.seekg(0, std::ifstream::beg); std::string content; content.reserve(length); content.assign(std::istreambuf_iterator<char>{existingFile}, std::istreambuf_iterator<char>{}); return content; } File::File(boost::filesystem::path filename) : m_stream(new std::ostringstream), m_filename(std::move(filename)) {} auto File::stream() -> std::ostream& { return *m_stream; } void Filesystem::flushToDisk() { for (auto& file : m_files) { const auto& newContent = file.m_stream->str(); // check if a file already exists if (boost::filesystem::exists(file.m_filename)) { // read existing file to string and compare const auto& content = readFile(file.m_filename); // if existing file has same content, skip overwriting it if (content == newContent) { skipped++; continue; } overwritten++; } else newlywritten++; // write new content to file std::ofstream f(file.m_filename.string()); f.exceptions(std::ios::failbit | std::ios::badbit); f.write(newContent.c_str(), newContent.size()); f.close(); } } auto Filesystem::newFile(boost::filesystem::path filename) -> File& { m_files.emplace_back(std::move(filename)); return m_files.back(); } void Filesystem::removeIfExists(const boost::filesystem::path& path) { if (boost::filesystem::exists(path)) { boost::filesystem::remove(path); deleted++; } } void Filesystem::mergeFilesInto(boost::filesystem::path filename) { std::ostringstream oss; for (auto& file : m_files) { auto str = file.m_stream->str(); oss.write(str.c_str(), str.size()); } *newFile(std::move(filename)).m_stream = std::move(oss); } } <commit_msg>fixed build gcc build issues<commit_after>#include "Filesystem.h" #include <fstream> #include <utility> namespace tigl { auto readFile(const boost::filesystem::path& filename) -> std::string { std::ifstream existingFile(filename.string()); if (!existingFile) return{}; // read file to string existingFile.seekg(0, std::ifstream::end); const auto length = existingFile.tellg(); existingFile.seekg(0, std::ifstream::beg); std::string content; content.reserve(length); content.assign(std::istreambuf_iterator<char>{existingFile}, std::istreambuf_iterator<char>{}); return content; } File::File(boost::filesystem::path filename) : m_stream(new std::ostringstream), m_filename(std::move(filename)) {} auto File::stream() -> std::ostream& { return *m_stream; } void Filesystem::flushToDisk() { for (auto& file : m_files) { const auto& newContent = file.m_stream->str(); // check if a file already exists if (boost::filesystem::exists(file.m_filename)) { // read existing file to string and compare const auto& content = readFile(file.m_filename); // if existing file has same content, skip overwriting it if (content == newContent) { skipped++; continue; } overwritten++; } else newlywritten++; // write new content to file std::ofstream f(file.m_filename.string()); f.exceptions(std::ios::failbit | std::ios::badbit); f.write(newContent.c_str(), newContent.size()); f.close(); } } auto Filesystem::newFile(boost::filesystem::path filename) -> File& { m_files.emplace_back(std::move(filename)); return m_files.back(); } void Filesystem::removeIfExists(const boost::filesystem::path& path) { if (boost::filesystem::exists(path)) { boost::filesystem::remove(path); deleted++; } } void Filesystem::mergeFilesInto(boost::filesystem::path filename) { auto& f = newFile(std::move(filename)); for (auto& file : m_files) { auto str = file.m_stream->str(); f.m_stream->write(str.c_str(), str.size()); } } } <|endoftext|>
<commit_before>/** * This file implements a command line utility to interact * with the d2 library. */ #include <d2/analysis.hpp> #include <d2/event_repository.hpp> #include <d2/graph_construction.hpp> #include <boost/assert.hpp> #include <boost/assign.hpp> #include <boost/foreach.hpp> #include <boost/function.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/properties.hpp> #include <boost/optional.hpp> #include <boost/phoenix.hpp> #include <boost/program_options.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <cstddef> #include <cstdlib> #include <fstream> #include <iostream> #include <map> #include <string> #include <utility> #include <vector> static std::string const VERSION = "0.1a"; namespace po = boost::program_options; namespace phx = boost::phoenix; using phx::arg_names::_1; namespace { // Dot rendering template <typename LockGraph> class LockGraphWriter { typedef typename boost::graph_traits<LockGraph>::edge_descriptor EdgeDescriptor; typedef typename boost::graph_traits<LockGraph>::vertex_descriptor VertexDescriptor; LockGraph const& graph_; // Silence MSVC warning C4512: assignment operator could not be generated LockGraphWriter& operator=(LockGraphWriter const&) /*= delete*/; public: explicit LockGraphWriter(LockGraph const& lg) : graph_(lg) { } template <typename Ostream> void operator()(Ostream& os, EdgeDescriptor edge) const { os << "[label=\"" << "from " << graph_[edge].l1_info.call_stack[0].function << " to " << graph_[edge].l2_info.call_stack[0].function << "\"]"; } template <typename Ostream> void operator()(Ostream&, VertexDescriptor) const { } }; template <typename LockGraph> LockGraphWriter<LockGraph> render_dot(LockGraph const& lg) { return LockGraphWriter<LockGraph>(lg); } // Statistic gathering template <typename LockGraph, typename SegmentationGraph> struct Statistics { Statistics(LockGraph const& lg, SegmentationGraph const&) : number_of_lock_graph_vertices(num_vertices(lg)), number_of_lock_graph_edges(num_edges(lg)) { } std::size_t number_of_lock_graph_vertices; std::size_t number_of_lock_graph_edges; boost::optional<std::size_t> number_of_distinct_cycles; template <typename Ostream> friend Ostream& operator<<(Ostream& os, Statistics const& self) { os << "number of vertices in the lock graph: " << self.number_of_lock_graph_vertices << '\n' << "number of edges in the lock graph: " << self.number_of_lock_graph_edges << '\n' << "number of distinct cycles in the lock graph: "; if (self.number_of_distinct_cycles) os << *self.number_of_distinct_cycles; else os << "not computed"; return os; } }; template <typename Stats> class StatisticGatherer { Stats& stats_; // Silence MSVC warning C4512: assignment operator could not be generated StatisticGatherer& operator=(StatisticGatherer const&) /*= delete*/; public: explicit StatisticGatherer(Stats& stats) : stats_(stats) { BOOST_ASSERT_MSG(!stats_.number_of_distinct_cycles, "gathering statistics on a statistic object that was already filled"); stats_.number_of_distinct_cycles = 0; } template <typename EdgePath, typename LockGraph> void operator()(EdgePath const&, LockGraph const&) const { ++*stats_.number_of_distinct_cycles; } }; template <typename Stats> StatisticGatherer<Stats> gather_stats(Stats& stats) { return StatisticGatherer<Stats>(stats); } // Deadlock analysis template <typename Ostream> class CyclePrinter { Ostream& os_; // Silence MSVC warning C4512: assignment operator could not be generated CyclePrinter& operator=(CyclePrinter const&) /*= delete*/; void format_call_stack(d2::detail::LockDebugInfo const& info, std::string const& indent = "") const { BOOST_FOREACH(d2::detail::StackFrame const& frame, info.call_stack) { os_ << indent << frame.ip << " " << frame.function << " in " << frame.module << '\n'; } } public: explicit CyclePrinter(Ostream& os) : os_(os) { } template <typename EdgePath, typename LockGraph> void operator()(EdgePath const& cycle, LockGraph const& graph) const { typedef typename boost::graph_traits<LockGraph>::edge_descriptor LockGraphEdgeDescriptor; typedef typename boost::edge_property_type<LockGraph>::type LockGraphEdge; os_ << "----------------------------------------------------"; BOOST_FOREACH(LockGraphEdgeDescriptor const& edge_desc, cycle) { LockGraphEdge const& edge = graph[edge_desc]; d2::SyncObject const& l1 = graph[source(edge_desc, graph)]; d2::SyncObject const& l2 = graph[target(edge_desc, graph)]; os_ << '\n'; os_ << "Thread " << edge.t << " acquired lock " << l2 << " in\n"; format_call_stack(edge.l2_info, " "); os_ << "while holding lock " << l1 << " taken in\n"; format_call_stack(edge.l1_info, " "); } os_ << "----------------------------------------------------\n\n"; } }; template <typename Ostream> CyclePrinter<Ostream> print_cycle(Ostream& os) { return CyclePrinter<Ostream>(os); } } // end anonymous namespace int main(int argc, char const* argv[]) { // Parse command line options. po::options_description global("Global options"); global.add_options() ( "help,h", "produce help message and exit" )( "version,v", "print version and exit" )( "output-file,o", po::value<std::string>(), "file to write the output to" )( "analyze", "perform the analysis for deadlocks" )( "dot", "produce a dot representation of the lock graph used during the analysis" )( "stats", "produce statistics about the usage of locks and threads" ) ; po::options_description hidden; hidden.add_options() ("repo-path", po::value<std::string>(), "path of the repository to examine") ; po::positional_options_description positionals; positionals.add("repo-path", 1); po::options_description analysis("Analysis options"); po::options_description dot("Dot rendering options"); po::options_description statistics("Statistics options"); po::options_description allowed; allowed.add(global).add(analysis).add(dot).add(statistics); po::options_description all; all.add(allowed).add(hidden); po::variables_map args; po::command_line_parser parser(argc, argv); try { po::store(parser.options(all).positional(positionals).run(), args); po::notify(args); } catch(po::error const& e) { std::cerr << e.what() << std::endl << allowed << std::endl; return EXIT_FAILURE; } // Some options make us do something and exit right away. These cases // are handled here. { typedef boost::function<void(po::variable_value)> DieAction; std::map<std::string, DieAction> die_actions = boost::assign::map_list_of<std::string, DieAction> ("help", phx::ref(std::cout) << allowed << '\n') ("version", phx::ref(std::cout) << VERSION << '\n') ; typedef std::pair<std::string, DieAction> DieActionPair; BOOST_FOREACH(DieActionPair const& action, die_actions) { if (args.count(action.first)) { action.second(args[action.first]); return EXIT_FAILURE; } } } // Open the repository on which we must operate. if (!args.count("repo-path")) { std::cerr << "missing the path of a repository on which to operate " "from the command line" << std::endl << allowed << std::endl; return EXIT_FAILURE; } d2::EventRepository<> repository(args["repo-path"].as<std::string>()); // Open the output stream to whatever passed on the command line or to // stdout if unspecified. std::ofstream output_ofs; if (args.count("output-file")) { std::string output_file = args["output-file"].as<std::string>(); output_ofs.open(output_file.c_str()); if (!output_ofs) { std::cerr << "Unable to open output file \"" << output_file <<'"'; return EXIT_FAILURE; } } std::ostream& output = args.count("output-file") ? output_ofs : std::cout; // Build the segmentation and the lock graph. They are required no matter // the options we received on the command line. d2::SegmentationGraph sg; d2::LockGraph lg; try { d2::build_graphs(repository, lg, sg); } catch (d2::EventTypeException const& e) { using boost::get_error_info; char const* const* actual_type = get_error_info<d2::ActualType>(e); char const* const* expected_type = get_error_info<d2::ExpectedType>(e); char const* unavailable = "\"unavailable\""; if (!actual_type) actual_type = &unavailable; if (!expected_type) expected_type = &unavailable; std::cerr << "Error while building the graphs:\n" " encountered an event of type " << *actual_type << " while expecting an event of type " << *expected_type << "." << std::endl; return EXIT_FAILURE; } // Main switch dispatching to the right action to perform. if (args.count("analyze") || (!args.count("dot") && !args.count("stats"))) { d2::analyze(lg, sg, print_cycle(std::cout)); } else if (args.count("dot")) { boost::write_graphviz(output, lg, render_dot(lg), render_dot(lg)); } else if (args.count("stats")) { Statistics<d2::LockGraph, d2::SegmentationGraph> stats(lg, sg); d2::analyze(lg, sg, gather_stats(stats)); output << stats << std::endl; } return EXIT_SUCCESS; } <commit_msg>Add error handling during the aperture of the repository in the command line utility.<commit_after>/** * This file implements a command line utility to interact * with the d2 library. */ #include <d2/analysis.hpp> #include <d2/event_repository.hpp> #include <d2/graph_construction.hpp> #include <boost/assert.hpp> #include <boost/assign.hpp> #include <boost/foreach.hpp> #include <boost/function.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/properties.hpp> #include <boost/optional.hpp> #include <boost/phoenix.hpp> #include <boost/program_options.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/scoped_ptr.hpp> #include <cstddef> #include <cstdlib> #include <fstream> #include <iostream> #include <map> #include <string> #include <utility> #include <vector> static std::string const VERSION = "0.1a"; namespace po = boost::program_options; namespace phx = boost::phoenix; using phx::arg_names::_1; namespace { // Dot rendering template <typename LockGraph> class LockGraphWriter { typedef typename boost::graph_traits<LockGraph>::edge_descriptor EdgeDescriptor; typedef typename boost::graph_traits<LockGraph>::vertex_descriptor VertexDescriptor; LockGraph const& graph_; // Silence MSVC warning C4512: assignment operator could not be generated LockGraphWriter& operator=(LockGraphWriter const&) /*= delete*/; public: explicit LockGraphWriter(LockGraph const& lg) : graph_(lg) { } template <typename Ostream> void operator()(Ostream& os, EdgeDescriptor edge) const { os << "[label=\"" << "from " << graph_[edge].l1_info.call_stack[0].function << " to " << graph_[edge].l2_info.call_stack[0].function << "\"]"; } template <typename Ostream> void operator()(Ostream&, VertexDescriptor) const { } }; template <typename LockGraph> LockGraphWriter<LockGraph> render_dot(LockGraph const& lg) { return LockGraphWriter<LockGraph>(lg); } // Statistic gathering template <typename LockGraph, typename SegmentationGraph> struct Statistics { Statistics(LockGraph const& lg, SegmentationGraph const&) : number_of_lock_graph_vertices(num_vertices(lg)), number_of_lock_graph_edges(num_edges(lg)) { } std::size_t number_of_lock_graph_vertices; std::size_t number_of_lock_graph_edges; boost::optional<std::size_t> number_of_distinct_cycles; template <typename Ostream> friend Ostream& operator<<(Ostream& os, Statistics const& self) { os << "number of vertices in the lock graph: " << self.number_of_lock_graph_vertices << '\n' << "number of edges in the lock graph: " << self.number_of_lock_graph_edges << '\n' << "number of distinct cycles in the lock graph: "; if (self.number_of_distinct_cycles) os << *self.number_of_distinct_cycles; else os << "not computed"; return os; } }; template <typename Stats> class StatisticGatherer { Stats& stats_; // Silence MSVC warning C4512: assignment operator could not be generated StatisticGatherer& operator=(StatisticGatherer const&) /*= delete*/; public: explicit StatisticGatherer(Stats& stats) : stats_(stats) { BOOST_ASSERT_MSG(!stats_.number_of_distinct_cycles, "gathering statistics on a statistic object that was already filled"); stats_.number_of_distinct_cycles = 0; } template <typename EdgePath, typename LockGraph> void operator()(EdgePath const&, LockGraph const&) const { ++*stats_.number_of_distinct_cycles; } }; template <typename Stats> StatisticGatherer<Stats> gather_stats(Stats& stats) { return StatisticGatherer<Stats>(stats); } // Deadlock analysis template <typename Ostream> class CyclePrinter { Ostream& os_; // Silence MSVC warning C4512: assignment operator could not be generated CyclePrinter& operator=(CyclePrinter const&) /*= delete*/; void format_call_stack(d2::detail::LockDebugInfo const& info, std::string const& indent = "") const { BOOST_FOREACH(d2::detail::StackFrame const& frame, info.call_stack) { os_ << indent << frame.ip << " " << frame.function << " in " << frame.module << '\n'; } } public: explicit CyclePrinter(Ostream& os) : os_(os) { } template <typename EdgePath, typename LockGraph> void operator()(EdgePath const& cycle, LockGraph const& graph) const { typedef typename boost::graph_traits<LockGraph>::edge_descriptor LockGraphEdgeDescriptor; typedef typename boost::edge_property_type<LockGraph>::type LockGraphEdge; os_ << "----------------------------------------------------"; BOOST_FOREACH(LockGraphEdgeDescriptor const& edge_desc, cycle) { LockGraphEdge const& edge = graph[edge_desc]; d2::SyncObject const& l1 = graph[source(edge_desc, graph)]; d2::SyncObject const& l2 = graph[target(edge_desc, graph)]; os_ << '\n'; os_ << "Thread " << edge.t << " acquired lock " << l2 << " in\n"; format_call_stack(edge.l2_info, " "); os_ << "while holding lock " << l1 << " taken in\n"; format_call_stack(edge.l1_info, " "); } os_ << "----------------------------------------------------\n\n"; } }; template <typename Ostream> CyclePrinter<Ostream> print_cycle(Ostream& os) { return CyclePrinter<Ostream>(os); } } // end anonymous namespace int main(int argc, char const* argv[]) { // Parse command line options. po::options_description global("Global options"); global.add_options() ( "help,h", "produce help message and exit" )( "version,v", "print version and exit" )( "output-file,o", po::value<std::string>(), "file to write the output to" )( "analyze", "perform the analysis for deadlocks" )( "dot", "produce a dot representation of the lock graph used during the analysis" )( "stats", "produce statistics about the usage of locks and threads" ) ; po::options_description hidden; hidden.add_options() ("repo-path", po::value<std::string>(), "path of the repository to examine") ("debug", "enable special debugging output") ; po::positional_options_description positionals; positionals.add("repo-path", 1); po::options_description analysis("Analysis options"); po::options_description dot("Dot rendering options"); po::options_description statistics("Statistics options"); po::options_description allowed; allowed.add(global).add(analysis).add(dot).add(statistics); po::options_description all; all.add(allowed).add(hidden); po::variables_map args; po::command_line_parser parser(argc, argv); try { po::store(parser.options(all).positional(positionals).run(), args); po::notify(args); } catch (po::error const& e) { std::cerr << e.what() << std::endl << allowed << std::endl; return EXIT_FAILURE; } // Some options make us do something and exit right away. These cases // are handled here. { typedef boost::function<void(po::variable_value)> DieAction; std::map<std::string, DieAction> die_actions = boost::assign::map_list_of<std::string, DieAction> ("help", phx::ref(std::cout) << allowed << '\n') ("version", phx::ref(std::cout) << VERSION << '\n') ; typedef std::pair<std::string, DieAction> DieActionPair; BOOST_FOREACH(DieActionPair const& action, die_actions) { if (args.count(action.first)) { action.second(args[action.first]); return EXIT_FAILURE; } } } // Open the repository on which we must operate. if (!args.count("repo-path")) { std::cerr << "missing the path of a repository on which to operate " "from the command line" << std::endl << allowed << std::endl; return EXIT_FAILURE; } std::string repo_path = args["repo-path"].as<std::string>(); boost::scoped_ptr<d2::EventRepository<> > repository; try { repository.reset(new d2::EventRepository<>(repo_path)); } catch (d2::RepositoryException const& e) { std::cerr << "unable to open the repository at \"" << repo_path << "\"\n"; if (args.count("debug")) std::cerr << boost::diagnostic_information(e) << '\n'; return EXIT_FAILURE; } // Open the output stream to whatever passed on the command line or to // stdout if unspecified. std::ofstream output_ofs; if (args.count("output-file")) { std::string output_file = args["output-file"].as<std::string>(); output_ofs.open(output_file.c_str()); if (!output_ofs) { std::cerr << "unable to open output file \"" << output_file << '"'; return EXIT_FAILURE; } } std::ostream& output = args.count("output-file") ? output_ofs : std::cout; // Build the segmentation and the lock graph. They are required no matter // the options we received on the command line. d2::SegmentationGraph sg; d2::LockGraph lg; try { d2::build_graphs(*repository, lg, sg); } catch (d2::EventTypeException const& e) { using boost::get_error_info; char const* const* actual_type = get_error_info<d2::ActualType>(e); char const* const* expected_type = get_error_info<d2::ExpectedType>(e); char const* unavailable = "\"unavailable\""; if (!actual_type) actual_type = &unavailable; if (!expected_type) expected_type = &unavailable; std::cerr << "error while building the graphs:\n" " encountered an event of type " << *actual_type << '\n' << " while expecting an event of type " << *expected_type << '\n'; return EXIT_FAILURE; } // Main switch dispatching to the right action to perform. if (args.count("analyze") || (!args.count("dot") && !args.count("stats"))) { d2::analyze(lg, sg, print_cycle(std::cout)); } else if (args.count("dot")) { boost::write_graphviz(output, lg, render_dot(lg), render_dot(lg)); } else if (args.count("stats")) { Statistics<d2::LockGraph, d2::SegmentationGraph> stats(lg, sg); d2::analyze(lg, sg, gather_stats(stats)); output << stats << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Removed incorrect StyleInvalidator FIXME.<commit_after><|endoftext|>
<commit_before>// // FileManager.hpp // CatchLib // // Created by John Barbero Unenge on 9/17/12. // Copyright (c) 2012 John Barbero Unenge. All rights reserved. // #if __APPLE__ #include <OpenGLES/ES2/gl.h> #else #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #endif #ifndef CatchiOS_FileManager_h #define CatchiOS_FileManager_h struct Texture{ GLint internalFormat; GLsizei width; GLsizei height; GLenum format; GLenum type; const GLvoid* data; }; class GLRenderer { public: GLRenderer(); ~GLRenderer(); void init(int width, int height); void createFrameBuffer(); void render(); private: GLuint BuildShader(const char* source, GLenum shaderType) const; GLuint BuildProgram(const char* vShader, const char* fShader) const; void ApplyOrtho(float maxX, float maxY) const; void ApplyRotation(float degrees) const; GLuint m_simpleProgram; GLuint m_framebuffer; GLuint m_renderbuffer; }; #endif <commit_msg>Moved the CLTexture out to SCLTexture.hpp.<commit_after>// // FileManager.hpp // CatchLib // // Created by John Barbero Unenge on 9/17/12. // Copyright (c) 2012 John Barbero Unenge. All rights reserved. // #if __APPLE__ #include <OpenGLES/ES2/gl.h> #else #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #endif #include "SCLTexture.hpp" #ifndef CatchiOS_FileManager_h #define CatchiOS_FileManager_h class GLRenderer { public: GLRenderer(); ~GLRenderer(); void init(int width, int height); void createFrameBuffer(); void render(); private: GLuint BuildShader(const char* source, GLenum shaderType) const; GLuint BuildProgram(const char* vShader, const char* fShader) const; void ApplyOrtho(float maxX, float maxY) const; void ApplyRotation(float degrees) const; GLuint m_simpleProgram; GLuint m_framebuffer; GLuint m_renderbuffer; }; #endif <|endoftext|>
<commit_before>#include <memory> #include <wx/progdlg.h> #include <wx/window.h> #include "Plater.hpp" #include "ProgressStatusBar.hpp" #include "Log.hpp" #include "MainFrame.hpp" namespace Slic3r { namespace GUI { const auto PROGRESS_BAR_EVENT = wxNewEventType(); Plater::Plater(wxWindow* parent, const wxString& title, std::shared_ptr<Settings> _settings) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, title), settings(_settings) { // Set callback for status event for worker threads /* this->print->set_status_cb([=](std::string percent percent, std::wstring message) { wxPostEvent(this, new wxPlThreadEvent(-1, PROGRESS_BAR_EVENT, }); */ auto on_select_object { [=](size_t& obj_idx) { this->select_object(obj_idx); } }; /* # Initialize handlers for canvases my $on_select_object = sub { my ($obj_idx) = @_; $self->select_object($obj_idx); }; my $on_double_click = sub { $self->object_settings_dialog if $self->selected_object; }; my $on_right_click = sub { my ($canvas, $click_pos) = @_; my ($obj_idx, $object) = $self->selected_object; return if !defined $obj_idx; my $menu = $self->object_menu; $canvas->PopupMenu($menu, $click_pos); $menu->Destroy; }; my $on_instances_moved = sub { $self->on_model_change; }; # Initialize 3D plater if ($Slic3r::GUI::have_OpenGL) { $self->{canvas3D} = Slic3r::GUI::Plater::3D->new($self->{preview_notebook}, $self->{objects}, $self->{model}, $self->{config}); $self->{preview_notebook}->AddPage($self->{canvas3D}, '3D'); $self->{canvas3D}->set_on_select_object($on_select_object); $self->{canvas3D}->set_on_double_click($on_double_click); $self->{canvas3D}->set_on_right_click(sub { $on_right_click->($self->{canvas3D}, @_); }); $self->{canvas3D}->set_on_instances_moved($on_instances_moved); $self->{canvas3D}->on_viewport_changed(sub { $self->{preview3D}->canvas->set_viewport_from_scene($self->{canvas3D}); }); } */ canvas2D = new Plate2D(preview_notebook, wxDefaultSize, objects, model, config, settings); preview_notebook->AddPage(canvas2D, _("2D")); /* # Initialize 2D preview canvas $self->{canvas} = Slic3r::GUI::Plater::2D->new($self->{preview_notebook}, wxDefaultSize, $self->{objects}, $self->{model}, $self->{config}); $self->{preview_notebook}->AddPage($self->{canvas}, '2D'); $self->{canvas}->on_select_object($on_select_object); $self->{canvas}->on_double_click($on_double_click); $self->{canvas}->on_right_click(sub { $on_right_click->($self->{canvas}, @_); }); $self->{canvas}->on_instances_moved($on_instances_moved); # Initialize 3D toolpaths preview $self->{preview3D_page_idx} = -1; if ($Slic3r::GUI::have_OpenGL) { $self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print}); $self->{preview3D}->canvas->on_viewport_changed(sub { $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas); }); $self->{preview_notebook}->AddPage($self->{preview3D}, 'Preview'); $self->{preview3D_page_idx} = $self->{preview_notebook}->GetPageCount-1; } # Initialize toolpaths preview $self->{toolpaths2D_page_idx} = -1; if ($Slic3r::GUI::have_OpenGL) { $self->{toolpaths2D} = Slic3r::GUI::Plater::2DToolpaths->new($self->{preview_notebook}, $self->{print}); $self->{preview_notebook}->AddPage($self->{toolpaths2D}, 'Layers'); $self->{toolpaths2D_page_idx} = $self->{preview_notebook}->GetPageCount-1; } EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub { wxTheApp->CallAfter(sub { my $sel = $self->{preview_notebook}->GetSelection; if ($sel == $self->{preview3D_page_idx} || $sel == $self->{toolpaths2D_page_idx}) { if (!$Slic3r::GUI::Settings->{_}{background_processing} && !$self->{processed}) { $self->statusbar->SetCancelCallback(sub { $self->stop_background_process; $self->statusbar->SetStatusText("Slicing cancelled"); $self->{preview_notebook}->SetSelection(0); }); $self->start_background_process; } else { $self->{preview3D}->load_print if $sel == $self->{preview3D_page_idx}; } } }); }); */ } void Plater::add() { Log::info(LogChannel, L"Called Add function"); auto& start_object_id = this->object_identifier; const auto& input_files{open_model(this, *(this->settings), wxTheApp->GetTopWindow())}; for (const auto& f : input_files) { Log::info(LogChannel, (wxString(L"Calling Load File for ") + f).ToStdWstring()); this->load_file(f); } // abort if no objects actually added. if (start_object_id == this->object_identifier) return; // save the added objects auto new_model {this->model}; // get newly added objects count auto new_objects_count = this->object_identifier - start_object_id; Slic3r::Log::info(LogChannel, (wxString("Obj id:") << object_identifier).ToStdWstring()); for (auto i = start_object_id; i < new_objects_count + start_object_id; i++) { const auto& obj_idx {this->get_object_index(i)}; new_model->add_object(*(this->model->objects.at(obj_idx))); } Slic3r::Log::info(LogChannel, (wxString("Obj id:") << object_identifier).ToStdWstring()); // Prepare for undo //this->add_undo_operation("ADD", nullptr, new_model, start_object_id); } std::vector<int> Plater::load_file(const wxString& file, const int obj_idx_to_load) { auto input_file {wxFileName(file)}; settings->skein_directory = input_file.GetPath(); settings->save_settings(); Slic3r::Model model; bool valid_load {true}; auto obj_idx {std::vector<int>()}; auto progress_dialog {new wxProgressDialog(_(L"Loading…"), _(L"Processing input file…"), 100, this, 0)}; progress_dialog->Pulse(); //TODO: Add a std::wstring so we can handle non-roman characters as file names. try { model = Slic3r::Model::read_from_file(file.ToStdString()); } catch (std::runtime_error& e) { show_error(this, e.what()); Slic3r::Log::error(LogChannel, LOG_WSTRING(file << " failed to load: " << e.what())); valid_load = false; } Slic3r::Log::info(LogChannel, LOG_WSTRING("load_valid is " << valid_load)); if (valid_load) { if (model.looks_like_multipart_object()) { auto dialog {new wxMessageDialog(this, _("This file contains several objects positioned at multiple heights. Instead of considering them as multiple objects, should I consider\n them this file as a single object having multiple parts?\n"), _("Multi-part object detected"), wxICON_WARNING | wxYES | wxNO)}; if (dialog->ShowModal() == wxID_YES) { model.convert_multipart_object(); } } for (auto i = 0U; i < model.objects.size(); i++) { auto object {model.objects[i]}; object->input_file = file.ToStdString(); for (auto j = 0U; j < object->volumes.size(); j++) { auto volume {object->volumes.at(j)}; volume->input_file = file.ToStdString(); volume->input_file_obj_idx = i; volume->input_file_vol_idx = j; } } auto i {0U}; if (obj_idx_to_load > 0) { Slic3r::Log::info(LogChannel, L"Loading model objects, obj_idx_to_load > 0"); const size_t idx_load = obj_idx_to_load; if (idx_load >= model.objects.size()) return std::vector<int>(); obj_idx = this->load_model_objects(model.objects.at(idx_load)); i = idx_load; } else { Slic3r::Log::info(LogChannel, L"Loading model objects, obj_idx_to_load = 0"); obj_idx = this->load_model_objects(model.objects); Slic3r::Log::info(LogChannel, LOG_WSTRING("obj_idx size: " << obj_idx.size())); } for (const auto &j : obj_idx) { this->objects[j].input_file = file; this->objects[j].input_file_obj_idx = i++; } GetFrame()->statusbar->SetStatusText(_("Loaded ") + input_file.GetName()); if (this->scaled_down) { GetFrame()->statusbar->SetStatusText(_("Your object appears to be too large, so it was automatically scaled down to fit your print bed.")); } if (this->outside_bounds) { GetFrame()->statusbar->SetStatusText(_("Some of your object(s) appear to be outside the print bed. Use the arrange button to correct this.")); } } progress_dialog->Destroy(); this->redo = std::stack<UndoOperation>(); return obj_idx; } std::vector<int> Plater::load_model_objects(ModelObject* model_object) { ModelObjectPtrs tmp {model_object}; // wrap in a std::vector return load_model_objects(tmp); } std::vector<int> Plater::load_model_objects(ModelObjectPtrs model_objects) { auto bed_center {this->bed_centerf()}; auto bed_shape {Slic3r::Polygon::new_scale(this->config->get<ConfigOptionPoints>("bed_shape").values)}; auto bed_size {bed_shape.bounding_box().size()}; bool need_arrange {false}; auto obj_idx {std::vector<int>()}; Slic3r::Log::info(LogChannel, LOG_WSTRING("Objects: " << model_objects.size())); for (auto& obj : model_objects) { auto o {this->model->add_object(*obj)}; o->repair(); auto tmpobj {PlaterObject()}; const auto objfile {wxFileName::FileName( obj->input_file )}; tmpobj.name = wxString(std::string() == obj->name ? obj->name : objfile.GetName()); tmpobj.identifier = (this->object_identifier)++; this->objects.push_back(tmpobj); obj_idx.push_back(this->objects.size()); Slic3r::Log::info(LogChannel, LOG_WSTRING("Object array new size: " << this->objects.size())); Slic3r::Log::info(LogChannel, LOG_WSTRING("Instances: " << obj->instances.size())); if (obj->instances.size() == 0) { if (settings->autocenter) { need_arrange = true; o->center_around_origin(); o->add_instance(); o->instances.back()->offset = this->bed_centerf(); } else { need_arrange = false; if (settings->autoalignz) { o->align_to_ground(); } o->add_instance(); } } else { if (settings->autoalignz) { o->align_to_ground(); } } { // If the object is too large (more than 5x the bed) scale it down. auto size {o->bounding_box().size()}; double ratio {0.0f}; if (ratio > 5) { for (auto& instance : o->instances) { instance->scaling_factor = (1.0f/ratio); this->scaled_down = true; } } } { // Provide a warning if downscaling by 5x still puts it over the bed size. } } return obj_idx; } MainFrame* Plater::GetFrame() { return dynamic_cast<MainFrame*>(wxGetTopLevelParent(this)); } int Plater::get_object_index(size_t object_id) { for (size_t i = 0U; i < this->objects.size(); i++) { if (this->objects.at(i).identifier == object_id) return static_cast<int>(i); } return -1; } }} // Namespace Slic3r::GUI <commit_msg>Remember that std::vector<>.size() needs to be offset by 1 if it's being used to find the last index.<commit_after>#include <memory> #include <wx/progdlg.h> #include <wx/window.h> #include "Plater.hpp" #include "ProgressStatusBar.hpp" #include "Log.hpp" #include "MainFrame.hpp" namespace Slic3r { namespace GUI { const auto PROGRESS_BAR_EVENT = wxNewEventType(); Plater::Plater(wxWindow* parent, const wxString& title, std::shared_ptr<Settings> _settings) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, title), settings(_settings) { // Set callback for status event for worker threads /* this->print->set_status_cb([=](std::string percent percent, std::wstring message) { wxPostEvent(this, new wxPlThreadEvent(-1, PROGRESS_BAR_EVENT, }); */ auto on_select_object { [=](size_t& obj_idx) { this->select_object(obj_idx); } }; /* # Initialize handlers for canvases my $on_select_object = sub { my ($obj_idx) = @_; $self->select_object($obj_idx); }; my $on_double_click = sub { $self->object_settings_dialog if $self->selected_object; }; my $on_right_click = sub { my ($canvas, $click_pos) = @_; my ($obj_idx, $object) = $self->selected_object; return if !defined $obj_idx; my $menu = $self->object_menu; $canvas->PopupMenu($menu, $click_pos); $menu->Destroy; }; my $on_instances_moved = sub { $self->on_model_change; }; # Initialize 3D plater if ($Slic3r::GUI::have_OpenGL) { $self->{canvas3D} = Slic3r::GUI::Plater::3D->new($self->{preview_notebook}, $self->{objects}, $self->{model}, $self->{config}); $self->{preview_notebook}->AddPage($self->{canvas3D}, '3D'); $self->{canvas3D}->set_on_select_object($on_select_object); $self->{canvas3D}->set_on_double_click($on_double_click); $self->{canvas3D}->set_on_right_click(sub { $on_right_click->($self->{canvas3D}, @_); }); $self->{canvas3D}->set_on_instances_moved($on_instances_moved); $self->{canvas3D}->on_viewport_changed(sub { $self->{preview3D}->canvas->set_viewport_from_scene($self->{canvas3D}); }); } */ canvas2D = new Plate2D(preview_notebook, wxDefaultSize, objects, model, config, settings); preview_notebook->AddPage(canvas2D, _("2D")); /* # Initialize 2D preview canvas $self->{canvas} = Slic3r::GUI::Plater::2D->new($self->{preview_notebook}, wxDefaultSize, $self->{objects}, $self->{model}, $self->{config}); $self->{preview_notebook}->AddPage($self->{canvas}, '2D'); $self->{canvas}->on_select_object($on_select_object); $self->{canvas}->on_double_click($on_double_click); $self->{canvas}->on_right_click(sub { $on_right_click->($self->{canvas}, @_); }); $self->{canvas}->on_instances_moved($on_instances_moved); # Initialize 3D toolpaths preview $self->{preview3D_page_idx} = -1; if ($Slic3r::GUI::have_OpenGL) { $self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print}); $self->{preview3D}->canvas->on_viewport_changed(sub { $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas); }); $self->{preview_notebook}->AddPage($self->{preview3D}, 'Preview'); $self->{preview3D_page_idx} = $self->{preview_notebook}->GetPageCount-1; } # Initialize toolpaths preview $self->{toolpaths2D_page_idx} = -1; if ($Slic3r::GUI::have_OpenGL) { $self->{toolpaths2D} = Slic3r::GUI::Plater::2DToolpaths->new($self->{preview_notebook}, $self->{print}); $self->{preview_notebook}->AddPage($self->{toolpaths2D}, 'Layers'); $self->{toolpaths2D_page_idx} = $self->{preview_notebook}->GetPageCount-1; } EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub { wxTheApp->CallAfter(sub { my $sel = $self->{preview_notebook}->GetSelection; if ($sel == $self->{preview3D_page_idx} || $sel == $self->{toolpaths2D_page_idx}) { if (!$Slic3r::GUI::Settings->{_}{background_processing} && !$self->{processed}) { $self->statusbar->SetCancelCallback(sub { $self->stop_background_process; $self->statusbar->SetStatusText("Slicing cancelled"); $self->{preview_notebook}->SetSelection(0); }); $self->start_background_process; } else { $self->{preview3D}->load_print if $sel == $self->{preview3D_page_idx}; } } }); }); */ } void Plater::add() { Log::info(LogChannel, L"Called Add function"); auto& start_object_id = this->object_identifier; const auto& input_files{open_model(this, *(this->settings), wxTheApp->GetTopWindow())}; for (const auto& f : input_files) { Log::info(LogChannel, (wxString(L"Calling Load File for ") + f).ToStdWstring()); this->load_file(f); } // abort if no objects actually added. if (start_object_id == this->object_identifier) return; // save the added objects auto new_model {this->model}; // get newly added objects count auto new_objects_count = this->object_identifier - start_object_id; Slic3r::Log::info(LogChannel, (wxString("Obj id:") << object_identifier).ToStdWstring()); for (auto i = start_object_id; i < new_objects_count + start_object_id; i++) { const auto& obj_idx {this->get_object_index(i)}; new_model->add_object(*(this->model->objects.at(obj_idx))); } Slic3r::Log::info(LogChannel, (wxString("Obj id:") << object_identifier).ToStdWstring()); // Prepare for undo //this->add_undo_operation("ADD", nullptr, new_model, start_object_id); } std::vector<int> Plater::load_file(const wxString& file, const int obj_idx_to_load) { auto input_file {wxFileName(file)}; settings->skein_directory = input_file.GetPath(); settings->save_settings(); Slic3r::Model model; bool valid_load {true}; auto obj_idx {std::vector<int>()}; auto progress_dialog {new wxProgressDialog(_(L"Loading…"), _(L"Processing input file…"), 100, this, 0)}; progress_dialog->Pulse(); //TODO: Add a std::wstring so we can handle non-roman characters as file names. try { model = Slic3r::Model::read_from_file(file.ToStdString()); } catch (std::runtime_error& e) { show_error(this, e.what()); Slic3r::Log::error(LogChannel, LOG_WSTRING(file << " failed to load: " << e.what())); valid_load = false; } Slic3r::Log::info(LogChannel, LOG_WSTRING("load_valid is " << valid_load)); if (valid_load) { if (model.looks_like_multipart_object()) { auto dialog {new wxMessageDialog(this, _("This file contains several objects positioned at multiple heights. Instead of considering them as multiple objects, should I consider\n them this file as a single object having multiple parts?\n"), _("Multi-part object detected"), wxICON_WARNING | wxYES | wxNO)}; if (dialog->ShowModal() == wxID_YES) { model.convert_multipart_object(); } } for (auto i = 0U; i < model.objects.size(); i++) { auto object {model.objects[i]}; object->input_file = file.ToStdString(); for (auto j = 0U; j < object->volumes.size(); j++) { auto volume {object->volumes.at(j)}; volume->input_file = file.ToStdString(); volume->input_file_obj_idx = i; volume->input_file_vol_idx = j; } } auto i {0U}; if (obj_idx_to_load > 0) { Slic3r::Log::info(LogChannel, L"Loading model objects, obj_idx_to_load > 0"); const size_t idx_load = obj_idx_to_load; if (idx_load >= model.objects.size()) return std::vector<int>(); obj_idx = this->load_model_objects(model.objects.at(idx_load)); i = idx_load; } else { Slic3r::Log::info(LogChannel, L"Loading model objects, obj_idx_to_load = 0"); obj_idx = this->load_model_objects(model.objects); Slic3r::Log::info(LogChannel, LOG_WSTRING("obj_idx size: " << obj_idx.size())); } for (const auto &j : obj_idx) { this->objects[j].input_file = file; this->objects[j].input_file_obj_idx = i++; } GetFrame()->statusbar->SetStatusText(_("Loaded ") + input_file.GetName()); if (this->scaled_down) { GetFrame()->statusbar->SetStatusText(_("Your object appears to be too large, so it was automatically scaled down to fit your print bed.")); } if (this->outside_bounds) { GetFrame()->statusbar->SetStatusText(_("Some of your object(s) appear to be outside the print bed. Use the arrange button to correct this.")); } } progress_dialog->Destroy(); this->redo = std::stack<UndoOperation>(); return obj_idx; } std::vector<int> Plater::load_model_objects(ModelObject* model_object) { ModelObjectPtrs tmp {model_object}; // wrap in a std::vector return load_model_objects(tmp); } std::vector<int> Plater::load_model_objects(ModelObjectPtrs model_objects) { auto bed_center {this->bed_centerf()}; auto bed_shape {Slic3r::Polygon::new_scale(this->config->get<ConfigOptionPoints>("bed_shape").values)}; auto bed_size {bed_shape.bounding_box().size()}; bool need_arrange {false}; auto obj_idx {std::vector<int>()}; Slic3r::Log::info(LogChannel, LOG_WSTRING("Objects: " << model_objects.size())); for (auto& obj : model_objects) { auto o {this->model->add_object(*obj)}; o->repair(); auto tmpobj {PlaterObject()}; const auto objfile {wxFileName::FileName( obj->input_file )}; tmpobj.name = wxString(std::string() == obj->name ? obj->name : objfile.GetName()); tmpobj.identifier = (this->object_identifier)++; this->objects.push_back(tmpobj); obj_idx.push_back(this->objects.size() - 1); Slic3r::Log::info(LogChannel, LOG_WSTRING("Object array new size: " << this->objects.size())); Slic3r::Log::info(LogChannel, LOG_WSTRING("Instances: " << obj->instances.size())); if (obj->instances.size() == 0) { if (settings->autocenter) { need_arrange = true; o->center_around_origin(); o->add_instance(); o->instances.back()->offset = this->bed_centerf(); } else { need_arrange = false; if (settings->autoalignz) { o->align_to_ground(); } o->add_instance(); } } else { if (settings->autoalignz) { o->align_to_ground(); } } { // If the object is too large (more than 5x the bed) scale it down. auto size {o->bounding_box().size()}; double ratio {0.0f}; if (ratio > 5) { for (auto& instance : o->instances) { instance->scaling_factor = (1.0f/ratio); this->scaled_down = true; } } } { // Provide a warning if downscaling by 5x still puts it over the bed size. } } return obj_idx; } MainFrame* Plater::GetFrame() { return dynamic_cast<MainFrame*>(wxGetTopLevelParent(this)); } int Plater::get_object_index(size_t object_id) { for (size_t i = 0U; i < this->objects.size(); i++) { if (this->objects.at(i).identifier == object_id) return static_cast<int>(i); } return -1; } }} // Namespace Slic3r::GUI <|endoftext|>
<commit_before>/* * For licensing please refer to the LICENSE.md file */ #pragma once #include <string> #include <vector> #include <valarray> #include <array> #include <fstream> #include <map> namespace neon { struct ElementData { ElementData(int numberOfNodes, int numberOfTags, int elementType, int id) : tags(numberOfTags, 0), nodalConnectivity(numberOfNodes, 0), elementType(elementType), id(id) { } std::vector<int> tags; std::vector<int> nodalConnectivity; int elementType; int id; }; struct NodeData { int id; std::array<double, 3> coordinates; }; /*! * \class GmshReader * \brief Parses Gmsh format and returns the data structures of the mesh * in a format for neon to process */ class GmshReader { public: using StringKey = std::string; using Value = std::vector<ElementData>; public: GmshReader(const std::string& fileName); ~GmshReader() = default; /** Gmsh element numbering scheme */ enum { LINE2 = 1, TRI3, QUAD4, TETRA4, HEX8, PRISM6, TRI6 = 9, TETRA10 = 11}; const std::map<StringKey, Value>& mesh() const {return gmshMesh;} private: /** * Parse the gmsh file as provided by the filename with the appended file * extension (.msh) * @param file name of the mesh to open * @return true if the read was successful */ bool parse(const std::string& fileName); /** * Provide a reference to the nodes and dimensions that will be populated * with the correct data based on the elementType * @param Gmsh element number * @return number of nodes per element */ short mapElementData(int elementType); /** * Check the version of gmsh is support otherwise print out a warning * @param gmshVersion */ void checkSupportedGmsh(float gmshVersion); void fillMesh(); private: std::map<StringKey, Value> gmshMesh; std::map<int, std::string> physicalGroupMap; std::vector<NodeData> nodeList; std::string fileName; //!< File name of gmsh file std::fstream gmshFile; //!< Hold an object to the file stream }; } <commit_msg>Added enumerations for each available element type<commit_after>/* * For licensing please refer to the LICENSE.md file */ #pragma once #include <string> #include <vector> #include <valarray> #include <array> #include <fstream> #include <map> namespace neon { struct ElementData { ElementData(int numberOfNodes, int numberOfTags, int elementType, int id) : tags(numberOfTags, 0), nodalConnectivity(numberOfNodes, 0), elementType(elementType), id(id) { } std::vector<int> tags; std::vector<int> nodalConnectivity; int elementType; int id; }; struct NodeData { int id; std::array<double, 3> coordinates; }; /*! * \class GmshReader * \brief Parses Gmsh format and returns the data structures of the mesh * in a format for neon to process */ class GmshReader { public: using StringKey = std::string; using Value = std::vector<ElementData>; public: GmshReader(const std::string& fileName); ~GmshReader() = default; /** Gmsh element numbering scheme */ enum ELEMENT_TYPE_ID {// Standard linear elements LINE2=1, TRIANGLE3, QUADRILATERAL4, TETRAHEDRON4, HEXAHEDRON8, PRISM6, PYRAMID5, // Quadratic elements LINE3, TRIANGLE6, QUADRILATERAL9, // 4 vertex, 4 edges and 1 face node TETRAHEDRON10, HEXAHEDRON27, PRISM18, PYRAMID14, POINT = 15, QUADRILATERAL8, HEXAHEDRON20, PRISM15, PYRAMID13, TRIANGLE9 = 20, TRIANGLE10, TRIANGLE12, TRIANGLE15, TRIANGLE15_IC, // Incomplete 15 node triangle TRIANGLE21 = 25, EDGE4, EDGE5, EDGE6, TETRAHEDRON20, TETRAHEDRON35, TETRAHEDRON56, HEXAHEDRON64 = 92, HEXAHEDRON125}; const std::map<StringKey, Value>& mesh() const {return gmshMesh;} private: /** * Parse the gmsh file as provided by the filename with the appended file * extension (.msh) * @param file name of the mesh to open * @return true if the read was successful */ bool parse(const std::string& fileName); /** * Provide a reference to the nodes and dimensions that will be populated * with the correct data based on the elementType * @param Gmsh element number * @return number of nodes per element */ short mapElementData(int elementType); /** * Check the version of gmsh is support otherwise print out a warning * @param gmshVersion */ void checkSupportedGmsh(float gmshVersion); void fillMesh(); private: std::map<StringKey, Value> gmshMesh; std::map<int, std::string> physicalGroupMap; std::vector<NodeData> nodeList; std::string fileName; //!< File name of gmsh file std::fstream gmshFile; //!< Hold an object to the file stream }; } <|endoftext|>
<commit_before>// Copyright (c) 2011 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 <windows.h> #include <uxtheme.h> #include <vsstyle.h> #include <vssym32.h> #include "base/command_line.h" #include "base/memory/ref_counted_memory.h" #include "base/memory/scoped_ptr.h" #include "base/resource_util.h" #include "grit/gfx_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/brush.h" #include "ui/gfx/canvas_direct2d.h" #include "ui/gfx/canvas_skia.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/native_theme_win.h" #include "ui/gfx/rect.h" #include "ui/gfx/win_util.h" namespace { const char kVisibleModeFlag[] = "d2d-canvas-visible"; const wchar_t kWindowClassName[] = L"GFXD2DTestWindowClass"; class TestWindow { public: static const int kWindowSize = 500; static const int kWindowPosition = 10; TestWindow() : hwnd_(NULL) { if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) Sleep(1000); RegisterMyClass(); hwnd_ = CreateWindowEx(0, kWindowClassName, NULL, WS_OVERLAPPEDWINDOW, kWindowPosition, kWindowPosition, kWindowSize, kWindowSize, NULL, NULL, NULL, this); DCHECK(hwnd_); // Initialize the RenderTarget for the window. rt_ = MakeHWNDRenderTarget(); if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) ShowWindow(hwnd(), SW_SHOW); } virtual ~TestWindow() { if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) Sleep(1000); DestroyWindow(hwnd()); UnregisterMyClass(); } HWND hwnd() const { return hwnd_; } ID2D1RenderTarget* rt() const { return rt_.get(); } private: ID2D1RenderTarget* MakeHWNDRenderTarget() { D2D1_RENDER_TARGET_PROPERTIES rt_properties = D2D1::RenderTargetProperties(); rt_properties.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE; ID2D1HwndRenderTarget* rt = NULL; gfx::CanvasDirect2D::GetD2D1Factory()->CreateHwndRenderTarget( rt_properties, D2D1::HwndRenderTargetProperties(hwnd(), D2D1::SizeU(500, 500)), &rt); return rt; } void RegisterMyClass() { WNDCLASSEX class_ex; class_ex.cbSize = sizeof(WNDCLASSEX); class_ex.style = CS_DBLCLKS; class_ex.lpfnWndProc = &DefWindowProc; class_ex.cbClsExtra = 0; class_ex.cbWndExtra = 0; class_ex.hInstance = NULL; class_ex.hIcon = NULL; class_ex.hCursor = LoadCursor(NULL, IDC_ARROW); class_ex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND); class_ex.lpszMenuName = NULL; class_ex.lpszClassName = kWindowClassName; class_ex.hIconSm = class_ex.hIcon; ATOM atom = RegisterClassEx(&class_ex); DCHECK(atom); } void UnregisterMyClass() { ::UnregisterClass(kWindowClassName, NULL); } HWND hwnd_; ScopedComPtr<ID2D1RenderTarget> rt_; DISALLOW_COPY_AND_ASSIGN(TestWindow); }; // Loads a png data blob from the data resources associated with this // executable, decodes it and returns a SkBitmap. SkBitmap LoadBitmapFromResources(int resource_id) { SkBitmap bitmap; HINSTANCE resource_instance = GetModuleHandle(NULL); void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(resource_instance, resource_id, &data_ptr, &data_size)) { scoped_refptr<RefCountedMemory> memory(new RefCountedStaticMemory( reinterpret_cast<const unsigned char*>(data_ptr), data_size)); if (!memory) return bitmap; if (!gfx::PNGCodec::Decode(memory->front(), memory->size(), &bitmap)) NOTREACHED() << "Unable to decode theme image resource " << resource_id; } return bitmap; } bool CheckForD2DCompatibility() { if (!gfx::Direct2dIsAvailable()) { LOG(WARNING) << "Test is disabled as it requires either Windows 7 or " << "Vista with Platform Update KB971644"; return false; } return true; } } // namespace TEST(CanvasDirect2D, CreateCanvas) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); } TEST(CanvasDirect2D, SaveRestoreNesting) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Simple. canvas.Save(); canvas.Restore(); // Nested. canvas.Save(); canvas.Save(); canvas.Restore(); canvas.Restore(); // Simple alpha. canvas.SaveLayerAlpha(127); canvas.Restore(); // Alpha with sub-rect. canvas.SaveLayerAlpha(127, gfx::Rect(20, 20, 100, 100)); canvas.Restore(); // Nested alpha. canvas.Save(); canvas.SaveLayerAlpha(127); canvas.Save(); canvas.Restore(); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, SaveLayerAlpha) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100); canvas.SaveLayerAlpha(127); canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, SaveLayerAlphaWithBounds) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100); canvas.SaveLayerAlpha(127, gfx::Rect(60, 60, 50, 50)); canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, FillRect) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.FillRectInt(SK_ColorRED, 20, 20, 100, 100); } TEST(CanvasDirect2D, PlatformPainting) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); gfx::NativeDrawingContext dc = canvas.BeginPlatformPaint(); // Use the system theme engine to draw a native button. This only works on a // GDI device context. RECT r = { 20, 20, 220, 80 }; gfx::NativeThemeWin::instance()->PaintButton( dc, BP_PUSHBUTTON, PBS_NORMAL, DFCS_BUTTONPUSH, &r); canvas.EndPlatformPaint(); } TEST(CanvasDirect2D, ClipRect) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); } TEST(CanvasDirect2D, ClipRectWithTranslate) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Repeat the same rendering as in ClipRect... canvas.Save(); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); canvas.Restore(); // ... then translate, clip and fill again relative to the new origin. canvas.Save(); canvas.TranslateInt(150, 150); canvas.ClipRectInt(10, 10, 110, 110); canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500); canvas.Restore(); } TEST(CanvasDirect2D, ClipRectWithScale) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Repeat the same rendering as in ClipRect... canvas.Save(); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); canvas.Restore(); // ... then translate and scale, clip and fill again relative to the new // origin. canvas.Save(); canvas.TranslateInt(150, 150); canvas.ScaleInt(2, 2); canvas.ClipRectInt(10, 10, 110, 110); canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500); canvas.Restore(); } TEST(CanvasDirect2D, DrawRectInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.DrawRectInt(SK_ColorRED, 10, 10, 200, 200); canvas.Restore(); } TEST(CanvasDirect2D, DrawLineInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.DrawLineInt(SK_ColorRED, 10, 10, 210, 210); canvas.Restore(); } TEST(CanvasDirect2D, DrawBitmapInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.DrawBitmapInt(bitmap, 100, 100); canvas.Restore(); } TEST(CanvasDirect2D, DrawBitmapInt2) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 10, 10, 30, 30, false); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 110, 110, 100, 100, true); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 220, 220, 100, 100, false); canvas.Restore(); } TEST(CanvasDirect2D, TileImageInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.TileImageInt(bitmap, 10, 10, 300, 300); canvas.Restore(); } <commit_msg>Removing uneeded test. Because of the native theme cleanup, the method being called here is going away anyway.<commit_after>// Copyright (c) 2011 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 <windows.h> #include <uxtheme.h> #include <vsstyle.h> #include <vssym32.h> #include "base/command_line.h" #include "base/memory/ref_counted_memory.h" #include "base/memory/scoped_ptr.h" #include "base/resource_util.h" #include "grit/gfx_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/brush.h" #include "ui/gfx/canvas_direct2d.h" #include "ui/gfx/canvas_skia.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/rect.h" #include "ui/gfx/win_util.h" namespace { const char kVisibleModeFlag[] = "d2d-canvas-visible"; const wchar_t kWindowClassName[] = L"GFXD2DTestWindowClass"; class TestWindow { public: static const int kWindowSize = 500; static const int kWindowPosition = 10; TestWindow() : hwnd_(NULL) { if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) Sleep(1000); RegisterMyClass(); hwnd_ = CreateWindowEx(0, kWindowClassName, NULL, WS_OVERLAPPEDWINDOW, kWindowPosition, kWindowPosition, kWindowSize, kWindowSize, NULL, NULL, NULL, this); DCHECK(hwnd_); // Initialize the RenderTarget for the window. rt_ = MakeHWNDRenderTarget(); if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) ShowWindow(hwnd(), SW_SHOW); } virtual ~TestWindow() { if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) Sleep(1000); DestroyWindow(hwnd()); UnregisterMyClass(); } HWND hwnd() const { return hwnd_; } ID2D1RenderTarget* rt() const { return rt_.get(); } private: ID2D1RenderTarget* MakeHWNDRenderTarget() { D2D1_RENDER_TARGET_PROPERTIES rt_properties = D2D1::RenderTargetProperties(); rt_properties.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE; ID2D1HwndRenderTarget* rt = NULL; gfx::CanvasDirect2D::GetD2D1Factory()->CreateHwndRenderTarget( rt_properties, D2D1::HwndRenderTargetProperties(hwnd(), D2D1::SizeU(500, 500)), &rt); return rt; } void RegisterMyClass() { WNDCLASSEX class_ex; class_ex.cbSize = sizeof(WNDCLASSEX); class_ex.style = CS_DBLCLKS; class_ex.lpfnWndProc = &DefWindowProc; class_ex.cbClsExtra = 0; class_ex.cbWndExtra = 0; class_ex.hInstance = NULL; class_ex.hIcon = NULL; class_ex.hCursor = LoadCursor(NULL, IDC_ARROW); class_ex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND); class_ex.lpszMenuName = NULL; class_ex.lpszClassName = kWindowClassName; class_ex.hIconSm = class_ex.hIcon; ATOM atom = RegisterClassEx(&class_ex); DCHECK(atom); } void UnregisterMyClass() { ::UnregisterClass(kWindowClassName, NULL); } HWND hwnd_; ScopedComPtr<ID2D1RenderTarget> rt_; DISALLOW_COPY_AND_ASSIGN(TestWindow); }; // Loads a png data blob from the data resources associated with this // executable, decodes it and returns a SkBitmap. SkBitmap LoadBitmapFromResources(int resource_id) { SkBitmap bitmap; HINSTANCE resource_instance = GetModuleHandle(NULL); void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(resource_instance, resource_id, &data_ptr, &data_size)) { scoped_refptr<RefCountedMemory> memory(new RefCountedStaticMemory( reinterpret_cast<const unsigned char*>(data_ptr), data_size)); if (!memory) return bitmap; if (!gfx::PNGCodec::Decode(memory->front(), memory->size(), &bitmap)) NOTREACHED() << "Unable to decode theme image resource " << resource_id; } return bitmap; } bool CheckForD2DCompatibility() { if (!gfx::Direct2dIsAvailable()) { LOG(WARNING) << "Test is disabled as it requires either Windows 7 or " << "Vista with Platform Update KB971644"; return false; } return true; } } // namespace TEST(CanvasDirect2D, CreateCanvas) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); } TEST(CanvasDirect2D, SaveRestoreNesting) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Simple. canvas.Save(); canvas.Restore(); // Nested. canvas.Save(); canvas.Save(); canvas.Restore(); canvas.Restore(); // Simple alpha. canvas.SaveLayerAlpha(127); canvas.Restore(); // Alpha with sub-rect. canvas.SaveLayerAlpha(127, gfx::Rect(20, 20, 100, 100)); canvas.Restore(); // Nested alpha. canvas.Save(); canvas.SaveLayerAlpha(127); canvas.Save(); canvas.Restore(); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, SaveLayerAlpha) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100); canvas.SaveLayerAlpha(127); canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, SaveLayerAlphaWithBounds) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100); canvas.SaveLayerAlpha(127, gfx::Rect(60, 60, 50, 50)); canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, FillRect) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.FillRectInt(SK_ColorRED, 20, 20, 100, 100); } TEST(CanvasDirect2D, ClipRect) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); } TEST(CanvasDirect2D, ClipRectWithTranslate) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Repeat the same rendering as in ClipRect... canvas.Save(); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); canvas.Restore(); // ... then translate, clip and fill again relative to the new origin. canvas.Save(); canvas.TranslateInt(150, 150); canvas.ClipRectInt(10, 10, 110, 110); canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500); canvas.Restore(); } TEST(CanvasDirect2D, ClipRectWithScale) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Repeat the same rendering as in ClipRect... canvas.Save(); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); canvas.Restore(); // ... then translate and scale, clip and fill again relative to the new // origin. canvas.Save(); canvas.TranslateInt(150, 150); canvas.ScaleInt(2, 2); canvas.ClipRectInt(10, 10, 110, 110); canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500); canvas.Restore(); } TEST(CanvasDirect2D, DrawRectInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.DrawRectInt(SK_ColorRED, 10, 10, 200, 200); canvas.Restore(); } TEST(CanvasDirect2D, DrawLineInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.DrawLineInt(SK_ColorRED, 10, 10, 210, 210); canvas.Restore(); } TEST(CanvasDirect2D, DrawBitmapInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.DrawBitmapInt(bitmap, 100, 100); canvas.Restore(); } TEST(CanvasDirect2D, DrawBitmapInt2) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 10, 10, 30, 30, false); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 110, 110, 100, 100, true); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 220, 220, 100, 100, false); canvas.Restore(); } TEST(CanvasDirect2D, TileImageInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.TileImageInt(bitmap, 10, 10, 300, 300); canvas.Restore(); } <|endoftext|>
<commit_before>#include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "thor/PrimitiveTypes.h" #include "thor/lang/Language.h" #include "thor/lang/String.h" #include "thor/container/Vector.h" using namespace thor; namespace { void draw_background(SDL_Renderer *renderer, int w, int h) { SDL_Color col[2] = { { 0x66, 0x66, 0x66, 0xff }, { 0x99, 0x99, 0x99, 0xff }, }; int i, x, y; SDL_Rect rect; rect.w = 8; rect.h = 8; for (y = 0; y < h; y += rect.h) { for (x = 0; x < w; x += rect.w) { /* use an 8x8 checkerboard pattern */ i = (((x ^ y) >> 3) & 1); SDL_SetRenderDrawColor(renderer, col[i].r, col[i].g, col[i].b, col[i].a); rect.x = x; rect.y = y; SDL_RenderFillRect(renderer, &rect); } } } } namespace imgutil { class Image : public thor::lang::Object { public: using PixCont = thor::container::Vector<int32>; Image(); ~Image(); bool load(thor::lang::String* filename); PixCont* getAllPixels(); void setAllPixels(PixCont* pixs); SDL_Surface *surface; }; Image::Image() : surface(nullptr) { } Image::~Image() { SDL_FreeSurface(surface); } bool Image::load(thor::lang::String* filename) { char cfilename[64]; wcstombs(cfilename, filename->data->c_str(), sizeof(cfilename)); surface = IMG_Load(cfilename); return surface != nullptr; } auto Image::getAllPixels() -> PixCont* { int w = surface->w; int h = surface->h; int total = w*h; int* ori_pixs = reinterpret_cast<int*>(surface->pixels); // FIXME: instead of total, create() always get a UINT_MAX...WTF? // PixCont* pixs = PixCont::create(static_cast<int64>(total)); PixCont* pixs = PixCont::create(); for(int i = 0; i < total; ++i) { int val = *ori_pixs; // pixs->set(i, val); pixs->pushBack(val); ++ori_pixs; } return pixs; } void Image::setAllPixels(PixCont* pixs) { int w = surface->w; int h = surface->h; int total = w*h; int* ori_pixs = reinterpret_cast<int*>(surface->pixels); for(int i = 0; i < total; ++i) { int val = pixs->get(i); *ori_pixs = val; ++ori_pixs; } } class Window : public thor::lang::Object { public: Window(int32 x, int32 y); ~Window(); bool isQuit(); void handleEvent(); void showImage(Image* img); private: SDL_Window *_window; SDL_Renderer *_render; SDL_Texture *_texture; bool _quit; }; Window::Window(int32 x, int32 y) : _window(nullptr), _render(nullptr), _texture(nullptr), _quit(false) { SDL_CreateWindowAndRenderer(0, 0, 0, &_window, &_render); SDL_SetWindowPosition(_window, 0, 0); SDL_SetWindowTitle(_window, "Thorlang Monochrome"); std::assert(_window != nullptr && _render != nullptr && "Failed to create SDL_Window / SDL_Renderer."); } Window::~Window() { SDL_DestroyRenderer(_render); SDL_DestroyWindow(_window); } bool Window::isQuit() { return _quit; } void Window::handleEvent() { SDL_Event event; while(SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_ESCAPE: _quit = 1; default: break; } break; case SDL_QUIT: _quit = 1; break; default: break; } } } void Window::showImage(Image* img) { int w, h; _texture = SDL_CreateTextureFromSurface(_render, img->surface); SDL_QueryTexture(_texture, nullptr, nullptr, &w, &h); SDL_SetWindowSize(_window, w, h); draw_background(_render, w, h); SDL_RenderCopy(_render, _texture, nullptr, nullptr); SDL_RenderPresent(_render); SDL_ShowWindow(_window); } bool initialize() { int result = SDL_Init(SDL_INIT_VIDEO); return result == 0; } void finalize() { SDL_Quit(); } } <commit_msg>Fix: release texture if any<commit_after>#include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "thor/PrimitiveTypes.h" #include "thor/lang/Language.h" #include "thor/lang/String.h" #include "thor/container/Vector.h" using namespace thor; namespace { void draw_background(SDL_Renderer *renderer, int w, int h) { SDL_Color col[2] = { { 0x66, 0x66, 0x66, 0xff }, { 0x99, 0x99, 0x99, 0xff }, }; int i, x, y; SDL_Rect rect; rect.w = 8; rect.h = 8; for (y = 0; y < h; y += rect.h) { for (x = 0; x < w; x += rect.w) { /* use an 8x8 checkerboard pattern */ i = (((x ^ y) >> 3) & 1); SDL_SetRenderDrawColor(renderer, col[i].r, col[i].g, col[i].b, col[i].a); rect.x = x; rect.y = y; SDL_RenderFillRect(renderer, &rect); } } } } namespace imgutil { class Image : public thor::lang::Object { public: using PixCont = thor::container::Vector<int32>; Image(); ~Image(); bool load(thor::lang::String* filename); PixCont* getAllPixels(); void setAllPixels(PixCont* pixs); SDL_Surface *surface; }; Image::Image() : surface(nullptr) { } Image::~Image() { SDL_FreeSurface(surface); } bool Image::load(thor::lang::String* filename) { char cfilename[64]; wcstombs(cfilename, filename->data->c_str(), sizeof(cfilename)); surface = IMG_Load(cfilename); return surface != nullptr; } auto Image::getAllPixels() -> PixCont* { int w = surface->w; int h = surface->h; int total = w*h; int* ori_pixs = reinterpret_cast<int*>(surface->pixels); // FIXME: instead of total, create() always get a UINT_MAX...WTF? // PixCont* pixs = PixCont::create(static_cast<int64>(total)); PixCont* pixs = PixCont::create(); for(int i = 0; i < total; ++i) { int val = *ori_pixs; // pixs->set(i, val); pixs->pushBack(val); ++ori_pixs; } return pixs; } void Image::setAllPixels(PixCont* pixs) { int w = surface->w; int h = surface->h; int total = w*h; int* ori_pixs = reinterpret_cast<int*>(surface->pixels); for(int i = 0; i < total; ++i) { int val = pixs->get(i); *ori_pixs = val; ++ori_pixs; } } class Window : public thor::lang::Object { public: Window(int32 x, int32 y); ~Window(); bool isQuit(); void handleEvent(); void showImage(Image* img); private: SDL_Window *_window; SDL_Renderer *_render; SDL_Texture *_texture; bool _quit; }; Window::Window(int32 x, int32 y) : _window(nullptr), _render(nullptr), _texture(nullptr), _quit(false) { SDL_CreateWindowAndRenderer(0, 0, 0, &_window, &_render); SDL_SetWindowPosition(_window, 0, 0); SDL_SetWindowTitle(_window, "Thorlang Monochrome"); std::assert(_window != nullptr && _render != nullptr && "Failed to create SDL_Window / SDL_Renderer."); } Window::~Window() { if(_texture != nullptr) SDL_DestroyTexture(_texture); SDL_DestroyRenderer(_render); SDL_DestroyWindow(_window); } bool Window::isQuit() { return _quit; } void Window::handleEvent() { SDL_Event event; while(SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_ESCAPE: _quit = 1; default: break; } break; case SDL_QUIT: _quit = 1; break; default: break; } } } void Window::showImage(Image* img) { int w, h; _texture = SDL_CreateTextureFromSurface(_render, img->surface); SDL_QueryTexture(_texture, nullptr, nullptr, &w, &h); SDL_SetWindowSize(_window, w, h); draw_background(_render, w, h); SDL_RenderCopy(_render, _texture, nullptr, nullptr); SDL_RenderPresent(_render); SDL_ShowWindow(_window); } bool initialize() { int result = SDL_Init(SDL_INIT_VIDEO); return result == 0; } void finalize() { SDL_Quit(); } } <|endoftext|>
<commit_before>/// @author Владимир Керимов #pragma once #include <data/bytes> #include <data_head/object_data.hpp> namespace data { class bytes::data : public object::data { public: data(); private: }; } // sine qua non <commit_msg>Saved change.<commit_after>/// @author Владимир Керимов #pragma once #include <data/bytes> #include <data_head/object_data.hpp> namespace data { class bytes::data : public object::data { public: data(); private: std::string m_array; }; } // sine qua non <|endoftext|>
<commit_before><commit_msg>BUG: removing items and adding again clears previous selection. mantis #1025<commit_after><|endoftext|>
<commit_before>/* A recursive C++ program to find Grundy Number for a game. Game Description : The game starts with a number- 'n' and the player to move divides the number- 'n' with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. */ #include<bits/stdc++.h> using namespace std; // A Function to calculate Mex of all the values in // that set. int calculateMex(unordered_set<int> Set) { int Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex); } // A function to Compute Grundy Number of 'n' // Only this function varies according to the game int calculateGrundy (int n) { if (n == 0) return (0); unordered_set<int> Set; // A Hash Table Set.insert(calculateGrundy(n/2)); Set.insert(calculateGrundy(n/3)); Set.insert(calculateGrundy(n/6)); return (calculateMex(Set)); } // Driver program to test above functions int main() { int n = 10; printf("%d", calculateGrundy (n)); return (0); } <commit_msg>Delete Combinatorial_Game_Theory_Nimbers_and_Mex.cpp<commit_after><|endoftext|>
<commit_before>/* Copyright 2011, Jernej Kovacic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** @file NumericUtil.cpp Implementation of the class NumericUtil, a collection of some useful numerical utilities. This is a templated class and must not be compiled. Instead it must be included after the class declaration in the .h file @author Jernej Kovacic */ // Deliberately there is no #include "NumericUtil.h" #include "Rational.h" #include "SqMatrixGeneric.h" #include "PolynomialGeneric.h" #include <complex> // Note that the optimal EPS depends on application requirements /* * Definition of EPS for type float */ template<> float math::NumericUtil<float>::EPS = 1e-9f; /* * Double is a more accurate type... */ template<> double math::NumericUtil<double>::EPS = 1e-16; /* * and long double is even more accurate */ template<> long double math::NumericUtil<long double>::EPS = 1e-22L; /* * In int and other types, EPS doesn't make sense, so set it to 0 */ template<class T> T math::NumericUtil<T>::EPS = static_cast<T>(0); /** * A constant value with the T's representation of zero (0) */ template<class T> const T math::NumericUtil<T>::ZERO ( static_cast<T>(0) ); /** * A constant value with the T's representation of one (1) */ template<class T> const T math::NumericUtil<T>::ONE ( static_cast<T>(1) ); /** * Does the given value equal (or is close enough to) zero? * Implementation depends on the type T. * For floating point types (float, double, long double), it checks * whether its absolute value is less than a hardcoded constant 'eps'. * * @param value * @ @return true or false */ template<class T> bool math::NumericUtil<T>::isZero(const T& value) { /* * The implementation for integers et al. where the == operator * does make sense and no comparison to EPS is necessary. */ bool retVal = ( ZERO==value ? true : false ); return retVal; } /* * Float, double and long double require specialized implementations of isZero(). * In case of these three types, the equality operator (==) is useless. * In numerical mathematics, two numbers are considered "equal", when * absolute value of their difference does not exceed a reasonably set EPS. * All specializations are very similar and only differ in types of an input value. * For easier maintainability, the specialization will be implemented * only once using a parameterized #define */ #define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FDL) \ template<> \ bool math::NumericUtil<FDL>::isZero(const FDL& value) \ { \ bool retVal = false; \ retVal = ( value>-EPS && value<EPS ? true : false ); \ return retVal; \ } // end of #define // derive specialization for float: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float) // ... for double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double) // ... and long double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO /* * Specialization for complex. * As complex is a templated class, again it must be implemented for each supported subtemplated * type. To facilitate this, a parameterized macro is introduced. * Note: norm() calculates a sum of both parts' squares. It is a bit more efficient to compare * it with EPS^2 than calculating its square root (the actual definition of complex abs. value). */ #define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(FDL) \ template<> \ bool math::NumericUtil<std::complex<FDL> >::isZero(const std::complex<FDL>& value) \ { \ bool retVal = false; \ const FDL eps = math::NumericUtil<FDL>::getEPS(); \ retVal = ( std::norm(value)<=eps*eps ? true : false ); \ return retVal; \ } // end of #define // derive specialization for float: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(float) // ... for double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(double) // ... and long double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX /* * Implementation for Rational */ template<> bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value) { // Rational already contains its own isZero()... return value.isZero(); } /** * @return value of 'eps' for the desired type */ template<class T> T math::NumericUtil<T>::getEPS() { return EPS; } /** * Sets the new value of 'eps' for the desired type if the default one does * not meet application's requirements. * * @note There is no check of input so make sure a sensible value * (typically a very small positive number) is entered. * * @param eps - new value of EPS */ template<class T> void math::NumericUtil<T>::setEPS(const T& eps) { EPS = eps; } /* * In C++, it is not possible to specialize a function of a templated class * if the specialization is also a generic type (e.g. T -> math::SqMatrixGeneric<T>). * However it is possible if a single function is templated. * For more details, see the discussion at: * http://www.cplusplus.com/forum/general/68298/ * * At the moment, getUnit() is only used by power(). Until it is changed, * getUnit() will be defined in this file as a templated standalone function. * Additionlly, implementations of the function are "hidden" in the namespace * math::getunit which is not supposed to be known to other members of math:: */ namespace math { namespace getunit { /* * @param t - an arbitrary instance of T, ignored by the generic implementation, * at specializations it might be useful to determine unit's dimensions etc. * * @return an instance of T acting as a multiplication unit */ template<class T> T getUnit(const T& t) { return T(math::NumericUtil<T>::ONE); } /* * Specialization for generic class math::SqMatrixGeneric<T> * * @param t - an arbitrary instance of a square matrix to determine * dimensions of the returned unit matrix * * @return a unit nxn square matrix where n is a dimension of 't' */ template<class T> math::SqMatrixGeneric<T> getUnit(const math::SqMatrixGeneric<T>& t) { const unsigned int N = t.nrRows(); math::SqMatrixGeneric<T> retVal(N); retVal.setUnit(); return retVal; } /* * Specialization for generic class math::PolynomialGeneric<T> * * @param t - ignored * * @return a unit polynomial p(x) = (T)1 */ template<class T> math::PolynomialGeneric<T> getUnit(const math::PolynomialGeneric<T>& t) { math::PolynomialGeneric<T> retVal(1); retVal.set(0, math::NumericUtil<T>::ONE); return retVal; } } // namespace units } // namespace math /** * Efficient calculation of positive integer power. * Complexity of the algorithm is O(log2 n). * * @note T must have implemented operator*= * * @param base - base of the exponentiation * @param n - exponent (a positive integer number) * * @return base^n */ template<class T> T math::NumericUtil<T>::power(const T& base, unsigned int n) { /* * "Exponentiation by squaring" algorithm will be applied. * * Exponentiation can be expanded into: * n n%2 n/2 * a = a * (a^2) * * where / and % are integer division and remainder operators. * * The expression above can be further recursively derived to: * n n%2 (n/2)%2 (n/2)/2 * a = a (a^2) (a^4) = * * n%2 (n/2)%2 (n/4)%2 ((n/2)/2)/2 * = a (a^2) (a^4) (a^8) = .... * * It is simple to develop an iterative algorithm where factor * is iteratively increased by squaring itself and coefficients * ai (i=0..n) are iteratively calculated by the remainder of * division by 2 */ // Note: it is safe to use bitwise operators for arithmetic operations // on unsigned int values as they do not depend on endianess: // http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness T retVal = math::getunit::getUnit(base); T factor = base; // Obtain coefficients ai from the exponent's binary form. // Note: "i>>=1" is a bitwise equivalent bitwise equivalent of "i/=2" for ( unsigned int i=n; i>0; i>>=1 ) { // Check the coefficient ai (no need to multiply retVal by 1 if ai is 0) // Note: "i&1" is a bitwise equivalent of "i%2" if ( 0!=(i & static_cast<unsigned int>(1) ) ) { retVal *= factor; } factor *= factor; } return retVal; } <commit_msg>Lib suggested values for default EPS<commit_after>/* Copyright 2011, Jernej Kovacic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @file NumericUtil.cpp * * Implementation of the class NumericUtil, a collection of some useful * numerical utilities. This is a templated class and must not be compiled. * Instead it must be included after the class declaration in the .h file * * @author Jernej Kovacic */ // Deliberately there is no #include "NumericUtil.h" #include "Rational.h" #include "SqMatrixGeneric.h" #include "PolynomialGeneric.h" #include <complex> #include <limits> // Note that the optimal EPS depends on application's requirements // For float, double and long double, a suggested value for EPS can be // obtained by std::numeric_limits<type>::epsilon(). #define _MATH_NUMERICUTIL_SPECIALIZED_EPS(FDL) \ template<> \ FDL math::NumericUtil<FDL>::EPS = std::numeric_limits<FDL>::epsilon(); // end of #define // definition of EPS for float: _MATH_NUMERICUTIL_SPECIALIZED_EPS(float) // double is a more accurate type: _MATH_NUMERICUTIL_SPECIALIZED_EPS(double) // ... and long double is even more accurate: _MATH_NUMERICUTIL_SPECIALIZED_EPS(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_EPS not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_EPS /* * For int and other types, EPS doesn't make sense, so set it to 0 */ template<class T> T math::NumericUtil<T>::EPS = static_cast<T>(0); /** * A constant value with the T's representation of zero (0) */ template<class T> const T math::NumericUtil<T>::ZERO ( static_cast<T>(0) ); /** * A constant value with the T's representation of one (1) */ template<class T> const T math::NumericUtil<T>::ONE ( static_cast<T>(1) ); /** * Does the given value equal (or is close enough to) zero? * Implementation depends on the type T. * For floating point types (float, double, long double), it checks * whether its absolute value is less than a hardcoded constant 'eps'. * * @param value * * @return true or false */ template<class T> bool math::NumericUtil<T>::isZero(const T& value) { /* * The implementation for integers et al. where the == operator * does make sense and no comparison to EPS is necessary. */ bool retVal = ( ZERO==value ? true : false ); return retVal; } /* * Float, double and long double require specialized implementations of isZero(). * In case of these three types, the equality operator (==) is useless. * In numerical mathematics, two numbers are considered "equal", when * absolute value of their difference does not exceed a reasonably set EPS. * All specializations are very similar and only differ in types of an input value. * For easier maintainability, the specialization will be implemented * only once using a parameterized #define */ #define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FDL) \ template<> \ bool math::NumericUtil<FDL>::isZero(const FDL& value) \ { \ bool retVal = false; \ retVal = ( value>-EPS && value<EPS ? true : false ); \ return retVal; \ } // end of #define // derive specialization for float: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float) // ... for double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double) // ... and long double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO /* * Specialization for complex. * As complex is a templated class, again it must be implemented for each supported subtemplated * type. To facilitate this, a parameterized macro is introduced. * Note: norm() calculates a sum of both parts' squares. It is a bit more efficient to compare * it with EPS^2 than calculating its square root (the actual definition of complex abs. value). */ #define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(FDL) \ template<> \ bool math::NumericUtil<std::complex<FDL> >::isZero(const std::complex<FDL>& value) \ { \ bool retVal = false; \ const FDL eps = math::NumericUtil<FDL>::getEPS(); \ retVal = ( std::norm(value)<=eps*eps ? true : false ); \ return retVal; \ } // end of #define // derive specialization for float: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(float) // ... for double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(double) // ... and long double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX /* * Implementation for Rational */ template<> bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value) { // Rational already contains its own isZero()... return value.isZero(); } /** * @return value of 'eps' for the desired type */ template<class T> T math::NumericUtil<T>::getEPS() { return EPS; } /** * Sets the new value of 'eps' for the desired type if the default one does * not meet application's requirements. * * @note There is no check of input so make sure a sensible value * (typically a very small positive number) is entered. * * @param eps - new value of EPS */ template<class T> void math::NumericUtil<T>::setEPS(const T& eps) { EPS = eps; } /* * In C++, it is not possible to specialize a function of a templated class * if the specialization is also a generic type (e.g. T -> math::SqMatrixGeneric<T>). * However it is possible if a single function is templated. * For more details, see the discussion at: * http://www.cplusplus.com/forum/general/68298/ * * At the moment, getUnit() is only used by power(). Until it is changed, * getUnit() will be defined in this file as a templated standalone function. * Additionlly, implementations of the function are "hidden" in the namespace * math::getunit which is not supposed to be known to other members of math:: */ namespace math { namespace getunit { /* * @param t - an arbitrary instance of T, ignored by the generic implementation, * at specializations it might be useful to determine unit's dimensions etc. * * @return an instance of T acting as a multiplication unit */ template<class T> T getUnit(const T& t) { return T(math::NumericUtil<T>::ONE); } /* * Specialization for generic class math::SqMatrixGeneric<T> * * @param t - an arbitrary instance of a square matrix to determine * dimensions of the returned unit matrix * * @return a unit nxn square matrix where n is a dimension of 't' */ template<class T> math::SqMatrixGeneric<T> getUnit(const math::SqMatrixGeneric<T>& t) { const unsigned int N = t.nrRows(); math::SqMatrixGeneric<T> retVal(N); retVal.setUnit(); return retVal; } /* * Specialization for generic class math::PolynomialGeneric<T> * * @param t - ignored * * @return a unit polynomial p(x) = (T)1 */ template<class T> math::PolynomialGeneric<T> getUnit(const math::PolynomialGeneric<T>& t) { math::PolynomialGeneric<T> retVal(1); retVal.set(0, math::NumericUtil<T>::ONE); return retVal; } } // namespace units } // namespace math /** * Efficient calculation of positive integer power. * Complexity of the algorithm is O(log2 n). * * @note T must have implemented operator*= * * @param base - base of the exponentiation * @param n - exponent (a positive integer number) * * @return base^n */ template<class T> T math::NumericUtil<T>::power(const T& base, unsigned int n) { /* * "Exponentiation by squaring" algorithm will be applied. * * Exponentiation can be expanded into: * n n%2 n/2 * a = a * (a^2) * * where / and % are integer division and remainder operators. * * The expression above can be further recursively derived to: * n n%2 (n/2)%2 (n/2)/2 * a = a (a^2) (a^4) = * * n%2 (n/2)%2 (n/4)%2 ((n/2)/2)/2 * = a (a^2) (a^4) (a^8) = .... * * It is simple to develop an iterative algorithm where factor * is iteratively increased by squaring itself and coefficients * ai (i=0..n) are iteratively calculated by the remainder of * division by 2 */ // Note: it is safe to use bitwise operators for arithmetic operations // on unsigned int values as they do not depend on endianess: // http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness T retVal = math::getunit::getUnit(base); T factor = base; // Obtain coefficients ai from the exponent's binary form. // Note: "i>>=1" is a bitwise equivalent bitwise equivalent of "i/=2" for ( unsigned int i=n; i>0; i>>=1 ) { // Check the coefficient ai (no need to multiply retVal by 1 if ai is 0) // Note: "i&1" is a bitwise equivalent of "i%2" if ( 0!=(i & static_cast<unsigned int>(1) ) ) { retVal *= factor; } factor *= factor; } return retVal; } <|endoftext|>
<commit_before>#include <Vertica.h> using Vertica::TransformFunction; using Vertica::TransformFunctionFactory; extern "C" { #include <json/selector.h> #include <json/slice.h> } #include "JsonCopyResult.hpp" template<class D> class AbstractJsonArrayUnnest : public TransformFunction { public: virtual void processPartition(Vertica::ServerInterface &, Vertica::PartitionReader &argReader, Vertica::PartitionWriter &resWriter) { do { const Vertica::VString &jsonSrc = argReader.getStringRef(0); if (jsonSrc.isNull()) { continue; } json_slice_t jsonIn = json_slice_new(jsonSrc.data(), jsonSrc.length()); json_slice_t jsonOut; json_array_iter_t iter; if (json_array_iter_init(&iter, &jsonIn) != JSON_ARRAY_ITER_OK) { continue; } for (;;) { json_array_iter_result_t result; result = json_array_iter_next(&iter, &jsonOut); if (result == JSON_ARRAY_ITER_OK) { D::copyResult(jsonOut, resWriter.getStringRef(0)); resWriter.next(); } else { break; } } } while (argReader.next()); } }; class JsonArrayUnnest : public JsonValueResult, public AbstractJsonArrayUnnest<JsonArrayUnnest> { public: static const char *resultColumnName() { return "JsonArrayUnnest"; } }; class JsonArrayUnnestStrings : public JsonStringResult, public AbstractJsonArrayUnnest<JsonArrayUnnestStrings> { public: static const char *resultColumnName() { return "JsonArrayUnnestStrings"; } }; class JsonArrayUnnestUnquoted : public JsonUnquotedResult, public AbstractJsonArrayUnnest<JsonArrayUnnestUnquoted> { public: static const char *resultColumnName() { return "JsonArrayUnnestUnquoted"; } }; template<class T> class AbstractJsonArrayUnnestFactory : public TransformFunctionFactory { public: virtual void getPrototype(Vertica::ServerInterface &, Vertica::ColumnTypes &argTypes, Vertica::ColumnTypes &resTypes) { argTypes.addVarchar(); resTypes.addVarchar(); } virtual void getReturnType(Vertica::ServerInterface &, const Vertica::SizedColumnTypes &argTypes, Vertica::SizedColumnTypes &resTypes) { const Vertica::VerticaType &jsonSrcType = argTypes.getColumnType(0); resTypes.addVarchar(jsonSrcType.getStringLength(), T::resultColumnName()); } virtual TransformFunction *createTransformFunction(Vertica::ServerInterface &iface) { return vt_createFuncObj(iface.allocator, T); } virtual void getPerInstanceResources(Vertica::ServerInterface &, Vertica::VResources &resources) { resources.nFileHandles = 0; resources.scratchMemory = 0; } }; class JsonArrayUnnestFactory : public AbstractJsonArrayUnnestFactory<JsonArrayUnnest> { }; class JsonArrayUnnestStringsFactory : public AbstractJsonArrayUnnestFactory<JsonArrayUnnestStrings> { }; class JsonArrayUnnestUnquotedFactory : public AbstractJsonArrayUnnestFactory<JsonArrayUnnestUnquoted> { }; RegisterFactory(JsonArrayUnnestFactory); RegisterFactory(JsonArrayUnnestStringsFactory); RegisterFactory(JsonArrayUnnestUnquotedFactory); <commit_msg>Get rid of trailing whitespace.<commit_after>#include <Vertica.h> using Vertica::TransformFunction; using Vertica::TransformFunctionFactory; extern "C" { #include <json/selector.h> #include <json/slice.h> } #include "JsonCopyResult.hpp" template<class D> class AbstractJsonArrayUnnest : public TransformFunction { public: virtual void processPartition(Vertica::ServerInterface &, Vertica::PartitionReader &argReader, Vertica::PartitionWriter &resWriter) { do { const Vertica::VString &jsonSrc = argReader.getStringRef(0); if (jsonSrc.isNull()) { continue; } json_slice_t jsonIn = json_slice_new(jsonSrc.data(), jsonSrc.length()); json_slice_t jsonOut; json_array_iter_t iter; if (json_array_iter_init(&iter, &jsonIn) != JSON_ARRAY_ITER_OK) { continue; } for (;;) { json_array_iter_result_t result; result = json_array_iter_next(&iter, &jsonOut); if (result == JSON_ARRAY_ITER_OK) { D::copyResult(jsonOut, resWriter.getStringRef(0)); resWriter.next(); } else { break; } } } while (argReader.next()); } }; class JsonArrayUnnest : public JsonValueResult, public AbstractJsonArrayUnnest<JsonArrayUnnest> { public: static const char *resultColumnName() { return "JsonArrayUnnest"; } }; class JsonArrayUnnestStrings : public JsonStringResult, public AbstractJsonArrayUnnest<JsonArrayUnnestStrings> { public: static const char *resultColumnName() { return "JsonArrayUnnestStrings"; } }; class JsonArrayUnnestUnquoted : public JsonUnquotedResult, public AbstractJsonArrayUnnest<JsonArrayUnnestUnquoted> { public: static const char *resultColumnName() { return "JsonArrayUnnestUnquoted"; } }; template<class T> class AbstractJsonArrayUnnestFactory : public TransformFunctionFactory { public: virtual void getPrototype(Vertica::ServerInterface &, Vertica::ColumnTypes &argTypes, Vertica::ColumnTypes &resTypes) { argTypes.addVarchar(); resTypes.addVarchar(); } virtual void getReturnType(Vertica::ServerInterface &, const Vertica::SizedColumnTypes &argTypes, Vertica::SizedColumnTypes &resTypes) { const Vertica::VerticaType &jsonSrcType = argTypes.getColumnType(0); resTypes.addVarchar(jsonSrcType.getStringLength(), T::resultColumnName()); } virtual TransformFunction *createTransformFunction(Vertica::ServerInterface &iface) { return vt_createFuncObj(iface.allocator, T); } virtual void getPerInstanceResources(Vertica::ServerInterface &, Vertica::VResources &resources) { resources.nFileHandles = 0; resources.scratchMemory = 0; } }; class JsonArrayUnnestFactory : public AbstractJsonArrayUnnestFactory<JsonArrayUnnest> { }; class JsonArrayUnnestStringsFactory : public AbstractJsonArrayUnnestFactory<JsonArrayUnnestStrings> { }; class JsonArrayUnnestUnquotedFactory : public AbstractJsonArrayUnnestFactory<JsonArrayUnnestUnquoted> { }; RegisterFactory(JsonArrayUnnestFactory); RegisterFactory(JsonArrayUnnestStringsFactory); RegisterFactory(JsonArrayUnnestUnquotedFactory); <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mslangid.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2006-04-07 14:30:38 $ * * 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 2004 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: 2004 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_I18NPOOL_MSLANGID_HXX #define INCLUDED_I18NPOOL_MSLANGID_HXX #ifndef _SAL_CONFIG_H_ #include <sal/config.h> #endif #ifndef INCLUDED_I18NPOOL_DLLAPI_H #include "i18npool/i18npooldllapi.h" #endif #ifndef INCLUDED_I18NPOOL_LANG_H #include "i18npool/lang.h" #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif /** Methods related to Microsoft language IDs. For details about MS-LANGIDs please see lang.h */ class I18NPOOL_DLLPUBLIC MsLangId { public: /// Create a LangID from a primary and a sublanguage. static inline LanguageType makeLangID( LanguageType nSubLangId, LanguageType nPriLangId) { return (nSubLangId << 10) | nPriLangId; } /// Get the primary language of a LangID. static inline LanguageType getPrimaryLanguage( LanguageType nLangID) { return nLangID & LANGUAGE_MASK_PRIMARY; } /// Get the sublanguage of a LangID. static inline LanguageType getSubLanguage( LanguageType nLangID) { return (nLangID & ~LANGUAGE_MASK_PRIMARY) >> 10; } /** Language/locale of category LC_CTYPE (on Unix, else the system language). Evaluation order: LC_ALL, LC_CTYPE, LANG */ static LanguageType getSystemLanguage(); /** Language/locale of category LC_MESSAGES (on Unix, else same as GetSystemLanguage()). Evaluation order: LANGUAGE, LC_ALL, LC_MESSAGES, LANG */ static LanguageType getSystemUILanguage(); /** @short: A proper language/locale if the nLang parameter designates some special value. @descr: NOTE: The "system" values may be overridden by the application's configuration. If you need to access the system values use <method>getRealLanguageWithoutConfig()</method> instead. @returns case LANGUAGE_PROCESS_OR_USER_DEFAULT : configured or system language case LANGUAGE_SYSTEM_DEFAULT : configured or system language case LANGUAGE_SYSTEM : configured or system language case LANGUAGE_NONE : configured or system UI language case LANGUAGE_DONTKNOW : LANGUAGE_ENGLISH_US else: nLang In case the configured language is LANGUAGE_SYSTEM, which is also the initial default, the system language is obtained. In case the configured or resulting system language is LANGUAGE_DONTKNOW, LANGUAGE_ENGLISH_US is returned instead. */ static LanguageType getRealLanguage( LanguageType nLang ); /** @short: Convert a LanguageType to a Locale, resolving LANGUAGE_SYSTEM. @ATTENTION: A round trip convertLanguageToLocale( convertLocaleToLanguage( ...)) is NOT possible because this method substitutes LANGUAGE_SYSTEM and the like. If round-trip is desired, you MUST use convertLanguageToLocale( ..., false) instead. */ static void convertLanguageToLocale( LanguageType nLang, ::com::sun::star::lang::Locale & rLocale ); /** @short: Convert a LanguageType to a Locale with handling of getRealLanguage(). @descr: If bResolveSystem==true don't use to convert a Language to a Locale for file storage because it substitutes LANGUAGE_SYSTEM and LANGUAGE_NONE and similar, use only at runtime! If bResolveSystem==false a LANGUAGE_SYSTEM results in an empty Locale. @ATTENTION: A round trip convertLanguageToLocale( convertLocaleToLanguage( ...)) using the default parameter is NOT possible because this method substitutes LANGUAGE_SYSTEM and the like. If round-trip is desired, you MUST use convertLanguageToLocale( ..., false) instead. */ static ::com::sun::star::lang::Locale convertLanguageToLocale( LanguageType nLang, bool bResolveSystem = true ); /** Convert a Locale to a LanguageType with handling of an empty language name designating the SYSTEM language. */ static LanguageType convertLocaleToLanguage( const ::com::sun::star::lang::Locale & rLocale ); // ----------------------------- // - ConvertLanguageToIsoNames - // ----------------------------- static void convertLanguageToIsoNames( LanguageType nLang, rtl::OUString& rLangStr, rtl::OUString& rCountry ); static void convertLanguageToIsoNames( LanguageType nLang, rtl::OString& rLangStr, rtl::OString& rCountry ); static rtl::OUString convertLanguageToIsoString( LanguageType nLang, sal_Unicode cSep = '-' ); static rtl::OString convertLanguageToIsoByteString( LanguageType nLang, sal_Char cSep = '-' ); // ----------------------------- // - ConvertIsoNamesToLanguage - // ----------------------------- static LanguageType convertIsoNamesToLanguage( const rtl::OUString& rLang, const rtl::OUString& rCountry ); static LanguageType convertIsoNamesToLanguage( const rtl::OString& rLang, const rtl::OString& rCountry ); static LanguageType convertIsoStringToLanguage( const rtl::OUString& rString, sal_Unicode cSep = '-' ); static LanguageType convertIsoByteStringToLanguage( const rtl::OString& rString, sal_Char cSep = '-' ); static LanguageType convertUnxByteStringToLanguage( const rtl::OString& rString ); /** @short: A real language/locale if the nLang parameter designates some special value. @descr: NOTE: This is a raw interface to the system and does not take any application configuration into account. If that is wanted, which is most likely, use <method>getRealLanguage()</method> instead. @returns case LANGUAGE_PROCESS_OR_USER_DEFAULT : getSystemLanguage() case LANGUAGE_SYSTEM_DEFAULT : getSystemLanguage() case LANGUAGE_SYSTEM : getSystemLanguage() case LANGUAGE_NONE : getSystemUILanguage() case LANGUAGE_DONTKNOW : LANGUAGE_ENGLISH_US else: nLang In case getSystemLanguage() or getSystemUILanguage() returned LANGUAGE_DONTKNOW, LANGUAGE_ENGLISH_US is returned instead. */ static LanguageType getRealLanguageWithoutConfig( LanguageType nLang ); /** Whether locale has a Right-To-Left orientation. */ static bool isRightToLeft( LanguageType nLang ); /** Get ::com::sun::star::i18n::ScriptType of locale. */ static sal_Int16 getScriptType( LanguageType nLang ); /** @ATTENTION: these are _ONLY_ to be called by the application's configuration! */ static void setConfiguredSystemLanguage( LanguageType nLang ); static void setConfiguredSystemUILanguage( LanguageType nLang ); // --------------------------------------------------------------------------- /** @internal - Access to fields of an element of the simple conversion table. For resource compiler build environment usage only! */ struct IsoLangEntry { LanguageType mnLang; sal_Char maLangStr[4]; sal_Char maCountry[3]; }; /** @internal - Return a pointer to the IsoLangEntry of the underlying table, matching the offset passed by nIndex. Only meaningful for the resource compiler to build a list of known languages. @returns address of IsoLangEntry, or NULL pointer if nIndex exceeds the table elements' count. */ static const IsoLangEntry* getIsoLangEntry( size_t nIndex ); // --------------------------------------------------------------------------- private: static LanguageType nConfiguredSystemLanguage; static LanguageType nConfiguredSystemUILanguage; static LanguageType getPlatformSystemLanguage(); static LanguageType getPlatformSystemUILanguage(); // Substitute LANGUAGE_SYSTEM for LANGUAGE_SYSTEM_DEFAULT and // LANGUAGE_PROCESS_OR_USER_DEFAULT, other values aren't touched. I18NPOOL_DLLPRIVATE static inline LanguageType simplifySystemLanguages( LanguageType nLang ); }; // static inline LanguageType MsLangId::getSystemLanguage() { return getPlatformSystemLanguage(); } // static inline LanguageType MsLangId::getSystemUILanguage() { return getPlatformSystemUILanguage(); } #endif // INCLUDED_I18NPOOL_MSLANGID_HXX <commit_msg>INTEGRATION: CWS locales203 (1.2.2); FILE MERGED 2006/04/20 16:52:12 er 1.2.2.2: #i61058# new: hasForbiddenCharacters(), getReplacementForObsoleteLanguage() 2006/04/12 17:31:13 er 1.2.2.1: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mslangid.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2006-05-04 09:10:57 $ * * 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 INCLUDED_I18NPOOL_MSLANGID_HXX #define INCLUDED_I18NPOOL_MSLANGID_HXX #ifndef _SAL_CONFIG_H_ #include <sal/config.h> #endif #ifndef INCLUDED_I18NPOOL_DLLAPI_H #include "i18npool/i18npooldllapi.h" #endif #ifndef INCLUDED_I18NPOOL_LANG_H #include "i18npool/lang.h" #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif /** Methods related to Microsoft language IDs. For details about MS-LANGIDs please see lang.h */ class I18NPOOL_DLLPUBLIC MsLangId { public: /// Create a LangID from a primary and a sublanguage. static inline LanguageType makeLangID( LanguageType nSubLangId, LanguageType nPriLangId) { return (nSubLangId << 10) | nPriLangId; } /// Get the primary language of a LangID. static inline LanguageType getPrimaryLanguage( LanguageType nLangID) { return nLangID & LANGUAGE_MASK_PRIMARY; } /// Get the sublanguage of a LangID. static inline LanguageType getSubLanguage( LanguageType nLangID) { return (nLangID & ~LANGUAGE_MASK_PRIMARY) >> 10; } /** Language/locale of category LC_CTYPE (on Unix, else the system language). Evaluation order: LC_ALL, LC_CTYPE, LANG */ static LanguageType getSystemLanguage(); /** Language/locale of category LC_MESSAGES (on Unix, else same as GetSystemLanguage()). Evaluation order: LANGUAGE, LC_ALL, LC_MESSAGES, LANG */ static LanguageType getSystemUILanguage(); /** @short: A proper language/locale if the nLang parameter designates some special value. @descr: NOTE: The "system" values may be overridden by the application's configuration. If you need to access the system values use <method>getRealLanguageWithoutConfig()</method> instead. @returns case LANGUAGE_PROCESS_OR_USER_DEFAULT : configured or system language case LANGUAGE_SYSTEM_DEFAULT : configured or system language case LANGUAGE_SYSTEM : configured or system language case LANGUAGE_NONE : configured or system UI language case LANGUAGE_DONTKNOW : LANGUAGE_ENGLISH_US else: nLang In case the configured language is LANGUAGE_SYSTEM, which is also the initial default, the system language is obtained. In case the configured or resulting system language is LANGUAGE_DONTKNOW, LANGUAGE_ENGLISH_US is returned instead. */ static LanguageType getRealLanguage( LanguageType nLang ); /** @short: Convert a LanguageType to a Locale, resolving LANGUAGE_SYSTEM. @ATTENTION: A round trip convertLanguageToLocale( convertLocaleToLanguage( ...)) is NOT possible because this method substitutes LANGUAGE_SYSTEM and the like. If round-trip is desired, you MUST use convertLanguageToLocale( ..., false) instead. */ static void convertLanguageToLocale( LanguageType nLang, ::com::sun::star::lang::Locale & rLocale ); /** @short: Convert a LanguageType to a Locale with handling of getRealLanguage(). @descr: If bResolveSystem==true don't use to convert a Language to a Locale for file storage because it substitutes LANGUAGE_SYSTEM and LANGUAGE_NONE and similar, use only at runtime! If bResolveSystem==false a LANGUAGE_SYSTEM results in an empty Locale. @ATTENTION: A round trip convertLanguageToLocale( convertLocaleToLanguage( ...)) using the default parameter is NOT possible because this method substitutes LANGUAGE_SYSTEM and the like. If round-trip is desired, you MUST use convertLanguageToLocale( ..., false) instead. */ static ::com::sun::star::lang::Locale convertLanguageToLocale( LanguageType nLang, bool bResolveSystem = true ); /** Convert a Locale to a LanguageType with handling of an empty language name designating the SYSTEM language. */ static LanguageType convertLocaleToLanguage( const ::com::sun::star::lang::Locale & rLocale ); // ----------------------------- // - ConvertLanguageToIsoNames - // ----------------------------- static void convertLanguageToIsoNames( LanguageType nLang, rtl::OUString& rLangStr, rtl::OUString& rCountry ); static void convertLanguageToIsoNames( LanguageType nLang, rtl::OString& rLangStr, rtl::OString& rCountry ); static rtl::OUString convertLanguageToIsoString( LanguageType nLang, sal_Unicode cSep = '-' ); static rtl::OString convertLanguageToIsoByteString( LanguageType nLang, sal_Char cSep = '-' ); // ----------------------------- // - ConvertIsoNamesToLanguage - // ----------------------------- static LanguageType convertIsoNamesToLanguage( const rtl::OUString& rLang, const rtl::OUString& rCountry ); static LanguageType convertIsoNamesToLanguage( const rtl::OString& rLang, const rtl::OString& rCountry ); static LanguageType convertIsoStringToLanguage( const rtl::OUString& rString, sal_Unicode cSep = '-' ); static LanguageType convertIsoByteStringToLanguage( const rtl::OString& rString, sal_Char cSep = '-' ); static LanguageType convertUnxByteStringToLanguage( const rtl::OString& rString ); /** @short: A real language/locale if the nLang parameter designates some special value. @descr: NOTE: This is a raw interface to the system and does not take any application configuration into account. If that is wanted, which is most likely, use <method>getRealLanguage()</method> instead. @returns case LANGUAGE_PROCESS_OR_USER_DEFAULT : getSystemLanguage() case LANGUAGE_SYSTEM_DEFAULT : getSystemLanguage() case LANGUAGE_SYSTEM : getSystemLanguage() case LANGUAGE_NONE : getSystemUILanguage() case LANGUAGE_DONTKNOW : LANGUAGE_ENGLISH_US else: nLang In case getSystemLanguage() or getSystemUILanguage() returned LANGUAGE_DONTKNOW, LANGUAGE_ENGLISH_US is returned instead. */ static LanguageType getRealLanguageWithoutConfig( LanguageType nLang ); /** Whether locale has a Right-To-Left orientation. */ static bool isRightToLeft( LanguageType nLang ); /** Whether there are "forbidden characters at start or end of line" in this locale. CJK locales. @see offapi/com/sun/star/i18n/ForbiddenCharacters.idl */ static bool hasForbiddenCharacters( LanguageType nLang ); /** Get ::com::sun::star::i18n::ScriptType of locale. */ static sal_Int16 getScriptType( LanguageType nLang ); /** Map an obsolete user defined LANGID (see lang.h LANGUAGE_OBSOLETE_USER_...) to the new value defined by MS in the meantime. */ static LanguageType getReplacementForObsoleteLanguage( LanguageType nLang ); /** @ATTENTION: these are _ONLY_ to be called by the application's configuration! */ static void setConfiguredSystemLanguage( LanguageType nLang ); static void setConfiguredSystemUILanguage( LanguageType nLang ); // --------------------------------------------------------------------------- /** @internal - Access to fields of an element of the simple conversion table. For resource compiler build environment usage only! */ struct IsoLangEntry { LanguageType mnLang; sal_Char maLangStr[4]; sal_Char maCountry[3]; }; /** @internal - Return a pointer to the IsoLangEntry of the underlying table, matching the offset passed by nIndex. Only meaningful for the resource compiler to build a list of known languages. @returns address of IsoLangEntry, or NULL pointer if nIndex exceeds the table elements' count. */ static const IsoLangEntry* getIsoLangEntry( size_t nIndex ); // --------------------------------------------------------------------------- private: static LanguageType nConfiguredSystemLanguage; static LanguageType nConfiguredSystemUILanguage; static LanguageType getPlatformSystemLanguage(); static LanguageType getPlatformSystemUILanguage(); // Substitute LANGUAGE_SYSTEM for LANGUAGE_SYSTEM_DEFAULT and // LANGUAGE_PROCESS_OR_USER_DEFAULT, other values aren't touched. I18NPOOL_DLLPRIVATE static inline LanguageType simplifySystemLanguages( LanguageType nLang ); }; // static inline LanguageType MsLangId::getSystemLanguage() { return getPlatformSystemLanguage(); } // static inline LanguageType MsLangId::getSystemUILanguage() { return getPlatformSystemUILanguage(); } #endif // INCLUDED_I18NPOOL_MSLANGID_HXX <|endoftext|>
<commit_before>#include "MQTTClient.h" void messageArrived(MQTT::MessageData& messageData) { MQTT::Message &message = messageData.message; // null terminate topic to create String object int len = messageData.topicName.lenstring.len; char topic[len+1]; memcpy(topic, messageData.topicName.lenstring.data, (size_t)len); topic[len] = '\0'; // null terminate payload char * payload = (char *)message.payload; payload[message.payloadlen] = '\0'; messageReceived(String(topic), String(payload), (char*)message.payload, (unsigned int)message.payloadlen); } MQTTClient::MQTTClient() {} boolean MQTTClient::begin(const char * hostname, Client& client) { return this->begin(hostname, 1883, client); } boolean MQTTClient::begin(const char * _hostname, int _port, Client& _client) { this->client = new MQTT::Client<Network, Timer, MQTT_BUFFER_SIZE, 0>(this->network); this->network.setClient(&_client); this->client->setDefaultMessageHandler(messageArrived); this->hostname = _hostname; this->port = _port; this->options = MQTTPacket_connectData_initializer; return true; } void MQTTClient::setWill(const char * topic) { this->setWill(topic, ""); } void MQTTClient::setWill(const char * topic, const char * payload) { this->options.willFlag = 0x1; this->options.will.topicName.cstring = (char*)topic; this->options.will.message.cstring = (char*)payload; } boolean MQTTClient::connect(const char * clientId) { return this->connect(clientId, NULL, NULL); } boolean MQTTClient::connect(const char * clientId, const char * username, const char * password) { if(!this->network.connect((char*)this->hostname, this->port)) { return false; } this->options.clientID.cstring = (char*)clientId; if(username && password) { this->options.username.cstring = (char*)username; this->options.password.cstring = (char*)password; } return this->client->connect(this->options) == MQTT::SUCCESS; } boolean MQTTClient::publish(String topic) { return this->publish(topic.c_str(), ""); } boolean MQTTClient::publish(String topic, String payload) { return this->publish(topic.c_str(), payload.c_str()); } boolean MQTTClient::publish(const char * topic, String payload) { return this->publish(topic, payload.c_str()); } boolean MQTTClient::publish(const char * topic, const char * payload) { return this->publish(topic, (char*)payload, (unsigned int)strlen(payload)); } boolean MQTTClient::publish(const char * topic, char * payload, unsigned int length) { MQTT::Message message; message.qos = MQTT::QOS0; message.retained = false; message.dup = false; message.payload = payload; message.payloadlen = length; return client->publish(topic, message) == MQTT::SUCCESS; } boolean MQTTClient::publish(MQTTMessage * message) { MQTT::Message _message; _message.qos = MQTT::QOS0; _message.retained = message->retained; _message.dup = false; _message.payload = message->payload; _message.payloadlen = message->length; return client->publish(message->topic, _message) == MQTT::SUCCESS; } boolean MQTTClient::subscribe(String topic) { return this->subscribe(topic.c_str()); } boolean MQTTClient::subscribe(const char * topic) { return client->subscribe(topic, MQTT::QOS0, NULL) == MQTT::SUCCESS; } boolean MQTTClient::unsubscribe(String topic) { return this->unsubscribe(topic.c_str()); } boolean MQTTClient::unsubscribe(const char * topic) { return client->unsubscribe(topic) == MQTT::SUCCESS; } void MQTTClient::loop() { if(!this->network.connected() && this->client->isConnected()) { // the following call will not send a packet but reset the instance // to allow proper reconnection this->client->disconnect(); } this->client->yield(); } boolean MQTTClient::connected() { return this->client->isConnected(); } boolean MQTTClient::disconnect() { return this->client->disconnect() == MQTT::SUCCESS; } <commit_msg>renamed handler function<commit_after>#include "MQTTClient.h" void MQTTClient_messageHandler(MQTT::MessageData &messageData) { MQTT::Message &message = messageData.message; // null terminate topic to create String object int len = messageData.topicName.lenstring.len; char topic[len+1]; memcpy(topic, messageData.topicName.lenstring.data, (size_t)len); topic[len] = '\0'; // null terminate payload char * payload = (char *)message.payload; payload[message.payloadlen] = '\0'; messageReceived(String(topic), String(payload), (char*)message.payload, (unsigned int)message.payloadlen); } MQTTClient::MQTTClient() {} boolean MQTTClient::begin(const char * hostname, Client& client) { return this->begin(hostname, 1883, client); } boolean MQTTClient::begin(const char * _hostname, int _port, Client& _client) { this->client = new MQTT::Client<Network, Timer, MQTT_BUFFER_SIZE, 0>(this->network); this->network.setClient(&_client); this->client->setDefaultMessageHandler(MQTTClient_messageHandler); this->hostname = _hostname; this->port = _port; this->options = MQTTPacket_connectData_initializer; return true; } void MQTTClient::setWill(const char * topic) { this->setWill(topic, ""); } void MQTTClient::setWill(const char * topic, const char * payload) { this->options.willFlag = 0x1; this->options.will.topicName.cstring = (char*)topic; this->options.will.message.cstring = (char*)payload; } boolean MQTTClient::connect(const char * clientId) { return this->connect(clientId, NULL, NULL); } boolean MQTTClient::connect(const char * clientId, const char * username, const char * password) { if(!this->network.connect((char*)this->hostname, this->port)) { return false; } this->options.clientID.cstring = (char*)clientId; if(username && password) { this->options.username.cstring = (char*)username; this->options.password.cstring = (char*)password; } return this->client->connect(this->options) == MQTT::SUCCESS; } boolean MQTTClient::publish(String topic) { return this->publish(topic.c_str(), ""); } boolean MQTTClient::publish(String topic, String payload) { return this->publish(topic.c_str(), payload.c_str()); } boolean MQTTClient::publish(const char * topic, String payload) { return this->publish(topic, payload.c_str()); } boolean MQTTClient::publish(const char * topic, const char * payload) { return this->publish(topic, (char*)payload, (unsigned int)strlen(payload)); } boolean MQTTClient::publish(const char * topic, char * payload, unsigned int length) { MQTT::Message message; message.qos = MQTT::QOS0; message.retained = false; message.dup = false; message.payload = payload; message.payloadlen = length; return client->publish(topic, message) == MQTT::SUCCESS; } boolean MQTTClient::publish(MQTTMessage * message) { MQTT::Message _message; _message.qos = MQTT::QOS0; _message.retained = message->retained; _message.dup = false; _message.payload = message->payload; _message.payloadlen = message->length; return client->publish(message->topic, _message) == MQTT::SUCCESS; } boolean MQTTClient::subscribe(String topic) { return this->subscribe(topic.c_str()); } boolean MQTTClient::subscribe(const char * topic) { return client->subscribe(topic, MQTT::QOS0, NULL) == MQTT::SUCCESS; } boolean MQTTClient::unsubscribe(String topic) { return this->unsubscribe(topic.c_str()); } boolean MQTTClient::unsubscribe(const char * topic) { return client->unsubscribe(topic) == MQTT::SUCCESS; } void MQTTClient::loop() { if(!this->network.connected() && this->client->isConnected()) { // the following call will not send a packet but reset the instance // to allow proper reconnection this->client->disconnect(); } this->client->yield(); } boolean MQTTClient::connected() { return this->client->isConnected(); } boolean MQTTClient::disconnect() { return this->client->disconnect() == MQTT::SUCCESS; } <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2018-2019 Baldur Karlsson * * 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 "d3d_helpers.h" #include <vector> #include "../test_common.h" std::string D3DFullscreenQuadVertex = R"EOSHADER( float4 main(uint vid : SV_VertexID) : SV_POSITION { float2 positions[] = { float2(-1.0f, 1.0f), float2( 1.0f, 1.0f), float2(-1.0f, -1.0f), float2( 1.0f, -1.0f), }; return float4(positions[vid], 0, 1); } )EOSHADER"; std::string D3DDefaultVertex = R"EOSHADER( struct vertin { float3 pos : POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; struct v2f { float4 pos : SV_POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; v2f main(vertin IN, uint vid : SV_VertexID) { v2f OUT = (v2f)0; OUT.pos = float4(IN.pos.xyz, 1); OUT.col = IN.col; OUT.uv = IN.uv; return OUT; } )EOSHADER"; std::string D3DDefaultPixel = R"EOSHADER( struct v2f { float4 pos : SV_POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; float4 main(v2f IN) : SV_Target0 { return IN.col; } )EOSHADER"; IDXGIAdapterPtr ChooseD3DAdapter(IDXGIFactoryPtr factory, int argc, char **argv, bool &warp) { struct AdapterInfo { IDXGIAdapterPtr adapter; DXGI_ADAPTER_DESC desc; }; std::vector<AdapterInfo> adapters; HRESULT hr = S_OK; for(UINT i = 0; i < 10; i++) { IDXGIAdapterPtr a; hr = factory->EnumAdapters(i, &a); if(hr == S_OK && a) { DXGI_ADAPTER_DESC desc; a->GetDesc(&desc); adapters.push_back({a, desc}); } else { break; } } IDXGIAdapterPtr adapter = NULL; for(int i = 0; i < argc; i++) { if(!strcmp(argv[i], "--warp")) { warp = true; adapter = NULL; break; } if(!strcmp(argv[i], "--gpu") && i + 1 < argc) { std::string needle = strlower(argv[i + 1]); if(needle == "warp") { adapter = warp; break; } const bool nv = (needle == "nv" || needle == "nvidia"); const bool amd = (needle == "amd"); const bool intel = (needle == "intel"); for(size_t a = 0; a < adapters.size(); a++) { std::string haystack = strlower(Wide2UTF8(adapters[a].desc.Description)); if(haystack.find(needle) != std::string::npos || (nv && adapters[a].desc.VendorId == 0x10DE) || (amd && adapters[a].desc.VendorId == 0x1002) || (intel && adapters[a].desc.VendorId == 0x8086)) { adapter = adapters[a].adapter; break; } } break; } } return adapter; } <commit_msg>Fix '--gpu warp' specifier in tests<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2018-2019 Baldur Karlsson * * 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 "d3d_helpers.h" #include <vector> #include "../test_common.h" std::string D3DFullscreenQuadVertex = R"EOSHADER( float4 main(uint vid : SV_VertexID) : SV_POSITION { float2 positions[] = { float2(-1.0f, 1.0f), float2( 1.0f, 1.0f), float2(-1.0f, -1.0f), float2( 1.0f, -1.0f), }; return float4(positions[vid], 0, 1); } )EOSHADER"; std::string D3DDefaultVertex = R"EOSHADER( struct vertin { float3 pos : POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; struct v2f { float4 pos : SV_POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; v2f main(vertin IN, uint vid : SV_VertexID) { v2f OUT = (v2f)0; OUT.pos = float4(IN.pos.xyz, 1); OUT.col = IN.col; OUT.uv = IN.uv; return OUT; } )EOSHADER"; std::string D3DDefaultPixel = R"EOSHADER( struct v2f { float4 pos : SV_POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; float4 main(v2f IN) : SV_Target0 { return IN.col; } )EOSHADER"; IDXGIAdapterPtr ChooseD3DAdapter(IDXGIFactoryPtr factory, int argc, char **argv, bool &warp) { struct AdapterInfo { IDXGIAdapterPtr adapter; DXGI_ADAPTER_DESC desc; }; std::vector<AdapterInfo> adapters; HRESULT hr = S_OK; for(UINT i = 0; i < 10; i++) { IDXGIAdapterPtr a; hr = factory->EnumAdapters(i, &a); if(hr == S_OK && a) { DXGI_ADAPTER_DESC desc; a->GetDesc(&desc); adapters.push_back({a, desc}); } else { break; } } IDXGIAdapterPtr adapter = NULL; for(int i = 0; i < argc; i++) { if(!strcmp(argv[i], "--warp")) { warp = true; adapter = NULL; break; } if(!strcmp(argv[i], "--gpu") && i + 1 < argc) { std::string needle = strlower(argv[i + 1]); if(needle == "warp") { warp = true; adapter = NULL; break; } const bool nv = (needle == "nv" || needle == "nvidia"); const bool amd = (needle == "amd"); const bool intel = (needle == "intel"); for(size_t a = 0; a < adapters.size(); a++) { std::string haystack = strlower(Wide2UTF8(adapters[a].desc.Description)); if(haystack.find(needle) != std::string::npos || (nv && adapters[a].desc.VendorId == 0x10DE) || (amd && adapters[a].desc.VendorId == 0x1002) || (intel && adapters[a].desc.VendorId == 0x8086)) { adapter = adapters[a].adapter; break; } } break; } } return adapter; } <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "net/proxy/dhcp_proxy_script_fetcher_win.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram.h" #include "base/perftimer.h" #include "base/threading/worker_pool.h" #include "net/base/net_errors.h" #include "net/proxy/dhcp_proxy_script_adapter_fetcher_win.h" #include <winsock2.h> #include <iphlpapi.h> #pragma comment(lib, "iphlpapi.lib") namespace { // How long to wait at maximum after we get results (a PAC file or // knowledge that no PAC file is configured) from whichever network // adapter finishes first. const int kMaxWaitAfterFirstResultMs = 400; const int kGetAdaptersAddressesErrors[] = { ERROR_ADDRESS_NOT_ASSOCIATED, ERROR_BUFFER_OVERFLOW, ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_NO_DATA, }; } // namespace namespace net { DhcpProxyScriptFetcherWin::DhcpProxyScriptFetcherWin( URLRequestContext* url_request_context) : state_(STATE_START), num_pending_fetchers_(0), url_request_context_(url_request_context) { DCHECK(url_request_context_); } DhcpProxyScriptFetcherWin::~DhcpProxyScriptFetcherWin() { // Count as user-initiated if we are not yet in STATE_DONE. Cancel(); // The WeakPtr we passed to the worker thread may be destroyed on the // worker thread. This detaches any outstanding WeakPtr state from // the current thread. base::SupportsWeakPtr<DhcpProxyScriptFetcherWin>::DetachFromThread(); } int DhcpProxyScriptFetcherWin::Fetch(string16* utf16_text, const CompletionCallback& callback) { DCHECK(CalledOnValidThread()); if (state_ != STATE_START && state_ != STATE_DONE) { NOTREACHED(); return ERR_UNEXPECTED; } fetch_start_time_ = base::TimeTicks::Now(); state_ = STATE_WAIT_ADAPTERS; callback_ = callback; destination_string_ = utf16_text; last_query_ = ImplCreateAdapterQuery(); base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind( &DhcpProxyScriptFetcherWin::AdapterQuery::GetCandidateAdapterNames, last_query_.get()), base::Bind( &DhcpProxyScriptFetcherWin::OnGetCandidateAdapterNamesDone, AsWeakPtr(), last_query_), true); return ERR_IO_PENDING; } void DhcpProxyScriptFetcherWin::Cancel() { DCHECK(CalledOnValidThread()); if (state_ != STATE_DONE) { // We only count this stat if the cancel was explicitly initiated by // our client, and if we weren't already in STATE_DONE. UMA_HISTOGRAM_TIMES("Net.DhcpWpadCancelTime", base::TimeTicks::Now() - fetch_start_time_); } CancelImpl(); } void DhcpProxyScriptFetcherWin::CancelImpl() { DCHECK(CalledOnValidThread()); if (state_ != STATE_DONE) { callback_.Reset(); wait_timer_.Stop(); state_ = STATE_DONE; for (FetcherVector::iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { (*it)->Cancel(); } fetchers_.reset(); } } void DhcpProxyScriptFetcherWin::OnGetCandidateAdapterNamesDone( scoped_refptr<AdapterQuery> query) { DCHECK(CalledOnValidThread()); // This can happen if this object is reused for multiple queries, // and a previous query was cancelled before it completed. if (query.get() != last_query_.get()) return; last_query_ = NULL; // Enable unit tests to wait for this to happen; in production this function // call is a no-op. ImplOnGetCandidateAdapterNamesDone(); // We may have been cancelled. if (state_ != STATE_WAIT_ADAPTERS) return; state_ = STATE_NO_RESULTS; const std::set<std::string>& adapter_names = query->adapter_names(); if (adapter_names.empty()) { TransitionToDone(); return; } for (std::set<std::string>::const_iterator it = adapter_names.begin(); it != adapter_names.end(); ++it) { DhcpProxyScriptAdapterFetcher* fetcher(ImplCreateAdapterFetcher()); fetcher->Fetch( *it, base::Bind(&DhcpProxyScriptFetcherWin::OnFetcherDone, base::Unretained(this))); fetchers_.push_back(fetcher); } num_pending_fetchers_ = fetchers_.size(); } std::string DhcpProxyScriptFetcherWin::GetFetcherName() const { DCHECK(CalledOnValidThread()); return "win"; } const GURL& DhcpProxyScriptFetcherWin::GetPacURL() const { DCHECK(CalledOnValidThread()); DCHECK_EQ(state_, STATE_DONE); return pac_url_; } void DhcpProxyScriptFetcherWin::OnFetcherDone(int result) { DCHECK(state_ == STATE_NO_RESULTS || state_ == STATE_SOME_RESULTS); if (--num_pending_fetchers_ == 0) { TransitionToDone(); return; } // If the only pending adapters are those less preferred than one // with a valid PAC script, we do not need to wait any longer. for (FetcherVector::iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { bool did_finish = (*it)->DidFinish(); int result = (*it)->GetResult(); if (did_finish && result == OK) { TransitionToDone(); return; } if (!did_finish || result != ERR_PAC_NOT_IN_DHCP) { break; } } // Once we have a single result, we set a maximum on how long to wait // for the rest of the results. if (state_ == STATE_NO_RESULTS) { state_ = STATE_SOME_RESULTS; wait_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(ImplGetMaxWaitMs()), this, &DhcpProxyScriptFetcherWin::OnWaitTimer); } } void DhcpProxyScriptFetcherWin::OnWaitTimer() { DCHECK_EQ(state_, STATE_SOME_RESULTS); // These are intended to help us understand whether our timeout may // be too aggressive or not aggressive enough. UMA_HISTOGRAM_COUNTS_100("Net.DhcpWpadNumAdaptersAtWaitTimer", fetchers_.size()); UMA_HISTOGRAM_COUNTS_100("Net.DhcpWpadNumPendingAdaptersAtWaitTimer", num_pending_fetchers_); TransitionToDone(); } void DhcpProxyScriptFetcherWin::TransitionToDone() { DCHECK(state_ == STATE_NO_RESULTS || state_ == STATE_SOME_RESULTS); int result = ERR_PAC_NOT_IN_DHCP; // Default if no fetchers. if (!fetchers_.empty()) { // Scan twice for the result; once through the whole list for success, // then if no success, return result for most preferred network adapter, // preferring "real" network errors to the ERR_PAC_NOT_IN_DHCP error. // Default to ERR_ABORTED if no fetcher completed. result = ERR_ABORTED; for (FetcherVector::iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { if ((*it)->DidFinish() && (*it)->GetResult() == OK) { result = OK; *destination_string_ = (*it)->GetPacScript(); pac_url_ = (*it)->GetPacURL(); break; } } if (result != OK) { destination_string_->clear(); for (FetcherVector::iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { if ((*it)->DidFinish()) { result = (*it)->GetResult(); if (result != ERR_PAC_NOT_IN_DHCP) { break; } } } } } CompletionCallback callback = callback_; CancelImpl(); DCHECK_EQ(state_, STATE_DONE); DCHECK(fetchers_.empty()); DCHECK(callback_.is_null()); // Invariant of data. UMA_HISTOGRAM_TIMES("Net.DhcpWpadCompletionTime", base::TimeTicks::Now() - fetch_start_time_); if (result != OK) { UMA_HISTOGRAM_CUSTOM_ENUMERATION( "Net.DhcpWpadFetchError", std::abs(result), GetAllErrorCodesForUma()); } // We may be deleted re-entrantly within this outcall. callback.Run(result); } int DhcpProxyScriptFetcherWin::num_pending_fetchers() const { return num_pending_fetchers_; } URLRequestContext* DhcpProxyScriptFetcherWin::url_request_context() const { return url_request_context_; } DhcpProxyScriptAdapterFetcher* DhcpProxyScriptFetcherWin::ImplCreateAdapterFetcher() { return new DhcpProxyScriptAdapterFetcher(url_request_context_); } DhcpProxyScriptFetcherWin::AdapterQuery* DhcpProxyScriptFetcherWin::ImplCreateAdapterQuery() { return new AdapterQuery(); } int DhcpProxyScriptFetcherWin::ImplGetMaxWaitMs() { return kMaxWaitAfterFirstResultMs; } bool DhcpProxyScriptFetcherWin::GetCandidateAdapterNames( std::set<std::string>* adapter_names) { DCHECK(adapter_names); adapter_names->clear(); // The GetAdaptersAddresses MSDN page recommends using a size of 15000 to // avoid reallocation. ULONG adapters_size = 15000; scoped_ptr_malloc<IP_ADAPTER_ADDRESSES> adapters; ULONG error = ERROR_SUCCESS; int num_tries = 0; PerfTimer time_api_access; do { adapters.reset( reinterpret_cast<IP_ADAPTER_ADDRESSES*>(malloc(adapters_size))); // Return only unicast addresses, and skip information we do not need. error = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, adapters.get(), &adapters_size); ++num_tries; } while (error == ERROR_BUFFER_OVERFLOW && num_tries <= 3); // This is primarily to validate our belief that the GetAdaptersAddresses API // function is fast enough to call synchronously from the network thread. UMA_HISTOGRAM_TIMES("Net.DhcpWpadGetAdaptersAddressesTime", time_api_access.Elapsed()); if (error != ERROR_SUCCESS) { UMA_HISTOGRAM_CUSTOM_ENUMERATION( "Net.DhcpWpadGetAdaptersAddressesError", error, base::CustomHistogram::ArrayToCustomRanges( kGetAdaptersAddressesErrors, arraysize(kGetAdaptersAddressesErrors))); } if (error == ERROR_NO_DATA) { // There are no adapters that we care about. return true; } if (error != ERROR_SUCCESS) { LOG(WARNING) << "Unexpected error retrieving WPAD configuration from DHCP."; return false; } IP_ADAPTER_ADDRESSES* adapter = NULL; for (adapter = adapters.get(); adapter; adapter = adapter->Next) { if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue; if ((adapter->Flags & IP_ADAPTER_DHCP_ENABLED) == 0) continue; DCHECK(adapter->AdapterName); adapter_names->insert(adapter->AdapterName); } return true; } DhcpProxyScriptFetcherWin::AdapterQuery::AdapterQuery() { } DhcpProxyScriptFetcherWin::AdapterQuery::~AdapterQuery() { } void DhcpProxyScriptFetcherWin::AdapterQuery::GetCandidateAdapterNames() { ImplGetCandidateAdapterNames(&adapter_names_); } const std::set<std::string>& DhcpProxyScriptFetcherWin::AdapterQuery::adapter_names() const { return adapter_names_; } bool DhcpProxyScriptFetcherWin::AdapterQuery::ImplGetCandidateAdapterNames( std::set<std::string>* adapter_names) { return DhcpProxyScriptFetcherWin::GetCandidateAdapterNames(adapter_names); } } // namespace net <commit_msg>[Coverity] Fixed uninitialized member<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 "net/proxy/dhcp_proxy_script_fetcher_win.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram.h" #include "base/perftimer.h" #include "base/threading/worker_pool.h" #include "net/base/net_errors.h" #include "net/proxy/dhcp_proxy_script_adapter_fetcher_win.h" #include <winsock2.h> #include <iphlpapi.h> #pragma comment(lib, "iphlpapi.lib") namespace { // How long to wait at maximum after we get results (a PAC file or // knowledge that no PAC file is configured) from whichever network // adapter finishes first. const int kMaxWaitAfterFirstResultMs = 400; const int kGetAdaptersAddressesErrors[] = { ERROR_ADDRESS_NOT_ASSOCIATED, ERROR_BUFFER_OVERFLOW, ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_NO_DATA, }; } // namespace namespace net { DhcpProxyScriptFetcherWin::DhcpProxyScriptFetcherWin( URLRequestContext* url_request_context) : state_(STATE_START), num_pending_fetchers_(0), destination_string_(NULL), url_request_context_(url_request_context) { DCHECK(url_request_context_); } DhcpProxyScriptFetcherWin::~DhcpProxyScriptFetcherWin() { // Count as user-initiated if we are not yet in STATE_DONE. Cancel(); // The WeakPtr we passed to the worker thread may be destroyed on the // worker thread. This detaches any outstanding WeakPtr state from // the current thread. base::SupportsWeakPtr<DhcpProxyScriptFetcherWin>::DetachFromThread(); } int DhcpProxyScriptFetcherWin::Fetch(string16* utf16_text, const CompletionCallback& callback) { DCHECK(CalledOnValidThread()); if (state_ != STATE_START && state_ != STATE_DONE) { NOTREACHED(); return ERR_UNEXPECTED; } fetch_start_time_ = base::TimeTicks::Now(); state_ = STATE_WAIT_ADAPTERS; callback_ = callback; destination_string_ = utf16_text; last_query_ = ImplCreateAdapterQuery(); base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind( &DhcpProxyScriptFetcherWin::AdapterQuery::GetCandidateAdapterNames, last_query_.get()), base::Bind( &DhcpProxyScriptFetcherWin::OnGetCandidateAdapterNamesDone, AsWeakPtr(), last_query_), true); return ERR_IO_PENDING; } void DhcpProxyScriptFetcherWin::Cancel() { DCHECK(CalledOnValidThread()); if (state_ != STATE_DONE) { // We only count this stat if the cancel was explicitly initiated by // our client, and if we weren't already in STATE_DONE. UMA_HISTOGRAM_TIMES("Net.DhcpWpadCancelTime", base::TimeTicks::Now() - fetch_start_time_); } CancelImpl(); } void DhcpProxyScriptFetcherWin::CancelImpl() { DCHECK(CalledOnValidThread()); if (state_ != STATE_DONE) { callback_.Reset(); wait_timer_.Stop(); state_ = STATE_DONE; for (FetcherVector::iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { (*it)->Cancel(); } fetchers_.reset(); } } void DhcpProxyScriptFetcherWin::OnGetCandidateAdapterNamesDone( scoped_refptr<AdapterQuery> query) { DCHECK(CalledOnValidThread()); // This can happen if this object is reused for multiple queries, // and a previous query was cancelled before it completed. if (query.get() != last_query_.get()) return; last_query_ = NULL; // Enable unit tests to wait for this to happen; in production this function // call is a no-op. ImplOnGetCandidateAdapterNamesDone(); // We may have been cancelled. if (state_ != STATE_WAIT_ADAPTERS) return; state_ = STATE_NO_RESULTS; const std::set<std::string>& adapter_names = query->adapter_names(); if (adapter_names.empty()) { TransitionToDone(); return; } for (std::set<std::string>::const_iterator it = adapter_names.begin(); it != adapter_names.end(); ++it) { DhcpProxyScriptAdapterFetcher* fetcher(ImplCreateAdapterFetcher()); fetcher->Fetch( *it, base::Bind(&DhcpProxyScriptFetcherWin::OnFetcherDone, base::Unretained(this))); fetchers_.push_back(fetcher); } num_pending_fetchers_ = fetchers_.size(); } std::string DhcpProxyScriptFetcherWin::GetFetcherName() const { DCHECK(CalledOnValidThread()); return "win"; } const GURL& DhcpProxyScriptFetcherWin::GetPacURL() const { DCHECK(CalledOnValidThread()); DCHECK_EQ(state_, STATE_DONE); return pac_url_; } void DhcpProxyScriptFetcherWin::OnFetcherDone(int result) { DCHECK(state_ == STATE_NO_RESULTS || state_ == STATE_SOME_RESULTS); if (--num_pending_fetchers_ == 0) { TransitionToDone(); return; } // If the only pending adapters are those less preferred than one // with a valid PAC script, we do not need to wait any longer. for (FetcherVector::iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { bool did_finish = (*it)->DidFinish(); int result = (*it)->GetResult(); if (did_finish && result == OK) { TransitionToDone(); return; } if (!did_finish || result != ERR_PAC_NOT_IN_DHCP) { break; } } // Once we have a single result, we set a maximum on how long to wait // for the rest of the results. if (state_ == STATE_NO_RESULTS) { state_ = STATE_SOME_RESULTS; wait_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(ImplGetMaxWaitMs()), this, &DhcpProxyScriptFetcherWin::OnWaitTimer); } } void DhcpProxyScriptFetcherWin::OnWaitTimer() { DCHECK_EQ(state_, STATE_SOME_RESULTS); // These are intended to help us understand whether our timeout may // be too aggressive or not aggressive enough. UMA_HISTOGRAM_COUNTS_100("Net.DhcpWpadNumAdaptersAtWaitTimer", fetchers_.size()); UMA_HISTOGRAM_COUNTS_100("Net.DhcpWpadNumPendingAdaptersAtWaitTimer", num_pending_fetchers_); TransitionToDone(); } void DhcpProxyScriptFetcherWin::TransitionToDone() { DCHECK(state_ == STATE_NO_RESULTS || state_ == STATE_SOME_RESULTS); int result = ERR_PAC_NOT_IN_DHCP; // Default if no fetchers. if (!fetchers_.empty()) { // Scan twice for the result; once through the whole list for success, // then if no success, return result for most preferred network adapter, // preferring "real" network errors to the ERR_PAC_NOT_IN_DHCP error. // Default to ERR_ABORTED if no fetcher completed. result = ERR_ABORTED; for (FetcherVector::iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { if ((*it)->DidFinish() && (*it)->GetResult() == OK) { result = OK; *destination_string_ = (*it)->GetPacScript(); pac_url_ = (*it)->GetPacURL(); break; } } if (result != OK) { destination_string_->clear(); for (FetcherVector::iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { if ((*it)->DidFinish()) { result = (*it)->GetResult(); if (result != ERR_PAC_NOT_IN_DHCP) { break; } } } } } CompletionCallback callback = callback_; CancelImpl(); DCHECK_EQ(state_, STATE_DONE); DCHECK(fetchers_.empty()); DCHECK(callback_.is_null()); // Invariant of data. UMA_HISTOGRAM_TIMES("Net.DhcpWpadCompletionTime", base::TimeTicks::Now() - fetch_start_time_); if (result != OK) { UMA_HISTOGRAM_CUSTOM_ENUMERATION( "Net.DhcpWpadFetchError", std::abs(result), GetAllErrorCodesForUma()); } // We may be deleted re-entrantly within this outcall. callback.Run(result); } int DhcpProxyScriptFetcherWin::num_pending_fetchers() const { return num_pending_fetchers_; } URLRequestContext* DhcpProxyScriptFetcherWin::url_request_context() const { return url_request_context_; } DhcpProxyScriptAdapterFetcher* DhcpProxyScriptFetcherWin::ImplCreateAdapterFetcher() { return new DhcpProxyScriptAdapterFetcher(url_request_context_); } DhcpProxyScriptFetcherWin::AdapterQuery* DhcpProxyScriptFetcherWin::ImplCreateAdapterQuery() { return new AdapterQuery(); } int DhcpProxyScriptFetcherWin::ImplGetMaxWaitMs() { return kMaxWaitAfterFirstResultMs; } bool DhcpProxyScriptFetcherWin::GetCandidateAdapterNames( std::set<std::string>* adapter_names) { DCHECK(adapter_names); adapter_names->clear(); // The GetAdaptersAddresses MSDN page recommends using a size of 15000 to // avoid reallocation. ULONG adapters_size = 15000; scoped_ptr_malloc<IP_ADAPTER_ADDRESSES> adapters; ULONG error = ERROR_SUCCESS; int num_tries = 0; PerfTimer time_api_access; do { adapters.reset( reinterpret_cast<IP_ADAPTER_ADDRESSES*>(malloc(adapters_size))); // Return only unicast addresses, and skip information we do not need. error = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, adapters.get(), &adapters_size); ++num_tries; } while (error == ERROR_BUFFER_OVERFLOW && num_tries <= 3); // This is primarily to validate our belief that the GetAdaptersAddresses API // function is fast enough to call synchronously from the network thread. UMA_HISTOGRAM_TIMES("Net.DhcpWpadGetAdaptersAddressesTime", time_api_access.Elapsed()); if (error != ERROR_SUCCESS) { UMA_HISTOGRAM_CUSTOM_ENUMERATION( "Net.DhcpWpadGetAdaptersAddressesError", error, base::CustomHistogram::ArrayToCustomRanges( kGetAdaptersAddressesErrors, arraysize(kGetAdaptersAddressesErrors))); } if (error == ERROR_NO_DATA) { // There are no adapters that we care about. return true; } if (error != ERROR_SUCCESS) { LOG(WARNING) << "Unexpected error retrieving WPAD configuration from DHCP."; return false; } IP_ADAPTER_ADDRESSES* adapter = NULL; for (adapter = adapters.get(); adapter; adapter = adapter->Next) { if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue; if ((adapter->Flags & IP_ADAPTER_DHCP_ENABLED) == 0) continue; DCHECK(adapter->AdapterName); adapter_names->insert(adapter->AdapterName); } return true; } DhcpProxyScriptFetcherWin::AdapterQuery::AdapterQuery() { } DhcpProxyScriptFetcherWin::AdapterQuery::~AdapterQuery() { } void DhcpProxyScriptFetcherWin::AdapterQuery::GetCandidateAdapterNames() { ImplGetCandidateAdapterNames(&adapter_names_); } const std::set<std::string>& DhcpProxyScriptFetcherWin::AdapterQuery::adapter_names() const { return adapter_names_; } bool DhcpProxyScriptFetcherWin::AdapterQuery::ImplGetCandidateAdapterNames( std::set<std::string>* adapter_names) { return DhcpProxyScriptFetcherWin::GetCandidateAdapterNames(adapter_names); } } // namespace net <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: taskpanelist.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: rt $ $Date: 2005-09-09 12:31:37 $ * * 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 _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _TOOLS_RCID_H #include <tools/rcid.h> #endif #ifndef _SV_DOCKWIN_HXX #include <dockwin.hxx> #endif #include <taskpanelist.hxx> #include <functional> #include <algorithm> // can't have static linkage because SUNPRO 5.2 complains Point ImplTaskPaneListGetPos( const Window *w ) { Point pos; if( w->ImplIsDockingWindow() ) { pos = ((DockingWindow*)w)->GetPosPixel(); Window *pF = ((DockingWindow*)w)->GetFloatingWindow(); if( pF ) pos = pF->OutputToAbsoluteScreenPixel( pF->ScreenToOutputPixel( pos ) ); else pos = w->OutputToAbsoluteScreenPixel( pos ); } else pos = w->OutputToAbsoluteScreenPixel( w->GetPosPixel() ); return pos; } // compares window pos left-to-right struct LTRSort : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w1, const Window* w2 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; struct LTRSortBackward : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w2, const Window* w1 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; // -------------------------------------------------- static void ImplTaskPaneListGrabFocus( Window *pWindow ) { // put focus in child of floating windows which is typically a toolbar // that can deal with the focus if( pWindow->ImplIsFloatingWindow() && pWindow->GetWindow( WINDOW_FIRSTCHILD ) ) pWindow = pWindow->GetWindow( WINDOW_FIRSTCHILD ); pWindow->GrabFocus(); } // -------------------------------------------------- TaskPaneList::TaskPaneList() { } TaskPaneList::~TaskPaneList() { } // -------------------------------------------------- void TaskPaneList::AddWindow( Window *pWindow ) { #if OSL_DEBUG_LEVEL > 0 bool bDockingWindow=false; bool bToolbox=false; bool bDialog=false; bool bUnknown=false; #endif if( pWindow ) { #if OSL_DEBUG_LEVEL > 0 if( pWindow->GetType() == RSC_DOCKINGWINDOW ) bDockingWindow = true; else if( pWindow->GetType() == RSC_TOOLBOX ) bToolbox = true; else if( pWindow->IsDialog() ) bDialog = true; else bUnknown = true; #endif ::std::vector< Window* >::iterator insertionPos = mTaskPanes.end(); for ( ::std::vector< Window* >::iterator p = mTaskPanes.begin(); p != mTaskPanes.end(); ++p ) { if ( *p == pWindow ) // avoid duplicates return; // If the new window is the child of an existing pane window, or vice versa, // ensure that in our pane list, *first* the child window appears, *then* // the ancestor window. // This is necessary for HandleKeyEvent: There, the list is traveled from the // beginning, until the first window is found which has the ChildPathFocus. Now // if this would be the ancestor window of another pane window, this would fudge // the result // 2004-09-27 - fs@openoffice.org, while fixing #i33573#, which included replacing // the original fix for #98916# with this one here. if ( pWindow->IsWindowOrChild( *p ) ) { insertionPos = p + 1; break; } if ( (*p)->IsWindowOrChild( pWindow ) ) { insertionPos = p; break; } } mTaskPanes.insert( insertionPos, pWindow ); } } // -------------------------------------------------- void TaskPaneList::RemoveWindow( Window *pWindow ) { ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); if( p != mTaskPanes.end() ) mTaskPanes.erase( p ); } // -------------------------------------------------- BOOL TaskPaneList::IsInList( Window *pWindow ) { ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); if( p != mTaskPanes.end() ) return TRUE; else return FALSE; } // -------------------------------------------------- BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent ) { // F6 cycles through everything and works always // Ctrl-TAB cycles through Menubar, Toolbars and Floatingwindows only and is // only active if one of those items has the focus BOOL bF6 = FALSE; BOOL bSplitterOnly = FALSE; BOOL bFocusInList = FALSE; KeyCode aKeyCode = aKeyEvent.GetKeyCode(); BOOL bForward = !aKeyCode.IsShift(); if( ( (aKeyCode.IsMod1() || aKeyCode.IsMod2()) && aKeyCode.GetCode() == KEY_TAB ) // Ctrl-TAB or Alt-TAB || ( bF6 = ( aKeyCode.GetCode()) == KEY_F6 ) // F6 ) { bSplitterOnly = bF6 && aKeyCode.IsMod1() && aKeyCode.IsShift(); // is the focus in the list ? ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { Window *pWin = *p; if( pWin->HasChildPathFocus( TRUE ) ) { bFocusInList = TRUE; // Ctrl-TAB does not work in Dialogs if( !bF6 && pWin->IsDialog() ) return FALSE; // Ctrl-F6 goes directly to the document if( !pWin->IsDialog() && bF6 && aKeyCode.IsMod1() && !aKeyCode.IsShift() ) { pWin->GrabFocusToDocument(); return TRUE; } // activate next task pane Window *pNextWin = NULL; if( bSplitterOnly ) pNextWin = FindNextSplitter( *p, TRUE ); else pNextWin = bF6 ? FindNextFloat( *p, bForward ) : FindNextPane( *p, bForward ); if( pNextWin != pWin ) { ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE; ImplTaskPaneListGrabFocus( pNextWin ); ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE; } else { // forward key if no splitter found if( bSplitterOnly ) return FALSE; // we did not find another taskpane, so // put focus back into document pWin->GrabFocusToDocument(); } return TRUE; } else p++; } // the focus is not in the list: activate first float if F6 was pressed if( !bFocusInList && bF6 ) { Window *pWin; if( bSplitterOnly ) pWin = FindNextSplitter( NULL, TRUE ); else pWin = FindNextFloat( NULL, bForward ); if( pWin ) { ImplTaskPaneListGrabFocus( pWin ); return TRUE; } } } return FALSE; } // -------------------------------------------------- // returns next valid pane Window* TaskPaneList::FindNextPane( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( ++p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->IsReallyVisible() && !(*p)->IsDialog() && !(*p)->ImplIsSplitter() ) { pWindow = *p; break; } } break; } else ++p; } return pWindow; } // -------------------------------------------------- // returns next splitter Window* TaskPaneList::FindNextSplitter( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( !pWindow || *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( pWindow ) // increment before test ++p; if( p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->ImplIsSplitter() && (*p)->IsReallyVisible() && !(*p)->IsDialog() && (*p)->GetParent()->HasChildPathFocus() ) { pWindow = *p; break; } if( !pWindow ) // increment after test, otherwise first element is skipped ++p; } break; } else ++p; } return pWindow; } // -------------------------------------------------- // returns first valid item (regardless of type) if pWindow==0, otherwise returns next valid float Window* TaskPaneList::FindNextFloat( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( !pWindow || *p == pWindow ) { while( p != mTaskPanes.end() ) { if( pWindow ) // increment before test ++p; if( p == mTaskPanes.end() ) break; // do not wrap, send focus back to document at end of list if( (*p)->IsReallyVisible() && !(*p)->ImplIsSplitter() ) { pWindow = *p; break; } if( !pWindow ) // increment after test, otherwise first element is skipped ++p; } break; } else ++p; } return pWindow; } // -------------------------------------------------- <commit_msg>INTEGRATION: CWS vcl48 (1.18.94); FILE MERGED 2005/11/04 11:09:58 ssa 1.18.94.1: #122235# improve TaskPaneList handling, remove Windows automatically on destruction<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: taskpanelist.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: rt $ $Date: 2005-11-10 15:49:19 $ * * 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 _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _TOOLS_RCID_H #include <tools/rcid.h> #endif #ifndef _SV_DOCKWIN_HXX #include <dockwin.hxx> #endif #include <taskpanelist.hxx> #include <functional> #include <algorithm> // can't have static linkage because SUNPRO 5.2 complains Point ImplTaskPaneListGetPos( const Window *w ) { Point pos; if( w->ImplIsDockingWindow() ) { pos = ((DockingWindow*)w)->GetPosPixel(); Window *pF = ((DockingWindow*)w)->GetFloatingWindow(); if( pF ) pos = pF->OutputToAbsoluteScreenPixel( pF->ScreenToOutputPixel( pos ) ); else pos = w->OutputToAbsoluteScreenPixel( pos ); } else pos = w->OutputToAbsoluteScreenPixel( w->GetPosPixel() ); return pos; } // compares window pos left-to-right struct LTRSort : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w1, const Window* w2 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; struct LTRSortBackward : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w2, const Window* w1 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; // -------------------------------------------------- static void ImplTaskPaneListGrabFocus( Window *pWindow ) { // put focus in child of floating windows which is typically a toolbar // that can deal with the focus if( pWindow->ImplIsFloatingWindow() && pWindow->GetWindow( WINDOW_FIRSTCHILD ) ) pWindow = pWindow->GetWindow( WINDOW_FIRSTCHILD ); pWindow->GrabFocus(); } // -------------------------------------------------- TaskPaneList::TaskPaneList() { } TaskPaneList::~TaskPaneList() { } // -------------------------------------------------- void TaskPaneList::AddWindow( Window *pWindow ) { #if OSL_DEBUG_LEVEL > 0 bool bDockingWindow=false; bool bToolbox=false; bool bDialog=false; bool bUnknown=false; #endif if( pWindow ) { #if OSL_DEBUG_LEVEL > 0 if( pWindow->GetType() == RSC_DOCKINGWINDOW ) bDockingWindow = true; else if( pWindow->GetType() == RSC_TOOLBOX ) bToolbox = true; else if( pWindow->IsDialog() ) bDialog = true; else bUnknown = true; #endif ::std::vector< Window* >::iterator insertionPos = mTaskPanes.end(); for ( ::std::vector< Window* >::iterator p = mTaskPanes.begin(); p != mTaskPanes.end(); ++p ) { if ( *p == pWindow ) // avoid duplicates return; // If the new window is the child of an existing pane window, or vice versa, // ensure that in our pane list, *first* the child window appears, *then* // the ancestor window. // This is necessary for HandleKeyEvent: There, the list is traveled from the // beginning, until the first window is found which has the ChildPathFocus. Now // if this would be the ancestor window of another pane window, this would fudge // the result // 2004-09-27 - fs@openoffice.org, while fixing #i33573#, which included replacing // the original fix for #98916# with this one here. if ( pWindow->IsWindowOrChild( *p ) ) { insertionPos = p + 1; break; } if ( (*p)->IsWindowOrChild( pWindow ) ) { insertionPos = p; break; } } mTaskPanes.insert( insertionPos, pWindow ); pWindow->ImplIsInTaskPaneList( TRUE ); } } // -------------------------------------------------- void TaskPaneList::RemoveWindow( Window *pWindow ) { ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); if( p != mTaskPanes.end() ) { mTaskPanes.erase( p ); pWindow->ImplIsInTaskPaneList( FALSE ); } } // -------------------------------------------------- BOOL TaskPaneList::IsInList( Window *pWindow ) { ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); if( p != mTaskPanes.end() ) return TRUE; else return FALSE; } // -------------------------------------------------- BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent ) { // F6 cycles through everything and works always // Ctrl-TAB cycles through Menubar, Toolbars and Floatingwindows only and is // only active if one of those items has the focus BOOL bF6 = FALSE; BOOL bSplitterOnly = FALSE; BOOL bFocusInList = FALSE; KeyCode aKeyCode = aKeyEvent.GetKeyCode(); BOOL bForward = !aKeyCode.IsShift(); if( ( (aKeyCode.IsMod1() || aKeyCode.IsMod2()) && aKeyCode.GetCode() == KEY_TAB ) // Ctrl-TAB or Alt-TAB || ( bF6 = ( aKeyCode.GetCode()) == KEY_F6 ) // F6 ) { bSplitterOnly = bF6 && aKeyCode.IsMod1() && aKeyCode.IsShift(); // is the focus in the list ? ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { Window *pWin = *p; if( pWin->HasChildPathFocus( TRUE ) ) { bFocusInList = TRUE; // Ctrl-TAB does not work in Dialogs if( !bF6 && pWin->IsDialog() ) return FALSE; // Ctrl-F6 goes directly to the document if( !pWin->IsDialog() && bF6 && aKeyCode.IsMod1() && !aKeyCode.IsShift() ) { pWin->GrabFocusToDocument(); return TRUE; } // activate next task pane Window *pNextWin = NULL; if( bSplitterOnly ) pNextWin = FindNextSplitter( *p, TRUE ); else pNextWin = bF6 ? FindNextFloat( *p, bForward ) : FindNextPane( *p, bForward ); if( pNextWin != pWin ) { ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE; ImplTaskPaneListGrabFocus( pNextWin ); ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE; } else { // forward key if no splitter found if( bSplitterOnly ) return FALSE; // we did not find another taskpane, so // put focus back into document pWin->GrabFocusToDocument(); } return TRUE; } else p++; } // the focus is not in the list: activate first float if F6 was pressed if( !bFocusInList && bF6 ) { Window *pWin; if( bSplitterOnly ) pWin = FindNextSplitter( NULL, TRUE ); else pWin = FindNextFloat( NULL, bForward ); if( pWin ) { ImplTaskPaneListGrabFocus( pWin ); return TRUE; } } } return FALSE; } // -------------------------------------------------- // returns next valid pane Window* TaskPaneList::FindNextPane( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( ++p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->IsReallyVisible() && !(*p)->IsDialog() && !(*p)->ImplIsSplitter() ) { pWindow = *p; break; } } break; } else ++p; } return pWindow; } // -------------------------------------------------- // returns next splitter Window* TaskPaneList::FindNextSplitter( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( !pWindow || *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( pWindow ) // increment before test ++p; if( p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->ImplIsSplitter() && (*p)->IsReallyVisible() && !(*p)->IsDialog() && (*p)->GetParent()->HasChildPathFocus() ) { pWindow = *p; break; } if( !pWindow ) // increment after test, otherwise first element is skipped ++p; } break; } else ++p; } return pWindow; } // -------------------------------------------------- // returns first valid item (regardless of type) if pWindow==0, otherwise returns next valid float Window* TaskPaneList::FindNextFloat( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( !pWindow || *p == pWindow ) { while( p != mTaskPanes.end() ) { if( pWindow ) // increment before test ++p; if( p == mTaskPanes.end() ) break; // do not wrap, send focus back to document at end of list if( (*p)->IsReallyVisible() && !(*p)->ImplIsSplitter() ) { pWindow = *p; break; } if( !pWindow ) // increment after test, otherwise first element is skipped ++p; } break; } else ++p; } return pWindow; } // -------------------------------------------------- <|endoftext|>
<commit_before>R__LOAD_LIBRARY(dt_RunDrawTest.C+) void dt_wrap(const char* from, Int_t mode = 0, Int_t verboseLevel = 0) { // gROOT->ProcessLine(".L dt_RunDrawTest.C+"); int status = !dt_RunDrawTest(from,mode,verboseLevel); if (verboseLevel==0) gSystem->Exit(status); } <commit_msg>correct syntax for preloading ACLiC library<commit_after>#include "dt_RunDrawTest.C+" void dt_wrap(const char* from, Int_t mode = 0, Int_t verboseLevel = 0) { // gROOT->ProcessLine(".L dt_RunDrawTest.C+"); int status = !dt_RunDrawTest(from,mode,verboseLevel); if (verboseLevel==0) gSystem->Exit(status); } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 Kolibre * * This file is part of kolibre-naviengine. * * Kolibre-naviengine is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * Kolibre-naviengine 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 kolibre-naviengine. If not, see <http://www.gnu.org/licenses/>. */ #include "NaviEngine.h" using namespace naviengine; int currentSibling(const AnyNode* node) { if (node->parent_->firstChild() == NULL) { return 0; } const AnyNode* tmp = node; int num = 1; while (tmp != node->parent_->firstChild() && tmp != NULL) { tmp = tmp->prev_; num++; } return num; } /** * Constructor */ NaviEngine::NaviEngine() : good_(false) { } /** * Destructor * * Deletes nodes in the menu stack */ NaviEngine::~NaviEngine() { while (not menuStack.empty()) { delete menuStack.top().menuModel; menuStack.pop(); } } /** * Check if the last function call was successful * * @return A boolean indicating if the last function call was successful or not */ bool NaviEngine::good() const { return good_; } /** * Open a menu * * @param node The menu node to open * @param narrable If true, narrate functions are called * @return true on success, otherwise false */ bool NaviEngine::openMenu(AnyNode* node, bool narrable) { if (node == 0) return false; MenuState before; MenuState menu; menu.menuModel = node; menu.state.currentNode = node; menu.state.currentChoice = node->firstChild(); menuStack.push(menu); if (narrable) { if (not node->play_before_onOpen_.empty()) { narrate(node->play_before_onOpen_.c_str()); } good_ = node->onOpen(*this); narrateShortPause(); narrateChange(before, menuStack.top()); } return good_; } /** * Close a menu * * @return true on success, otherwsie false */ bool NaviEngine::closeMenu() { if (menuStack.size() > 1) { MenuState menu = menuStack.top(); delete menu.menuModel; menu.menuModel = NULL; menuStack.pop(); return true; // This means the menu was closed } MenuState& menu = menuStack.top(); menu.state.currentNode = menu.menuModel; // Fix the root menu state if someone borked it. menu.state.currentChoice = menu.state.currentNode->firstChild(); return false; // No menu closed } /** * Invokes onNarrate for the current node * * If onNarrate returns false NaviEngine will render the node * with the help of it's virtual narrate functions */ void NaviEngine::narrateNode() { MenuState& menu = menuStack.top(); if (not menu.state.currentNode->onNarrate()) { narrate(menu.state.currentNode->name_.c_str()); narrate(menu.state.currentNode->info_.c_str()); narrateShortPause(); narrateNode(menu.state.currentChoice); } } /** * Invoke onNarrate for a node * * If onNarrate returns false NaviEngine will render the node * with the help of it's virtual narrate functions * * @param choice A pointer the to choice to narrate */ void NaviEngine::narrateNode(AnyNode* node) { if (node == 0) return; if (not node->onNarrate()) { std::string name = node->name_; if (name != "") { narrate(currentSibling(node)); narrate(name.c_str()); narrateLongPause(); } } } /** * Invoke onRender for a node * * @param node A pointer the the node to render * @return The result from the onRender invoke */ bool NaviEngine::renderNode(AnyNode* node) { if (node == NULL) return false; bool selfRendered = node->onRender(); return not selfRendered; } /** * Go to the root (top) node * * @return true on success, otherwise false */ bool NaviEngine::top() { MenuState menu = menuStack.top(); // If already on top level, open the menu if (menu.state.currentNode == menu.menuModel) { narrate(menuStack.top().state.currentNode->play_before_onOpen_.c_str()); narrateShortPause(); menuStack.top().state.currentNode->onOpen(*this); } // If not on top level, go to top level while (menuStack.size() > 1 || menu.state.currentNode != menu.menuModel) { narrateStop(); up(); menu = menuStack.top(); } return true; } /** * Check if state has changed * * @param before The MenuState before * @return true is state has changed, otherwise false */ bool NaviEngine::stateHasChanged(const MenuState& before) { MenuState& now = menuStack.top(); if (now.state.currentNode != before.state.currentNode) { return true; } return false; } /** * Open the current node by invoking onOpen on a state change * * @param before The MenuState before * @return the result from onOpen if the state has changed, otherwise false */ bool NaviEngine::openOnChange(const MenuState& before) { MenuState& now = menuStack.top(); if (now.state.currentNode == NULL) closeMenu(); now = menuStack.top(); { // Check if the node has changed if (now.state.currentNode != before.state.currentNode) { narrate(now.state.currentNode->play_before_onOpen_.c_str()); narrateShortPause(); good_ = now.state.currentNode->onOpen(*this); narrateChange(before, now); return good_; } } return false; } /** * Go to the parent node * * @return true on success, otherwise false */ bool NaviEngine::up() { bool success = false; MenuState before = menuStack.top(); success = menuStack.top().state.currentNode->up(*this); if (stateHasChanged(before)) return openOnChange(before); return openOnChange(before); } /** * Open the currently selected child * * @return true on success, otherwise false */ bool NaviEngine::select() { bool success = false; MenuState before = menuStack.top(); success = menuStack.top().state.currentNode->select(*this); if (stateHasChanged(before)) return openOnChange(before); return openOnChange(before); } /** * Open the child referenced by uri * * @param uri The uri of the child * @return true on success, otherwise false */ bool NaviEngine::selectNodeByUri(std::string uri) { bool success = false; MenuState before = menuStack.top(); AnyNode* currentNode = menuStack.top().state.currentNode; if (currentNode->isVirtual()) { success = currentNode->selectByUri(*this, uri); } else { AnyNode* currentChild = currentNode->firstChild(); if (currentChild != NULL) { do { if (uri == currentChild->uri_) { menuStack.top().state.currentChoice = currentChild; success = currentNode->select(*this); break; } currentChild = currentChild->next_; } while (currentChild != currentNode->firstChild() && currentChild != NULL); } } if (stateHasChanged(before)) return openOnChange(before); return success; } /** * Go to the next child and set it as the currently selected child * * @return true on success, otherwise false */ bool NaviEngine::next() { MenuState& menu = menuStack.top(); MenuState before = menu; if (menu.state.currentNode->next(*this)) { narrateChange(before, menu); return true; } return false; } /** * Go to the previous child and set it as the currently selected child * * @return true on success, otherwise false */ bool NaviEngine::prev() { MenuState& menu = menuStack.top(); MenuState before = menu; if (menu.state.currentNode->prev(*this)) { narrateChange(before, menu); return true; } return false; } /** * Open the context menu for the current node * * @return true on success, otherwise false */ bool NaviEngine::openContextMenu() { MenuState& menu = menuStack.top(); return menu.state.currentNode->menu(*this); } /** * Let the current node process the command * * @param command The enumerated command the node shall process * @data data A pointer to a optional data object * @return The result of the process operation */ bool NaviEngine::process(int command, void* data) { MenuState& menu = menuStack.top(); MenuState before = menu; bool processedCommand = true; if (not menu.state.currentNode->process(*this, command, data)) { // This is a short of time hack. processedCommand = false; } { // Check if the node has changed during process MenuState& menu = menuStack.top(); if (menu.state.currentNode != before.state.currentNode) { if (menu.state.currentNode == NULL) { closeMenu(); } MenuState& menu = menuStack.top(); narrate(menu.state.currentNode->play_before_onOpen_.c_str()); narrateShortPause(); good_ = menu.state.currentNode->onOpen(*this); // Consider a successful node change to mean that the command was processed. if (good_) processedCommand = true; } } MenuState& after = menuStack.top(); narrateChange(before, after); return processedCommand; } /** * Get the number of children for a node * * @param node A pointer to the node for which to get the number of children * @return A positive value if the node has children, otherwise 0 */ int NaviEngine::numberOfChildren(AnyNode* node) { if (node == NULL || node->firstChild() == NULL) { return 0; } const AnyNode* tmp = node->firstChild(); int num = 0; do { tmp = tmp->next_; num++; } while (tmp != node->firstChild() && tmp != NULL); return num; } /** * Get the current node * * @return A pointer to the current node */ AnyNode* NaviEngine::getCurrentNode() { return menuStack.top().state.currentNode; } /** * Set the current node * * @param node A pointer to the node which shell become the current node */ void NaviEngine::setCurrentNode(AnyNode* node) { menuStack.top().state.currentNode = node; } /** * Get the current choice * * @return A pointer to the current choice */ AnyNode* NaviEngine::getCurrentChoice() { return menuStack.top().state.currentChoice; } /** * Set the current choice * * @param node A pointer to the node which shall become the current choice */ void NaviEngine::setCurrentChoice(AnyNode* node) { menuStack.top().state.currentChoice = node; } <commit_msg>Fix unclear use of openOnChange<commit_after>/* * Copyright (C) 2012 Kolibre * * This file is part of kolibre-naviengine. * * Kolibre-naviengine is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * Kolibre-naviengine 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 kolibre-naviengine. If not, see <http://www.gnu.org/licenses/>. */ #include "NaviEngine.h" using namespace naviengine; int currentSibling(const AnyNode* node) { if (node->parent_->firstChild() == NULL) { return 0; } const AnyNode* tmp = node; int num = 1; while (tmp != node->parent_->firstChild() && tmp != NULL) { tmp = tmp->prev_; num++; } return num; } /** * Constructor */ NaviEngine::NaviEngine() : good_(false) { } /** * Destructor * * Deletes nodes in the menu stack */ NaviEngine::~NaviEngine() { while (not menuStack.empty()) { delete menuStack.top().menuModel; menuStack.pop(); } } /** * Check if the last function call was successful * * @return A boolean indicating if the last function call was successful or not */ bool NaviEngine::good() const { return good_; } /** * Open a menu * * @param node The menu node to open * @param narrable If true, narrate functions are called * @return true on success, otherwise false */ bool NaviEngine::openMenu(AnyNode* node, bool narrable) { if (node == 0) return false; MenuState before; MenuState menu; menu.menuModel = node; menu.state.currentNode = node; menu.state.currentChoice = node->firstChild(); menuStack.push(menu); if (narrable) { if (not node->play_before_onOpen_.empty()) { narrate(node->play_before_onOpen_.c_str()); } good_ = node->onOpen(*this); narrateShortPause(); narrateChange(before, menuStack.top()); } return good_; } /** * Close a menu * * @return true on success, otherwsie false */ bool NaviEngine::closeMenu() { if (menuStack.size() > 1) { MenuState menu = menuStack.top(); delete menu.menuModel; menu.menuModel = NULL; menuStack.pop(); return true; // This means the menu was closed } MenuState& menu = menuStack.top(); menu.state.currentNode = menu.menuModel; // Fix the root menu state if someone borked it. menu.state.currentChoice = menu.state.currentNode->firstChild(); return false; // No menu closed } /** * Invokes onNarrate for the current node * * If onNarrate returns false NaviEngine will render the node * with the help of it's virtual narrate functions */ void NaviEngine::narrateNode() { MenuState& menu = menuStack.top(); if (not menu.state.currentNode->onNarrate()) { narrate(menu.state.currentNode->name_.c_str()); narrate(menu.state.currentNode->info_.c_str()); narrateShortPause(); narrateNode(menu.state.currentChoice); } } /** * Invoke onNarrate for a node * * If onNarrate returns false NaviEngine will render the node * with the help of it's virtual narrate functions * * @param choice A pointer the to choice to narrate */ void NaviEngine::narrateNode(AnyNode* node) { if (node == 0) return; if (not node->onNarrate()) { std::string name = node->name_; if (name != "") { narrate(currentSibling(node)); narrate(name.c_str()); narrateLongPause(); } } } /** * Invoke onRender for a node * * @param node A pointer the the node to render * @return The result from the onRender invoke */ bool NaviEngine::renderNode(AnyNode* node) { if (node == NULL) return false; bool selfRendered = node->onRender(); return not selfRendered; } /** * Go to the root (top) node * * @return true on success, otherwise false */ bool NaviEngine::top() { MenuState menu = menuStack.top(); // If already on top level, open the menu if (menu.state.currentNode == menu.menuModel) { narrate(menuStack.top().state.currentNode->play_before_onOpen_.c_str()); narrateShortPause(); menuStack.top().state.currentNode->onOpen(*this); } // If not on top level, go to top level while (menuStack.size() > 1 || menu.state.currentNode != menu.menuModel) { narrateStop(); up(); menu = menuStack.top(); } return true; } /** * Check if state has changed * * @param before The MenuState before * @return true is state has changed, otherwise false */ bool NaviEngine::stateHasChanged(const MenuState& before) { MenuState& now = menuStack.top(); if (now.state.currentNode != before.state.currentNode) { return true; } return false; } /** * Open the current node by invoking onOpen on a state change * * @param before The MenuState before * @return the result from onOpen if the state has changed, otherwise false */ bool NaviEngine::openOnChange(const MenuState& before) { MenuState& now = menuStack.top(); if (now.state.currentNode == NULL) closeMenu(); if (stateHasChanged(before)) { now = menuStack.top(); narrate(now.state.currentNode->play_before_onOpen_.c_str()); narrateShortPause(); good_ = now.state.currentNode->onOpen(*this); narrateChange(before, now); return good_; } return false; } /** * Go to the parent node * * @return true on success, otherwise false */ bool NaviEngine::up() { bool success = false; MenuState before = menuStack.top(); success = menuStack.top().state.currentNode->up(*this); return openOnChange(before); } /** * Open the currently selected child * * @return true on success, otherwise false */ bool NaviEngine::select() { bool success = false; MenuState before = menuStack.top(); success = menuStack.top().state.currentNode->select(*this); return openOnChange(before); } /** * Open the child referenced by uri * * @param uri The uri of the child * @return true on success, otherwise false */ bool NaviEngine::selectNodeByUri(std::string uri) { bool success = false; MenuState before = menuStack.top(); AnyNode* currentNode = menuStack.top().state.currentNode; if (currentNode->isVirtual()) { success = currentNode->selectByUri(*this, uri); } else { AnyNode* currentChild = currentNode->firstChild(); if (currentChild != NULL) { do { if (uri == currentChild->uri_) { menuStack.top().state.currentChoice = currentChild; success = currentNode->select(*this); break; } currentChild = currentChild->next_; } while (currentChild != currentNode->firstChild() && currentChild != NULL); } } if (stateHasChanged(before)) return openOnChange(before); return success; } /** * Go to the next child and set it as the currently selected child * * @return true on success, otherwise false */ bool NaviEngine::next() { MenuState& menu = menuStack.top(); MenuState before = menu; if (menu.state.currentNode->next(*this)) { narrateChange(before, menu); return true; } return false; } /** * Go to the previous child and set it as the currently selected child * * @return true on success, otherwise false */ bool NaviEngine::prev() { MenuState& menu = menuStack.top(); MenuState before = menu; if (menu.state.currentNode->prev(*this)) { narrateChange(before, menu); return true; } return false; } /** * Open the context menu for the current node * * @return true on success, otherwise false */ bool NaviEngine::openContextMenu() { MenuState& menu = menuStack.top(); return menu.state.currentNode->menu(*this); } /** * Let the current node process the command * * @param command The enumerated command the node shall process * @data data A pointer to a optional data object * @return The result of the process operation */ bool NaviEngine::process(int command, void* data) { MenuState& menu = menuStack.top(); MenuState before = menu; bool processedCommand = true; if (not menu.state.currentNode->process(*this, command, data)) { // This is a short of time hack. processedCommand = false; } { // Check if the node has changed during process MenuState& menu = menuStack.top(); if (menu.state.currentNode != before.state.currentNode) { if (menu.state.currentNode == NULL) { closeMenu(); } MenuState& menu = menuStack.top(); narrate(menu.state.currentNode->play_before_onOpen_.c_str()); narrateShortPause(); good_ = menu.state.currentNode->onOpen(*this); // Consider a successful node change to mean that the command was processed. if (good_) processedCommand = true; } } MenuState& after = menuStack.top(); narrateChange(before, after); return processedCommand; } /** * Get the number of children for a node * * @param node A pointer to the node for which to get the number of children * @return A positive value if the node has children, otherwise 0 */ int NaviEngine::numberOfChildren(AnyNode* node) { if (node == NULL || node->firstChild() == NULL) { return 0; } const AnyNode* tmp = node->firstChild(); int num = 0; do { tmp = tmp->next_; num++; } while (tmp != node->firstChild() && tmp != NULL); return num; } /** * Get the current node * * @return A pointer to the current node */ AnyNode* NaviEngine::getCurrentNode() { return menuStack.top().state.currentNode; } /** * Set the current node * * @param node A pointer to the node which shell become the current node */ void NaviEngine::setCurrentNode(AnyNode* node) { menuStack.top().state.currentNode = node; } /** * Get the current choice * * @return A pointer to the current choice */ AnyNode* NaviEngine::getCurrentChoice() { return menuStack.top().state.currentChoice; } /** * Set the current choice * * @param node A pointer to the node which shall become the current choice */ void NaviEngine::setCurrentChoice(AnyNode* node) { menuStack.top().state.currentChoice = node; } <|endoftext|>
<commit_before>/** * @file Cosa/DS18B20.cpp * @version 1.0 * * @section License * Copyright (C) 2012, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @section Description * Driver for the DS18B20 Programmable Resolution 1-Write * Digital Thermometer. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/DS18B20.h" bool DS18B20::convert_request() { if (!_pin->reset()) return (0); _pin->write(OneWire::SKIP_ROM); _pin->write(CONVERT_T); return (1); } bool DS18B20::read_scratchpad() { if (!_pin->reset()) return (0); _pin->write(OneWire::SKIP_ROM); _pin->write(READ_SCRATCHPAD); _pin->begin(); for (uint8_t i = 0; i < SCRATCHPAD_MAX; i++) { _scratchpad[i] = _pin->read(); } return (_pin->end() == 0); } void DS18B20::print_scratchpad(IOStream& stream) { for (uint8_t i = 0; i < SCRATCHPAD_MAX; i++) { stream.printf_P(PSTR("scratchpad[%d] = %hd\n"), i, _scratchpad[i]); } } int16_t DS18B20::get_temperature() { int16_t temp = (_scratchpad[1] << 8) | _scratchpad[0]; return (temp); } void DS18B20::get(temperature_t& res) { int16_t temp = ((int16_t*) _scratchpad)[0]; int16_t numerator = temp >> 4; if (temp < 0) temp = -temp; uint16_t denominator = 0; uint16_t fraction = 625; for (uint8_t i = 0; i < 4; i++) { if (temp & 1) denominator += fraction; fraction <<= 1; temp >>= 1; } if (denominator < 1000 && denominator > 500) denominator = 1000; res.numerator = numerator; res.denominator = denominator; } <commit_msg>Improved sample access in DS18B20 sample in scratchpad memory.<commit_after>/** * @file Cosa/DS18B20.cpp * @version 1.0 * * @section License * Copyright (C) 2012, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @section Description * Driver for the DS18B20 Programmable Resolution 1-Write * Digital Thermometer. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/DS18B20.h" bool DS18B20::convert_request() { if (!_pin->reset()) return (0); _pin->write(OneWire::SKIP_ROM); _pin->write(CONVERT_T); return (1); } bool DS18B20::read_scratchpad() { if (!_pin->reset()) return (0); _pin->write(OneWire::SKIP_ROM); _pin->write(READ_SCRATCHPAD); _pin->begin(); for (uint8_t i = 0; i < SCRATCHPAD_MAX; i++) { _scratchpad[i] = _pin->read(); } return (_pin->end() == 0); } void DS18B20::print_scratchpad(IOStream& stream) { for (uint8_t i = 0; i < SCRATCHPAD_MAX; i++) { stream.printf_P(PSTR("scratchpad[%d] = %hd\n"), i, _scratchpad[i]); } } int16_t DS18B20::get_temperature() { return (((int16_t*) _scratchpad)[0]); } void DS18B20::get(temperature_t& res) { int16_t temp = ((int16_t*) _scratchpad)[0]; int16_t numerator = temp >> 4; if (temp < 0) temp = -temp; uint16_t denominator = 0; uint16_t fraction = 625; for (uint8_t i = 0; i < 4; i++) { if (temp & 1) denominator += fraction; fraction <<= 1; temp >>= 1; } if (denominator < 1000 && denominator > 500) denominator = 1000; res.numerator = numerator; res.denominator = denominator; } <|endoftext|>
<commit_before>#ifndef ANY_HPP # define ANY_HPP # pragma once #include <cassert> #include <cstdint> #include <stdexcept> #include <typeinfo> #include <type_traits> #include <utility> namespace generic { class any { using typeid_t = ::std::uintptr_t; template <typename T> static typeid_t type_id() { return typeid_t(&type_id<T>); } public: any() = default; any(any const& other) : content(other.content ? other.content->clone() : nullptr) { } any(any&& other) noexcept { *this = ::std::move(other); } template<typename ValueType, typename = typename ::std::enable_if< !::std::is_same<any, typename ::std::decay<ValueType>::type>::value >::type > any(ValueType&& value) : content(new holder<typename ::std::decay<ValueType>::type>( ::std::forward<ValueType>(value))) { } ~any() { delete content; } public: // modifiers void clear() noexcept { swap(any()); } void swap(any& other) noexcept { ::std::swap(content, other.content); } void swap(any&& other) noexcept { ::std::swap(content, other.content); } any& operator=(any const& rhs) { return *this = any(rhs); } any& operator=(any&& rhs) noexcept { content = rhs.content; rhs.content = nullptr; return *this; } template<typename ValueType, typename = typename ::std::enable_if< !::std::is_same<any, typename ::std::decay<ValueType>::type>{} >::type > any& operator=(ValueType&& rhs) { return *this = any(::std::forward<ValueType>(rhs)); } public: // queries explicit operator bool() const noexcept { return content; } typeid_t type() const noexcept { return content ? content->type() : type_id<void>(); } private: // types struct placeholder { placeholder() = default; virtual ~placeholder() = default; virtual placeholder* clone() const = 0; virtual typeid_t type() const = 0; }; template <typename ValueType, typename = void> struct holder : public placeholder { public: // constructor template <class T> holder(T&& value) : held(::std::forward<T>(value)) { } holder& operator=(holder const&) = delete; placeholder* clone() const final { throw ::std::logic_error(""); } public: // queries typeid_t type() const noexcept final { return type_id<ValueType>(); } public: ValueType held; }; template <typename ValueType> struct holder< ValueType, typename ::std::enable_if< ::std::is_copy_constructible<ValueType>::value >::type > : public placeholder { public: // constructor template <class T> holder(T&& value) : held(::std::forward<T>(value)) { } placeholder* clone() const final { return new holder<ValueType>(held); } public: // queries typeid_t type() const noexcept final { return type_id<ValueType>(); } public: ValueType held; }; private: // representation template<typename ValueType> friend ValueType* any_cast(any*) noexcept; template<typename ValueType> friend ValueType* unsafe_any_cast(any*) noexcept; placeholder* content{}; }; template<typename ValueType> inline ValueType* unsafe_any_cast(any* const operand) noexcept { return &static_cast<any::holder<ValueType>*>(operand->content)->held; } template<typename ValueType> inline ValueType const* unsafe_any_cast(any const* const operand) noexcept { return unsafe_any_cast<ValueType>(const_cast<any*>(operand)); } template<typename ValueType> inline ValueType* any_cast(any* const operand) noexcept { return operand && (operand->type() == any::type_id<typename ::std::decay<ValueType>::type>()) ? &static_cast<any::holder<ValueType>*>(operand->content)->held : nullptr; } template<typename ValueType> inline ValueType const* any_cast(any const* const operand) noexcept { return any_cast<ValueType>(const_cast<any*>(operand)); } template<typename ValueType> inline ValueType any_cast(any& operand) { using nonref = typename ::std::remove_reference<ValueType>::type; #ifndef NDEBUG auto const result(any_cast<nonref>(&operand)); if (!result) { throw ::std::bad_cast(); } // else do nothing return *result; #else return *unsafe_any_cast<nonref>(&operand); #endif // NDEBUG } template<typename ValueType> inline ValueType any_cast(any const& operand) { using nonref = typename ::std::remove_reference<ValueType>::type; return any_cast<nonref const&>(const_cast<any&>(operand)); } } #endif // ANY_HPP <commit_msg>some fixes<commit_after>#ifndef ANY_HPP # define ANY_HPP # pragma once #include <cassert> #include <cstdint> #include <stdexcept> #include <typeinfo> #include <type_traits> #include <utility> namespace generic { class any { using typeid_t = ::std::uintptr_t; template <typename T> constexpr static typeid_t type_id() { return typeid_t(type_id<T>); } public: any() = default; any(any const& other) : content(other.content ? other.content->clone() : nullptr) { } any(any&& other) noexcept { *this = ::std::move(other); } template<typename ValueType, typename = typename ::std::enable_if< !::std::is_same<any, typename ::std::decay<ValueType>::type>::value >::type > any(ValueType&& value) : content(new holder<typename ::std::decay<ValueType>::type>( ::std::forward<ValueType>(value))) { } ~any() { delete content; } public: // modifiers void clear() noexcept { swap(any()); } void swap(any& other) noexcept { ::std::swap(content, other.content); } void swap(any&& other) noexcept { ::std::swap(content, other.content); } any& operator=(any const& rhs) { return *this = any(rhs); } any& operator=(any&& rhs) noexcept { content = rhs.content; rhs.content = nullptr; return *this; } template<typename ValueType, typename = typename ::std::enable_if< !::std::is_same<any, typename ::std::decay<ValueType>::type>{} >::type > any& operator=(ValueType&& rhs) { return *this = any(::std::forward<ValueType>(rhs)); } public: // queries explicit operator bool() const noexcept { return content; } typeid_t type() const noexcept { return content ? content->type() : type_id<void>(); } private: // types struct placeholder { placeholder() = default; virtual ~placeholder() = default; virtual placeholder* clone() const = 0; virtual typeid_t type() const = 0; }; template <typename ValueType, typename = void> struct holder : public placeholder { public: // constructor template <class T> holder(T&& value) : held(::std::forward<T>(value)) { } holder& operator=(holder const&) = delete; placeholder* clone() const final { throw ::std::logic_error(""); } public: // queries typeid_t type() const noexcept final { return type_id<ValueType>(); } public: ValueType held; }; template <typename ValueType> struct holder< ValueType, typename ::std::enable_if< ::std::is_copy_constructible<ValueType>::value >::type > : public placeholder { public: // constructor template <class T> holder(T&& value) : held(::std::forward<T>(value)) { } placeholder* clone() const final { return new holder<ValueType>(held); } public: // queries typeid_t type() const noexcept final { return type_id<ValueType>(); } public: ValueType held; }; private: // representation template<typename ValueType> friend ValueType* any_cast(any*) noexcept; template<typename ValueType> friend ValueType* unsafe_any_cast(any*) noexcept; placeholder* content{}; }; template<typename ValueType> inline ValueType* unsafe_any_cast(any* const operand) noexcept { return &static_cast<any::holder<ValueType>*>(operand->content)->held; } template<typename ValueType> inline ValueType const* unsafe_any_cast(any const* const operand) noexcept { return unsafe_any_cast<ValueType>(const_cast<any*>(operand)); } template<typename ValueType> inline ValueType* any_cast(any* const operand) noexcept { return operand && (operand->type() == any::type_id<typename ::std::decay<ValueType>::type>()) ? &static_cast<any::holder<ValueType>*>(operand->content)->held : nullptr; } template<typename ValueType> inline ValueType const* any_cast(any const* const operand) noexcept { return any_cast<ValueType>(const_cast<any*>(operand)); } template<typename ValueType> inline ValueType any_cast(any& operand) { using nonref = typename ::std::remove_reference<ValueType>::type; #ifndef NDEBUG auto const result(any_cast<nonref>(&operand)); if (!result) { throw ::std::bad_cast(); } // else do nothing return *result; #else return *unsafe_any_cast<nonref>(&operand); #endif // NDEBUG } template<typename ValueType> inline ValueType any_cast(any const& operand) { using nonref = typename ::std::remove_reference<ValueType>::type; return any_cast<nonref const&>(const_cast<any&>(operand)); } } #endif // ANY_HPP <|endoftext|>
<commit_before>/************************************************************************/ /* */ /* Copyright 2009 by Ullrich Koethe and Hans Meine */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://hci.iwr.uni-heidelberg.de/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* Permission is hereby granted, free of charge, to any person */ /* obtaining a copy of this software and associated documentation */ /* files (the "Software"), to deal in the Software without */ /* restriction, including without limitation the rights to use, */ /* copy, modify, merge, publish, distribute, sublicense, and/or */ /* sell copies of the Software, and to permit persons to whom the */ /* Software is furnished to do so, subject to the following */ /* conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the */ /* Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ /* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ /* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ /* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ /* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ /* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ /* OTHER DEALINGS IN THE SOFTWARE. */ /* */ /************************************************************************/ #define PY_ARRAY_UNIQUE_SYMBOL vigranumpycore_PyArray_API #define NO_IMPORT_ARRAY #include <vigra/numpy_array.hxx> #include <vigra/numpy_array_converters.hxx> #include <boost/python.hpp> #include <boost/python/to_python_converter.hpp> namespace python = boost::python; namespace vigra { #define VIGRA_NUMPY_TYPECHECKER(type) \ if(python::object((python::detail::new_reference)PyArray_TypeObjectFromType(type)).ptr() == obj) \ return obj; #define VIGRA_NUMPY_TYPECONVERTER(type) \ if(python::object((python::detail::new_reference)PyArray_TypeObjectFromType(type)).ptr() == obj) \ typeID = type; struct NumpyTypenumConverter { NumpyTypenumConverter() { python::converter::registry::insert(&convertible, &construct, python::type_id<NPY_TYPES>()); python::to_python_converter<NPY_TYPES, NumpyTypenumConverter>(); } static void* convertible(PyObject* obj) { // FIXME: there should be a more elegant way to program this... if(obj == 0) return 0; if(obj->ob_type == &PyArrayDescr_Type) return obj; if(!PyType_Check(obj)) return 0; VIGRA_NUMPY_TYPECHECKER(NPY_BOOL) VIGRA_NUMPY_TYPECHECKER(NPY_INT8) VIGRA_NUMPY_TYPECHECKER(NPY_UINT8) VIGRA_NUMPY_TYPECHECKER(NPY_INT16) VIGRA_NUMPY_TYPECHECKER(NPY_UINT16) VIGRA_NUMPY_TYPECHECKER(NPY_INT32) VIGRA_NUMPY_TYPECHECKER(NPY_UINT32) VIGRA_NUMPY_TYPECHECKER(NPY_INT) VIGRA_NUMPY_TYPECHECKER(NPY_UINT) VIGRA_NUMPY_TYPECHECKER(NPY_INT64) VIGRA_NUMPY_TYPECHECKER(NPY_UINT64) VIGRA_NUMPY_TYPECHECKER(NPY_FLOAT32) VIGRA_NUMPY_TYPECHECKER(NPY_FLOAT64) VIGRA_NUMPY_TYPECHECKER(NPY_LONGDOUBLE) VIGRA_NUMPY_TYPECHECKER(NPY_CFLOAT) VIGRA_NUMPY_TYPECHECKER(NPY_CDOUBLE) VIGRA_NUMPY_TYPECHECKER(NPY_CLONGDOUBLE) return 0; } // from Python static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data) { void* const storage = ((python::converter::rvalue_from_python_storage<NumpyAnyArray>* ) data)->storage.bytes; // FIXME: there should be a more elegant way to program this... int typeID = -1; if(obj->ob_type == &PyArrayDescr_Type) typeID = (NPY_TYPES)((PyArray_Descr*)obj)->type_num; VIGRA_NUMPY_TYPECONVERTER(NPY_BOOL) VIGRA_NUMPY_TYPECONVERTER(NPY_INT8) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT8) VIGRA_NUMPY_TYPECONVERTER(NPY_INT16) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT16) VIGRA_NUMPY_TYPECONVERTER(NPY_INT32) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT32) VIGRA_NUMPY_TYPECONVERTER(NPY_INT) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT) VIGRA_NUMPY_TYPECONVERTER(NPY_INT64) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT64) VIGRA_NUMPY_TYPECONVERTER(NPY_FLOAT32) VIGRA_NUMPY_TYPECONVERTER(NPY_FLOAT64) VIGRA_NUMPY_TYPECONVERTER(NPY_LONGDOUBLE) VIGRA_NUMPY_TYPECONVERTER(NPY_CFLOAT) VIGRA_NUMPY_TYPECONVERTER(NPY_CDOUBLE) VIGRA_NUMPY_TYPECONVERTER(NPY_CLONGDOUBLE) new (storage) NPY_TYPES((NPY_TYPES)typeID); data->convertible = storage; } // to Python static PyObject* convert(NPY_TYPES typeID) { return PyArray_TypeObjectFromType(typeID); } }; #undef VIGRA_NUMPY_TYPECHECKER #undef VIGRA_NUMPY_TYPECONVERTER struct NumpyAnyArrayConverter { NumpyAnyArrayConverter() { python::converter::registry::insert(&convertible, &construct, python::type_id<NumpyAnyArray>()); python::to_python_converter<NumpyAnyArray, NumpyAnyArrayConverter>(); } static void* convertible(PyObject* obj) { return obj && (obj == Py_None || PyArray_Check(obj)) ? obj : 0; } // from Python static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data) { void* const storage = ((python::converter::rvalue_from_python_storage<NumpyAnyArray>* ) data)->storage.bytes; if(obj == Py_None) obj = 0; new (storage) NumpyAnyArray(obj); data->convertible = storage; } static PyObject* convert(NumpyAnyArray const& a) { return returnNumpyArray(a); } }; namespace detail { template <int N, class T> struct MultiArrayShapeConverterTraits { typedef TinyVector<T, N> ShapeType; static void construct(void* const storage, PyObject * obj) { ShapeType * shape = new (storage) ShapeType(); for(int i=0; i<PySequence_Length(obj); ++i) (*shape)[i] = python::extract<T>(PySequence_ITEM(obj, i)); } }; template <class T> struct MultiArrayShapeConverterTraits<0, T> { typedef ArrayVector<T> ShapeType; static void construct(void* const storage, PyObject * obj) { int len = (obj == Py_None) ? 0 : PySequence_Length(obj); ShapeType * shape = new (storage) ShapeType(len); for(int i=0; i<len; ++i) (*shape)[i] = python::extract<T>(PySequence_ITEM(obj, i)); } }; } // namespace detail template <int M, class T> struct MultiArrayShapeConverter { typedef typename detail::MultiArrayShapeConverterTraits<M, T>::ShapeType ShapeType; MultiArrayShapeConverter() { python::converter::registry::insert(&convertible, &construct, python::type_id<ShapeType>()); python::to_python_converter<ShapeType, MultiArrayShapeConverter>(); } static void* convertible(PyObject* obj) { if(obj == 0) return 0; if(M == 0 && obj == Py_None) return obj; if(!PySequence_Check(obj) || (M != 0 && PySequence_Length(obj) != M)) return 0; for(int i=0; i<PySequence_Length(obj); ++i) if(!PyNumber_Check(PySequence_ITEM(obj, i))) return 0; return obj; } // from Python static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data) { void* const storage = ((python::converter::rvalue_from_python_storage<ShapeType>* ) data)->storage.bytes; detail::MultiArrayShapeConverterTraits<M, T>::construct(storage, obj); data->convertible = storage; } // to Python static PyObject* convert(ShapeType const& shape) { return shapeToPythonTuple(shape).release(); } }; python_ptr point2DToPythonTuple(Point2D const & point) { python_ptr tuple(PyTuple_New(2), python_ptr::keep_count); pythonToCppException(tuple); PyTuple_SET_ITEM((PyTupleObject *)tuple.get(), 0 ,pythonFromData(point.x).release()); PyTuple_SET_ITEM((PyTupleObject *)tuple.get(), 1 ,pythonFromData(point.y).release()); return tuple; } struct Point2DConverter { Point2DConverter() { python::converter::registry::insert(&convertible, &construct, python::type_id<Point2D>()); python::to_python_converter<Point2D, Point2DConverter>(); } static void* convertible(PyObject* obj) { if(obj == 0 || !PySequence_Check(obj) || (PySequence_Length(obj) !=2)) return 0; if(!PyNumber_Check(PySequence_Fast_GET_ITEM(obj,0))) return 0; if(!PyNumber_Check(PySequence_Fast_GET_ITEM(obj,0))) return 0; return obj; } //from python static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data) { void* const storage = ((python::converter::rvalue_from_python_storage<Point2D>*) data)->storage.bytes; new (storage) Point2D(python::extract<int>(PySequence_Fast_GET_ITEM(obj,0)), python::extract<int>(PySequence_Fast_GET_ITEM(obj,1))); data->convertible = storage; } //to python static PyObject* convert(Point2D const& p) { return point2DToPythonTuple(p).release(); } }; void registerNumpyPoint2DConverter() { Point2DConverter(); } template <class T> void registerNumpyShapeConvertersOneType() { MultiArrayShapeConverter<0, T>(); MultiArrayShapeConverter<1, T>(); MultiArrayShapeConverter<2, T>(); MultiArrayShapeConverter<3, T>(); MultiArrayShapeConverter<4, T>(); MultiArrayShapeConverter<5, T>(); } void registerNumpyShapeConvertersAllTypes() { registerNumpyShapeConvertersOneType<MultiArrayIndex>(); registerNumpyShapeConvertersOneType<float>(); registerNumpyShapeConvertersOneType<double>(); if(typeid(npy_intp) != typeid(MultiArrayIndex)) MultiArrayShapeConverter<0, npy_intp>(); } #if 0 // FIXME: reimplement to replace the Python versions for consistence? PyObject * constructNumpyArrayFromShape(python::object type, ArrayVector<npy_intp> const & shape, unsigned int spatialDimensions, unsigned int channels, NPY_TYPES typeCode, std::string order, bool init) { PyObject * obj = type.ptr(); vigra_precondition(obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type), "constructNumpyArray(type, ...): first argument was not an array type."); return detail::constructNumpyArrayImpl((PyTypeObject *)obj, shape, spatialDimensions, channels, typeCode, order, init).release(); } PyObject * constructNumpyArrayFromArray(python::object type, NumpyAnyArray array, unsigned int spatialDimensions, unsigned int channels, NPY_TYPES typeCode, std::string order, bool init) { PyObject * obj = type.ptr(); vigra_precondition(obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type), "constructNumpyArray(type, ...): first argument was not an array type."); PyObject * res = detail::constructNumpyArrayImpl((PyTypeObject *)obj, array.shape(), spatialDimensions, channels, typeCode, order, false, array.strideOrdering()).release(); if(init) { NumpyAnyArray lhs(res); lhs = array; } return res; } #endif PyObject * constructArrayFromAxistags(python::object type, ArrayVector<npy_intp> const & shape, NPY_TYPES typeCode, AxisTags const & axistags, bool init) { PyAxisTags pyaxistags(python_ptr(python::object(axistags).ptr())); ArrayVector<npy_intp> norm_shape(shape); if(pyaxistags.size() > 0) { ArrayVector<npy_intp> permutation(pyaxistags.permutationToNormalOrder()); applyPermutation(permutation.begin(), permutation.end(), shape.begin(), norm_shape.begin()); } TaggedShape tagged_shape(norm_shape, pyaxistags); // FIXME: check that type is an array class? return constructArray(tagged_shape, typeCode, init, python_ptr(type.ptr())); } void registerNumpyArrayConverters() { NumpyTypenumConverter(); registerNumpyShapeConvertersAllTypes(); registerNumpyPoint2DConverter(); NumpyAnyArrayConverter(); python::docstring_options doc_options(true, true, false); doc_options.disable_all(); python::def("constructArrayFromAxistags", &constructArrayFromAxistags); // python::def("constructNumpyArray", &constructNumpyArrayFromArray); } } // namespace vigra <commit_msg>added #include Python.h<commit_after>/************************************************************************/ /* */ /* Copyright 2009 by Ullrich Koethe and Hans Meine */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://hci.iwr.uni-heidelberg.de/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* Permission is hereby granted, free of charge, to any person */ /* obtaining a copy of this software and associated documentation */ /* files (the "Software"), to deal in the Software without */ /* restriction, including without limitation the rights to use, */ /* copy, modify, merge, publish, distribute, sublicense, and/or */ /* sell copies of the Software, and to permit persons to whom the */ /* Software is furnished to do so, subject to the following */ /* conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the */ /* Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ /* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ /* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ /* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ /* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ /* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ /* OTHER DEALINGS IN THE SOFTWARE. */ /* */ /************************************************************************/ #define PY_ARRAY_UNIQUE_SYMBOL vigranumpycore_PyArray_API #define NO_IMPORT_ARRAY #include <Python.h> #include <vigra/numpy_array.hxx> #include <vigra/numpy_array_converters.hxx> #include <boost/python.hpp> #include <boost/python/to_python_converter.hpp> namespace python = boost::python; namespace vigra { #define VIGRA_NUMPY_TYPECHECKER(type) \ if(python::object((python::detail::new_reference)PyArray_TypeObjectFromType(type)).ptr() == obj) \ return obj; #define VIGRA_NUMPY_TYPECONVERTER(type) \ if(python::object((python::detail::new_reference)PyArray_TypeObjectFromType(type)).ptr() == obj) \ typeID = type; struct NumpyTypenumConverter { NumpyTypenumConverter() { python::converter::registry::insert(&convertible, &construct, python::type_id<NPY_TYPES>()); python::to_python_converter<NPY_TYPES, NumpyTypenumConverter>(); } static void* convertible(PyObject* obj) { // FIXME: there should be a more elegant way to program this... if(obj == 0) return 0; if(obj->ob_type == &PyArrayDescr_Type) return obj; if(!PyType_Check(obj)) return 0; VIGRA_NUMPY_TYPECHECKER(NPY_BOOL) VIGRA_NUMPY_TYPECHECKER(NPY_INT8) VIGRA_NUMPY_TYPECHECKER(NPY_UINT8) VIGRA_NUMPY_TYPECHECKER(NPY_INT16) VIGRA_NUMPY_TYPECHECKER(NPY_UINT16) VIGRA_NUMPY_TYPECHECKER(NPY_INT32) VIGRA_NUMPY_TYPECHECKER(NPY_UINT32) VIGRA_NUMPY_TYPECHECKER(NPY_INT) VIGRA_NUMPY_TYPECHECKER(NPY_UINT) VIGRA_NUMPY_TYPECHECKER(NPY_INT64) VIGRA_NUMPY_TYPECHECKER(NPY_UINT64) VIGRA_NUMPY_TYPECHECKER(NPY_FLOAT32) VIGRA_NUMPY_TYPECHECKER(NPY_FLOAT64) VIGRA_NUMPY_TYPECHECKER(NPY_LONGDOUBLE) VIGRA_NUMPY_TYPECHECKER(NPY_CFLOAT) VIGRA_NUMPY_TYPECHECKER(NPY_CDOUBLE) VIGRA_NUMPY_TYPECHECKER(NPY_CLONGDOUBLE) return 0; } // from Python static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data) { void* const storage = ((python::converter::rvalue_from_python_storage<NumpyAnyArray>* ) data)->storage.bytes; // FIXME: there should be a more elegant way to program this... int typeID = -1; if(obj->ob_type == &PyArrayDescr_Type) typeID = (NPY_TYPES)((PyArray_Descr*)obj)->type_num; VIGRA_NUMPY_TYPECONVERTER(NPY_BOOL) VIGRA_NUMPY_TYPECONVERTER(NPY_INT8) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT8) VIGRA_NUMPY_TYPECONVERTER(NPY_INT16) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT16) VIGRA_NUMPY_TYPECONVERTER(NPY_INT32) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT32) VIGRA_NUMPY_TYPECONVERTER(NPY_INT) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT) VIGRA_NUMPY_TYPECONVERTER(NPY_INT64) VIGRA_NUMPY_TYPECONVERTER(NPY_UINT64) VIGRA_NUMPY_TYPECONVERTER(NPY_FLOAT32) VIGRA_NUMPY_TYPECONVERTER(NPY_FLOAT64) VIGRA_NUMPY_TYPECONVERTER(NPY_LONGDOUBLE) VIGRA_NUMPY_TYPECONVERTER(NPY_CFLOAT) VIGRA_NUMPY_TYPECONVERTER(NPY_CDOUBLE) VIGRA_NUMPY_TYPECONVERTER(NPY_CLONGDOUBLE) new (storage) NPY_TYPES((NPY_TYPES)typeID); data->convertible = storage; } // to Python static PyObject* convert(NPY_TYPES typeID) { return PyArray_TypeObjectFromType(typeID); } }; #undef VIGRA_NUMPY_TYPECHECKER #undef VIGRA_NUMPY_TYPECONVERTER struct NumpyAnyArrayConverter { NumpyAnyArrayConverter() { python::converter::registry::insert(&convertible, &construct, python::type_id<NumpyAnyArray>()); python::to_python_converter<NumpyAnyArray, NumpyAnyArrayConverter>(); } static void* convertible(PyObject* obj) { return obj && (obj == Py_None || PyArray_Check(obj)) ? obj : 0; } // from Python static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data) { void* const storage = ((python::converter::rvalue_from_python_storage<NumpyAnyArray>* ) data)->storage.bytes; if(obj == Py_None) obj = 0; new (storage) NumpyAnyArray(obj); data->convertible = storage; } static PyObject* convert(NumpyAnyArray const& a) { return returnNumpyArray(a); } }; namespace detail { template <int N, class T> struct MultiArrayShapeConverterTraits { typedef TinyVector<T, N> ShapeType; static void construct(void* const storage, PyObject * obj) { ShapeType * shape = new (storage) ShapeType(); for(int i=0; i<PySequence_Length(obj); ++i) (*shape)[i] = python::extract<T>(PySequence_ITEM(obj, i)); } }; template <class T> struct MultiArrayShapeConverterTraits<0, T> { typedef ArrayVector<T> ShapeType; static void construct(void* const storage, PyObject * obj) { int len = (obj == Py_None) ? 0 : PySequence_Length(obj); ShapeType * shape = new (storage) ShapeType(len); for(int i=0; i<len; ++i) (*shape)[i] = python::extract<T>(PySequence_ITEM(obj, i)); } }; } // namespace detail template <int M, class T> struct MultiArrayShapeConverter { typedef typename detail::MultiArrayShapeConverterTraits<M, T>::ShapeType ShapeType; MultiArrayShapeConverter() { python::converter::registry::insert(&convertible, &construct, python::type_id<ShapeType>()); python::to_python_converter<ShapeType, MultiArrayShapeConverter>(); } static void* convertible(PyObject* obj) { if(obj == 0) return 0; if(M == 0 && obj == Py_None) return obj; if(!PySequence_Check(obj) || (M != 0 && PySequence_Length(obj) != M)) return 0; for(int i=0; i<PySequence_Length(obj); ++i) if(!PyNumber_Check(PySequence_ITEM(obj, i))) return 0; return obj; } // from Python static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data) { void* const storage = ((python::converter::rvalue_from_python_storage<ShapeType>* ) data)->storage.bytes; detail::MultiArrayShapeConverterTraits<M, T>::construct(storage, obj); data->convertible = storage; } // to Python static PyObject* convert(ShapeType const& shape) { return shapeToPythonTuple(shape).release(); } }; python_ptr point2DToPythonTuple(Point2D const & point) { python_ptr tuple(PyTuple_New(2), python_ptr::keep_count); pythonToCppException(tuple); PyTuple_SET_ITEM((PyTupleObject *)tuple.get(), 0 ,pythonFromData(point.x).release()); PyTuple_SET_ITEM((PyTupleObject *)tuple.get(), 1 ,pythonFromData(point.y).release()); return tuple; } struct Point2DConverter { Point2DConverter() { python::converter::registry::insert(&convertible, &construct, python::type_id<Point2D>()); python::to_python_converter<Point2D, Point2DConverter>(); } static void* convertible(PyObject* obj) { if(obj == 0 || !PySequence_Check(obj) || (PySequence_Length(obj) !=2)) return 0; if(!PyNumber_Check(PySequence_Fast_GET_ITEM(obj,0))) return 0; if(!PyNumber_Check(PySequence_Fast_GET_ITEM(obj,0))) return 0; return obj; } //from python static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data) { void* const storage = ((python::converter::rvalue_from_python_storage<Point2D>*) data)->storage.bytes; new (storage) Point2D(python::extract<int>(PySequence_Fast_GET_ITEM(obj,0)), python::extract<int>(PySequence_Fast_GET_ITEM(obj,1))); data->convertible = storage; } //to python static PyObject* convert(Point2D const& p) { return point2DToPythonTuple(p).release(); } }; void registerNumpyPoint2DConverter() { Point2DConverter(); } template <class T> void registerNumpyShapeConvertersOneType() { MultiArrayShapeConverter<0, T>(); MultiArrayShapeConverter<1, T>(); MultiArrayShapeConverter<2, T>(); MultiArrayShapeConverter<3, T>(); MultiArrayShapeConverter<4, T>(); MultiArrayShapeConverter<5, T>(); } void registerNumpyShapeConvertersAllTypes() { registerNumpyShapeConvertersOneType<MultiArrayIndex>(); registerNumpyShapeConvertersOneType<float>(); registerNumpyShapeConvertersOneType<double>(); if(typeid(npy_intp) != typeid(MultiArrayIndex)) MultiArrayShapeConverter<0, npy_intp>(); } #if 0 // FIXME: reimplement to replace the Python versions for consistence? PyObject * constructNumpyArrayFromShape(python::object type, ArrayVector<npy_intp> const & shape, unsigned int spatialDimensions, unsigned int channels, NPY_TYPES typeCode, std::string order, bool init) { PyObject * obj = type.ptr(); vigra_precondition(obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type), "constructNumpyArray(type, ...): first argument was not an array type."); return detail::constructNumpyArrayImpl((PyTypeObject *)obj, shape, spatialDimensions, channels, typeCode, order, init).release(); } PyObject * constructNumpyArrayFromArray(python::object type, NumpyAnyArray array, unsigned int spatialDimensions, unsigned int channels, NPY_TYPES typeCode, std::string order, bool init) { PyObject * obj = type.ptr(); vigra_precondition(obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type), "constructNumpyArray(type, ...): first argument was not an array type."); PyObject * res = detail::constructNumpyArrayImpl((PyTypeObject *)obj, array.shape(), spatialDimensions, channels, typeCode, order, false, array.strideOrdering()).release(); if(init) { NumpyAnyArray lhs(res); lhs = array; } return res; } #endif PyObject * constructArrayFromAxistags(python::object type, ArrayVector<npy_intp> const & shape, NPY_TYPES typeCode, AxisTags const & axistags, bool init) { PyAxisTags pyaxistags(python_ptr(python::object(axistags).ptr())); ArrayVector<npy_intp> norm_shape(shape); if(pyaxistags.size() > 0) { ArrayVector<npy_intp> permutation(pyaxistags.permutationToNormalOrder()); applyPermutation(permutation.begin(), permutation.end(), shape.begin(), norm_shape.begin()); } TaggedShape tagged_shape(norm_shape, pyaxistags); // FIXME: check that type is an array class? return constructArray(tagged_shape, typeCode, init, python_ptr(type.ptr())); } void registerNumpyArrayConverters() { NumpyTypenumConverter(); registerNumpyShapeConvertersAllTypes(); registerNumpyPoint2DConverter(); NumpyAnyArrayConverter(); python::docstring_options doc_options(true, true, false); doc_options.disable_all(); python::def("constructArrayFromAxistags", &constructArrayFromAxistags); // python::def("constructNumpyArray", &constructNumpyArrayFromArray); } } // namespace vigra <|endoftext|>
<commit_before>//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef POPULATION_HPP #define POPULATION_HPP namespace galgo { //================================================================================================= template <typename T, int...N> class Population { static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend."); public: // nullary constructor Population() {} // constructor Population(const GeneticAlgorithm<T,N...>& ga); // create a population of chromosomes void creation(); // evolve population, get next generation void evolution(); // access element in current population at position pos const CHR<T,N...>& operator()(int pos) const; // access element in mating population at position pos const CHR<T,N...>& operator[](int pos) const; // return iterator to current population beginning typename std::vector<CHR<T,N...>>::iterator begin(); // return const iterator to current population beginning typename std::vector<CHR<T,N...>>::const_iterator cbegin() const; // return iterator to current population ending typename std::vector<CHR<T,N...>>::iterator end(); // return const iterator to current population ending typename std::vector<CHR<T,N...>>::const_iterator cend() const; // select element at position pos in current population and copy it into mating population void select(int pos); // set all fitness to positive values void adjustFitness(); // compute fitness sum of current population T getSumFitness() const; // get worst objective function total result from current population T getWorstTotal() const; // return population size int popsize() const; // return mating population size int matsize() const; // return tournament size int tntsize() const; // return numero of generation int nogen() const; // return number of generations int nbgen() const; // return selection pressure T SP() const; private: std::vector<CHR<T,N...>> curpop; // current population std::vector<CHR<T,N...>> matpop; // mating population std::vector<CHR<T,N...>> newpop; // new population const GeneticAlgorithm<T,N...>* ptr = nullptr; // pointer to genetic algorithm int nbrcrov; // number of cross-over int matidx; // mating population index // elitism => saving best chromosomes in new population void elitism(); // create new population from recombination of the old one void recombination(); // complete new population randomly void completion(); // update population (adapting, sorting) void updating(); }; /*-------------------------------------------------------------------------------------------------*/ // constructor template <typename T, int...N> Population<T,N...>::Population(const GeneticAlgorithm<T,N...>& ga) { ptr = &ga; nbrcrov = floor(ga.covrate * (ga.popsize - ga.elitpop)); // adjusting nbrcrov (must be an even number) if (nbrcrov % 2 != 0) nbrcrov -= 1; // for convenience, we add elitpop to nbrcrov nbrcrov += ga.elitpop; // allocating memory curpop.resize(ga.popsize); matpop.resize(ga.matsize); } /*-------------------------------------------------------------------------------------------------*/ // create a population of chromosomes template <typename T, int...N> void Population<T,N...>::creation() { int start = 0; // initializing first chromosome if (!ptr->initialSet.empty()) { curpop[0] = std::make_shared<Chromosome<T,N...>>(*ptr); curpop[0]->initialize(); curpop[0]->evaluate(); start++; } // getting the rest #ifdef _OPENMP #pragma omp parallel for num_threads(MAX_THREADS) #endif for (int i = start; i < ptr->popsize; ++i) { curpop[i] = std::make_shared<Chromosome<T,N...>>(*ptr); curpop[i]->create(); curpop[i]->evaluate(); } // updating population this->updating(); } /*-------------------------------------------------------------------------------------------------*/ // population evolution (selection, recombination, completion, mutation), get next generation template <typename T, int...N> void Population<T,N...>::evolution() { // initializing mating population index matidx = 0; // selecting mating population ptr->Selection(*this); // applying elitism if required this->elitism(); // crossing-over mating population this->recombination(); // completing new population this->completion(); // moving new population into current population for next generation curpop = std::move(newpop); // updating population this->updating(); } /*-------------------------------------------------------------------------------------------------*/ // elitism => saving best chromosomes in new population, making a copy of each elit chromosome template <typename T, int...N> void Population<T,N...>::elitism() { // (re)allocating new population newpop.resize(ptr->popsize); if (ptr->elitpop > 0) { // copying elit chromosomes into new population std::transform(curpop.cbegin(), curpop.cend(), newpop.begin(), [](const CHR<T,N...>& chr)->CHR<T,N...>{return std::make_shared<Chromosome<T,N...>>(*chr);}); } } /*-------------------------------------------------------------------------------------------------*/ // create new population from recombination of the old one template <typename T, int...N> void Population<T,N...>::recombination() { // creating a new population by cross-over #ifdef _OPENMP #pragma omp parallel for num_threads(MAX_THREADS) #endif for (int i = ptr->elitpop; i < nbrcrov; i = i + 2) { // initializing 2 new chromosome newpop[i] = std::make_shared<Chromosome<T,N...>>(*ptr); newpop[i+1] = std::make_shared<Chromosome<T,N...>>(*ptr); // crossing-over mating population to create 2 new chromosomes ptr->CrossOver(*this, newpop[i], newpop[i+1]); // mutating new chromosomes ptr->Mutation(newpop[i]); ptr->Mutation(newpop[i+1]); // evaluating new chromosomes newpop[i]->evaluate(); newpop[i+1]->evaluate(); } } /*-------------------------------------------------------------------------------------------------*/ // complete new population template <typename T, int...N> void Population<T,N...>::completion() { #ifdef _OPENMP #pragma omp parallel for num_threads(MAX_THREADS) #endif for (int i = nbrcrov; i < ptr->popsize; ++i) { // selecting chromosome randomly from mating population newpop[i] = std::make_shared<Chromosome<T,N...>>(*matpop[uniform<int>(0, ptr->matsize)]); // mutating chromosome ptr->Mutation(newpop[i]); // evaluating chromosome newpop[i]->evaluate(); } } /*-------------------------------------------------------------------------------------------------*/ // update population (adapting, sorting) template <typename T, int...N> void Population<T,N...>::updating() { // adapting population to constraints if (ptr->Constraint != nullptr) { ptr->Adaptation(*this); } // sorting chromosomes from best to worst fitness std::sort(curpop.begin(),curpop.end(),[](const CHR<T,N...>& chr1,const CHR<T,N...>& chr2)->bool{return chr1->fitness > chr2->fitness;}); } /*-------------------------------------------------------------------------------------------------*/ // access element in current population at position pos template <typename T, int...N> const CHR<T,N...>& Population<T,N...>::operator()(int pos) const { #ifndef NDEBUG if (pos > ptr->popsize - 1) { throw std::invalid_argument("Error: in galgo::Population<T>::operator()(int), exceeding current population memory."); } #endif return curpop[pos]; } /*-------------------------------------------------------------------------------------------------*/ // access element in mating population at position pos template <typename T, int...N> const CHR<T,N...>& Population<T,N...>::operator[](int pos) const { #ifndef NDEBUG if (pos > ptr->matsize - 1) { throw std::invalid_argument("Error: in galgo::Population<T>::operator[](int), exceeding mating population memory."); } #endif return matpop[pos]; } /*-------------------------------------------------------------------------------------------------*/ // return iterator to current population beginning template <typename T, int...N> inline typename std::vector<CHR<T,N...>>::iterator Population<T,N...>::begin() { return curpop.begin(); } /*-------------------------------------------------------------------------------------------------*/ // return const iterator to current population beginning template <typename T, int...N> inline typename std::vector<CHR<T,N...>>::const_iterator Population<T,N...>::cbegin() const { return curpop.cbegin(); } /*-------------------------------------------------------------------------------------------------*/ // return iterator to current population ending template <typename T, int...N> inline typename std::vector<CHR<T,N...>>::iterator Population<T,N...>::end() { return curpop.end(); } /*-------------------------------------------------------------------------------------------------*/ // return const iterator to current population ending template <typename T, int...N> inline typename std::vector<CHR<T,N...>>::const_iterator Population<T,N...>::cend() const { return curpop.cend(); } /*-------------------------------------------------------------------------------------------------*/ // select element at position pos in current population and copy it into mating population template <typename T, int...N> inline void Population<T,N...>::select(int pos) { #ifndef NDEBUG if (pos > ptr->popsize - 1) { throw std::out_of_range("Error: in galgo::Population<T>::select(int), exceeding current population memory."); } if (matidx == ptr->matsize) { throw std::out_of_range("Error: in galgo::Population<T>::select(int), exceeding mating population memory."); } #endif matpop[matidx] = curpop[pos]; matidx++; } /*-------------------------------------------------------------------------------------------------*/ // set all fitness to positive values (used in RWS and SUS selection methods) template <typename T, int...N> void Population<T,N...>::adjustFitness() { // getting worst population fitness T worstFitness = curpop.back()->fitness; if (worstFitness < 0) { // getting best fitness T bestFitness = curpop.front()->fitness; // case where all fitness are equal and negative if (worstFitness == bestFitness) { std::for_each(curpop.begin(), curpop.end(), [](CHR<T,N...>& chr)->void{chr->fitness *= -1;}); } else { std::for_each(curpop.begin(), curpop.end(), [worstFitness](CHR<T,N...>& chr)->void{chr->fitness -= worstFitness;}); } } } /*-------------------------------------------------------------------------------------------------*/ // compute population fitness sum (used in TRS, RWS and SUS selection methods) template <typename T, int...N> inline T Population<T,N...>::getSumFitness() const { return std::accumulate(curpop.cbegin(), curpop.cend(), 0.0, [](T sum, const CHR<T,N...>& chr)->T{return sum + T(chr->fitness);}); } /*-------------------------------------------------------------------------------------------------*/ // get worst objective function total result from current population (used in constraint(s) adaptation) template <typename T, int...N> inline T Population<T,N...>::getWorstTotal() const { auto it = std::min_element(curpop.begin(), curpop.end(), [](const CHR<T,N...>& chr1, const CHR<T,N...>& chr2)->bool{return chr1->getTotal() < chr2->getTotal();}); return (*it)->getTotal(); } /*-------------------------------------------------------------------------------------------------*/ // return population size template <typename T, int...N> inline int Population<T,N...>::popsize() const { return ptr->popsize; } /*-------------------------------------------------------------------------------------------------*/ // return mating population size template <typename T, int...N> inline int Population<T,N...>::matsize() const { return ptr->matsize; } /*-------------------------------------------------------------------------------------------------*/ // return tournament size template <typename T, int...N> inline int Population<T,N...>::tntsize() const { return ptr->tntsize; } /*-------------------------------------------------------------------------------------------------*/ // return numero of generation template <typename T, int...N> inline int Population<T,N...>::nogen() const { return ptr->nogen; } /*-------------------------------------------------------------------------------------------------*/ // return number of generations template <typename T, int...N> inline int Population<T,N...>::nbgen() const { return ptr->nbgen; } /*-------------------------------------------------------------------------------------------------*/ // return selection pressure template <typename T, int...N> inline T Population<T,N...>::SP() const { return ptr->SP; } //================================================================================================= } #endif <commit_msg>Delete Population.hpp<commit_after><|endoftext|>
<commit_before>//--------------------------------------------------------------- SudokuGrid.cpp #include "SudokuGrid.h" #include "SetOperations.h" #include <numeric> #include <stdexcept> #include <string> using namespace std; namespace { const string subhorz(13, '-'); const string subhorz2(13, ' '); const string horz = "+" + subhorz + "+" + subhorz + "+" + subhorz + "+"; const string horz2 = "|" + subhorz2 + "|" + subhorz2 + "|" + subhorz2 + "|"; const string vert(11, '|'); } // namespace const SudokuGrid::set_t SudokuGrid::EMPTY; const SudokuGrid::set_t SudokuGrid::U{ makeRange<SudokuGrid::value_t>(1, SudokuGrid::ORDER2 + 1)}; ostream &operator<<(ostream &os, const SudokuGrid &sdkg) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if ((col != 0) && (col % SudokuGrid::ORDER == 0)) { os << "|"; } if (!sdkg.cellIsSolved(row, col)) { os << " . "; } else { os << " " << sdkg._cell[row][col] << " "; } } os << endl; if ((row != SudokuGrid::ORDER2 - 1) && (row % SudokuGrid::ORDER == (SudokuGrid::ORDER - 1))) { // @TODO Remove magic number os << string(29, '-') << endl; } } os << endl; return os; } std::istream &operator>>(std::istream &is, SudokuGrid &sdkg) { int value{0}; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { is >> value; sdkg.add(value, row, col); } } sdkg.calculateAllCellCandidates(); return is; } void writeCandidates(std::ostream &os, const SudokuGrid &sdkg) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (col == 0 && row % SudokuGrid::ORDER == 0 && row < SudokuGrid::ORDER2 - 1) { os << horz; if (row == 0) { os << " ID = " << &sdkg << " " << sdkg.getID() << " " << (sdkg.isSolvable() ? "" : " not solvable"); } os << endl << horz2 << endl; } if (col == 0) os << "| "; SudokuGrid::set_t candidates = sdkg.getCellCandidates(row, col); for (SudokuGrid::value_t v = 1; v <= SudokuGrid::ORDER; ++v) { if (isAnElementOf(v, candidates)) { os << v; } else { candidates == SudokuGrid::EMPTY ? os << ' ' : os << '.'; } } if ((col != 0) && (col % SudokuGrid::ORDER == 2)) { os << " | "; } else { os << " "; } } os << endl; for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (col == 0) os << "| "; int pos{-1}; SudokuGrid::set_t candidates{sdkg.getCellCandidates(row, col)}; for (SudokuGrid::value_t v = SudokuGrid::ORDER + 1; v <= 2 * SudokuGrid::ORDER; ++v) { if (isAnElementOf(v, candidates)) { os << v; } else { if (candidates == SudokuGrid::EMPTY) { ++pos; (pos == 1) ? os << sdkg._cell[row][col] : os << ' '; } else { os << '.'; } } } if ((col != 0) && (col % SudokuGrid::ORDER == 2)) { os << " | "; } else { os << " "; } } os << endl; for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (col == 0) os << "| "; SudokuGrid::set_t candidates{sdkg.getCellCandidates(row, col)}; for (SudokuGrid::value_t v = 2 * SudokuGrid::ORDER + 1; v < 3 * SudokuGrid::ORDER + 1; ++v) { if (isAnElementOf(v, candidates)) { os << v; } else { candidates == SudokuGrid::EMPTY ? os << ' ' : os << '.'; } } if ((col != 0) && (col % SudokuGrid::ORDER == 2)) { os << " | "; } else { os << " "; } } os << endl << horz2 << endl; } os << horz << endl; } void writeLatex(std::ostream &os, const SudokuGrid &sdkg) { os << "\n\\begin{sudoku}\n"; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (!sdkg.cellIsSolved(row, col)) { os << "| "; } else { os << "|" << sdkg._cell[row][col]; } } os << "|.\n"; } os << "\\end{sudoku}\n\n"; } SudokuGrid::SudokuGrid() : _id{} , _numberOfCellsSolved{0} , _isSolvable{true} , _cell{{}} , _columnSet{{}} , _rowSet{{}} , _blockSet{{}} , _candidates{{}} , pRow{} , pColumn{} , pBlock{} { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int column = 0; column < SudokuGrid::ORDER2; ++column) { _candidates[row][column] = U; } } _columnSet.fill(U); _rowSet.fill(U); for (int row = 0; row < SudokuGrid::ORDER; ++row) { for (int column = 0; column < SudokuGrid::ORDER; ++column) { _blockSet[row][column] = U; } } mapPointerArraysToCandidates(); } SudokuGrid::SudokuGrid(const SudokuGrid &sdkg) : _id{sdkg._id} , _numberOfCellsSolved{sdkg._numberOfCellsSolved} , _isSolvable{sdkg._isSolvable} , _cell{{}} , _columnSet{{}} , _rowSet{{}} , _blockSet{{}} , _candidates{{}} , pRow{} , pColumn{} , pBlock{} { _cell = sdkg._cell; _columnSet = sdkg._columnSet; _rowSet = sdkg._rowSet; _blockSet = sdkg._blockSet; _candidates = sdkg._candidates; mapPointerArraysToCandidates(); // writeCandidates(cout, sdkg); // cout << "COPY" << endl; // writeCandidates(cout, *this); } SudokuGrid &SudokuGrid::operator=(const SudokuGrid &sdkg) { if (this != &sdkg) { _id = sdkg._id; _numberOfCellsSolved = sdkg._numberOfCellsSolved; _isSolvable = sdkg._isSolvable; _cell = sdkg._cell; _columnSet = sdkg._columnSet; _rowSet = sdkg._rowSet; _blockSet = sdkg._blockSet; _candidates = sdkg._candidates; mapPointerArraysToCandidates(); } return *this; } bool SudokuGrid::removeCandidates(const set_t &rem, int row, int column) { set_t candidates{_candidates[row][column]}; _candidates[row][column] = _candidates[row][column] - rem; return candidates != _candidates[row][column]; } void SudokuGrid::add(const value_t value, int row, int column) { if (isSolvable()) { if (isAnElementOf(value, SudokuGrid::U)) { // cout << "-- Add: " << Value << " in [" << Row << "][" << Column << // "]" << endl; if (isAnElementOf(value, _columnSet[column]) && isAnElementOf(value, _rowSet[row]) && isAnElementOf(value, _blockSet[row / SudokuGrid::ORDER] [column / SudokuGrid::ORDER])) { _columnSet[column].erase(value); _rowSet[row].erase(value); _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER] .erase(value); _candidates[row][column] = SudokuGrid::EMPTY; _cell[row][column] = value; ++_numberOfCellsSolved; } else { // cout << "ADD ERROR" << endl; // writeCandidates(cout, *this); // getchar(); throw std::logic_error( "-- [" + to_string(row) + "][" + to_string(column) + "] Sudoku element: " + to_string(value) + " not in groups"); } } else { if (value != 0) { throw std::logic_error("-- Sudoku element: " + to_string(value) + " must be in the range " "[1," + to_string(SudokuGrid::ORDER2) + "]"); } _cell[row][column] = 0; } calculateAllCellCandidates(); } else { cout << "ADD to not solvable sudoku grid " << getID() << endl; } } void SudokuGrid::unsafeAdd(const value_t value, int row, int column) { _columnSet[column].erase(value); _rowSet[row].erase(value); _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER].erase(value); _candidates[row][column] = SudokuGrid::EMPTY; _cell[row][column] = value; if (value != 0) { ++_numberOfCellsSolved; } calculateAllCellCandidates(); } //------------------------------------------------------------------------------ void SudokuGrid::calculateAllCellCandidates() { for (int row = 0; row < SudokuGrid::ORDER2 && _isSolvable; ++row) { for (int col = 0; col < SudokuGrid::ORDER2 && _isSolvable; ++col) { if (!cellIsSolved(row, col)) { _candidates[row][col] = calculateCellCandidates(row, col); if (_candidates[row][col].empty()) { _isSolvable = false; } } } } } SudokuGrid::set_t SudokuGrid::calculateCellCandidates(int row, int column) const { return _columnSet[column] * _rowSet[row] * _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER]; } void SudokuGrid::mapPointerArraysToCandidates() { for (int groupIndex = 0; groupIndex < SudokuGrid::ORDER2; ++groupIndex) { for (int index = 0; index < SudokuGrid::ORDER2; ++index) { pRow[groupIndex][index] = &_candidates[groupIndex][index]; pColumn[groupIndex][index] = &_candidates[index][groupIndex]; } } for (int blockIndex = 0; blockIndex < SudokuGrid::ORDER2; ++blockIndex) { int index = 0; int starti = SudokuGrid::ORDER * (blockIndex / SudokuGrid::ORDER); int startj = SudokuGrid::ORDER * (blockIndex % SudokuGrid::ORDER); for (int i = starti; i < starti + SudokuGrid::ORDER; ++i) { for (int j = startj; j < startj + SudokuGrid::ORDER; ++j) { pBlock[blockIndex][index++] = &_candidates[i][j]; } } } } //----------------------------------------------------------- eof SudokuGrid.cpp <commit_msg>Improved layout<commit_after>#include "SudokuGrid.h" #include "SetOperations.h" #include <numeric> #include <stdexcept> #include <string> using namespace std; namespace { const string subhorz(13, '-'); const string subhorz2(13, ' '); const string horz = "+" + subhorz + "+" + subhorz + "+" + subhorz + "+"; const string horz2 = "|" + subhorz2 + "|" + subhorz2 + "|" + subhorz2 + "|"; const string vert(11, '|'); } // namespace const SudokuGrid::set_t SudokuGrid::EMPTY; const SudokuGrid::set_t SudokuGrid::U{ makeRange<SudokuGrid::value_t>(1, SudokuGrid::ORDER2 + 1)}; ostream &operator<<(ostream &os, const SudokuGrid &sdkg) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if ((col != 0) && (col % SudokuGrid::ORDER == 0)) { os << "|"; } if (!sdkg.cellIsSolved(row, col)) { os << " . "; } else { os << " " << sdkg._cell[row][col] << " "; } } os << endl; if ((row != SudokuGrid::ORDER2 - 1) && (row % SudokuGrid::ORDER == (SudokuGrid::ORDER - 1))) { // @TODO Remove magic number os << string(29, '-') << endl; } } os << endl; return os; } std::istream &operator>>(std::istream &is, SudokuGrid &sdkg) { int value{0}; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { is >> value; sdkg.add(value, row, col); } } sdkg.calculateAllCellCandidates(); return is; } void writeCandidates(std::ostream &os, const SudokuGrid &sdkg) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (col == 0 && row % SudokuGrid::ORDER == 0 && row < SudokuGrid::ORDER2 - 1) { os << horz; if (row == 0) { os << " ID = " << &sdkg << " " << sdkg.getID() << " " << (sdkg.isSolvable() ? "" : " not solvable"); } os << endl << horz2 << endl; } if (col == 0) { os << "| "; } SudokuGrid::set_t candidates = sdkg.getCellCandidates(row, col); for (SudokuGrid::value_t v = 1; v <= SudokuGrid::ORDER; ++v) { if (isAnElementOf(v, candidates)) { os << v; } else { candidates == SudokuGrid::EMPTY ? os << ' ' : os << '.'; } } if ((col != 0) && (col % SudokuGrid::ORDER == 2)) { os << " | "; } else { os << " "; } } os << endl; for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (col == 0) { os << "| "; } int pos{-1}; SudokuGrid::set_t candidates{sdkg.getCellCandidates(row, col)}; for (SudokuGrid::value_t v = SudokuGrid::ORDER + 1; v <= 2 * SudokuGrid::ORDER; ++v) { if (isAnElementOf(v, candidates)) { os << v; } else { if (candidates == SudokuGrid::EMPTY) { ++pos; (pos == 1) ? os << sdkg._cell[row][col] : os << ' '; } else { os << '.'; } } } if ((col != 0) && (col % SudokuGrid::ORDER == 2)) { os << " | "; } else { os << " "; } } os << endl; for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (col == 0) { os << "| "; } SudokuGrid::set_t candidates{sdkg.getCellCandidates(row, col)}; for (SudokuGrid::value_t v = 2 * SudokuGrid::ORDER + 1; v < 3 * SudokuGrid::ORDER + 1; ++v) { if (isAnElementOf(v, candidates)) { os << v; } else { candidates == SudokuGrid::EMPTY ? os << ' ' : os << '.'; } } if ((col != 0) && (col % SudokuGrid::ORDER == 2)) { os << " | "; } else { os << " "; } } os << endl << horz2 << endl; } os << horz << endl; } void writeLatex(std::ostream &os, const SudokuGrid &sdkg) { os << "\n\\begin{sudoku}\n"; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (!sdkg.cellIsSolved(row, col)) { os << "| "; } else { os << "|" << sdkg._cell[row][col]; } } os << "|.\n"; } os << "\\end{sudoku}\n\n"; } SudokuGrid::SudokuGrid() : _id{} , _numberOfCellsSolved{0} , _isSolvable{true} , _cell{{}} , _columnSet{{}} , _rowSet{{}} , _blockSet{{}} , _candidates{{}} , pRow{} , pColumn{} , pBlock{} { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int column = 0; column < SudokuGrid::ORDER2; ++column) { _candidates[row][column] = U; } } _columnSet.fill(U); _rowSet.fill(U); for (int row = 0; row < SudokuGrid::ORDER; ++row) { for (int column = 0; column < SudokuGrid::ORDER; ++column) { _blockSet[row][column] = U; } } mapPointerArraysToCandidates(); } SudokuGrid::SudokuGrid(const SudokuGrid &sdkg) : _id{sdkg._id} , _numberOfCellsSolved{sdkg._numberOfCellsSolved} , _isSolvable{sdkg._isSolvable} , _cell{{}} , _columnSet{{}} , _rowSet{{}} , _blockSet{{}} , _candidates{{}} , pRow{} , pColumn{} , pBlock{} { _cell = sdkg._cell; _columnSet = sdkg._columnSet; _rowSet = sdkg._rowSet; _blockSet = sdkg._blockSet; _candidates = sdkg._candidates; mapPointerArraysToCandidates(); // writeCandidates(cout, sdkg); // cout << "COPY" << endl; // writeCandidates(cout, *this); } SudokuGrid &SudokuGrid::operator=(const SudokuGrid &sdkg) { if (this != &sdkg) { _id = sdkg._id; _numberOfCellsSolved = sdkg._numberOfCellsSolved; _isSolvable = sdkg._isSolvable; _cell = sdkg._cell; _columnSet = sdkg._columnSet; _rowSet = sdkg._rowSet; _blockSet = sdkg._blockSet; _candidates = sdkg._candidates; mapPointerArraysToCandidates(); } return *this; } bool SudokuGrid::removeCandidates(const set_t &rem, int row, int column) { set_t candidates{_candidates[row][column]}; _candidates[row][column] = _candidates[row][column] - rem; return candidates != _candidates[row][column]; } void SudokuGrid::add(const value_t value, int row, int column) { if (isSolvable()) { if (isAnElementOf(value, SudokuGrid::U)) { // cout << "-- Add: " << Value << " in [" << Row << "][" << Column << // "]" << endl; if (isAnElementOf(value, _columnSet[column]) && isAnElementOf(value, _rowSet[row]) && isAnElementOf(value, _blockSet[row / SudokuGrid::ORDER] [column / SudokuGrid::ORDER])) { _columnSet[column].erase(value); _rowSet[row].erase(value); _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER] .erase(value); _candidates[row][column] = SudokuGrid::EMPTY; _cell[row][column] = value; ++_numberOfCellsSolved; } else { // cout << "ADD ERROR" << endl; // writeCandidates(cout, *this); // getchar(); throw std::logic_error( "-- [" + to_string(row) + "][" + to_string(column) + "] Sudoku element: " + to_string(value) + " not in groups"); } } else { if (value != 0) { throw std::logic_error("-- Sudoku element: " + to_string(value) + " must be in the range " "[1," + to_string(SudokuGrid::ORDER2) + "]"); } _cell[row][column] = 0; } calculateAllCellCandidates(); } else { cout << "ADD to not solvable sudoku grid " << getID() << endl; } } void SudokuGrid::unsafeAdd(const value_t value, int row, int column) { _columnSet[column].erase(value); _rowSet[row].erase(value); _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER].erase(value); _candidates[row][column] = SudokuGrid::EMPTY; _cell[row][column] = value; if (value != 0) { ++_numberOfCellsSolved; } calculateAllCellCandidates(); } //------------------------------------------------------------------------------ void SudokuGrid::calculateAllCellCandidates() { for (int row = 0; row < SudokuGrid::ORDER2 && _isSolvable; ++row) { for (int col = 0; col < SudokuGrid::ORDER2 && _isSolvable; ++col) { if (!cellIsSolved(row, col)) { _candidates[row][col] = calculateCellCandidates(row, col); if (_candidates[row][col].empty()) { _isSolvable = false; } } } } } SudokuGrid::set_t SudokuGrid::calculateCellCandidates(int row, int column) const { return _columnSet[column] * _rowSet[row] * _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER]; } void SudokuGrid::mapPointerArraysToCandidates() { for (int groupIndex = 0; groupIndex < SudokuGrid::ORDER2; ++groupIndex) { for (int index = 0; index < SudokuGrid::ORDER2; ++index) { pRow[groupIndex][index] = &_candidates[groupIndex][index]; pColumn[groupIndex][index] = &_candidates[index][groupIndex]; } } for (int blockIndex = 0; blockIndex < SudokuGrid::ORDER2; ++blockIndex) { int index = 0; int starti = SudokuGrid::ORDER * (blockIndex / SudokuGrid::ORDER); int startj = SudokuGrid::ORDER * (blockIndex % SudokuGrid::ORDER); for (int i = starti; i < starti + SudokuGrid::ORDER; ++i) { for (int j = startj; j < startj + SudokuGrid::ORDER; ++j) { pBlock[blockIndex][index++] = &_candidates[i][j]; } } } } <|endoftext|>
<commit_before>/** * @file VolumeData.cpp * @author Takashi Michikawa <michikawa@acm.org> */ #include <mi/VolumeData.hpp> namespace mi { template <typename T> class VolumeData<T>::Impl { public: Impl ( void ) : _isReadable ( false ) { return; } ~Impl ( void ) { return; } VolumeInfo& info ( void ) { return this->_info; } T& at ( const int x, const int y, const int z ) { return this->_data.at ( z ).at ( y ).at ( x ); } bool allocate ( void ) { if ( ! this->isReadable() ) { const Point3i& size = this->_info.getSize (); this->_isReadable = false; this->_data.assign ( size.z() , std::vector<std::vector<T> > ( size.y(), std::vector<T> ( size.x(), T() ) ) ); if ( this->_data.size() != static_cast<size_t> ( size.z() ) ) { return false; } this->_isReadable = true; } return true; } bool deallocate ( void ) { this->_data.erase ( this->_data.begin(), this->_data.end() ); this->_isReadable = false; return true; } bool isReadable ( void ) const { return this->_isReadable; } private: VolumeInfo _info; std::vector<std::vector<std::vector<T> > > _data; bool _isReadable; }; template <typename T> VolumeData<T>::VolumeData ( void ) : _impl ( new VolumeData<T>::Impl() ) { return; } template <typename T> VolumeData<T>::VolumeData ( const int x, const int y, const int z , const bool allocateMemory ) : _impl ( new VolumeData<T>::Impl() ) { const Point3i size ( x, y, z ); const VolumeInfo info ( size ); this->init ( info, allocateMemory ); return; } template <typename T> VolumeData<T>::VolumeData ( const Point3i& size, const bool allocateMemory ) : _impl ( new VolumeData<T>::Impl() ) { const VolumeInfo info ( size ); this->init ( info, allocateMemory ); return; } template <typename T> VolumeData<T>::VolumeData ( const VolumeInfo& info, const bool allocateMemory ) : _impl ( new VolumeData<T>::Impl() ) { this->init ( info, allocateMemory ); return; } template <typename T> VolumeData<T>::~VolumeData ( void ) { delete this->_impl; return; } template <typename T> VolumeData<T>& VolumeData<T>::init ( const Point3i& size, const bool allocateMemory ) { const VolumeInfo info ( size ); return this->init ( info, allocateMemory ); } template <typename T> VolumeData<T>& VolumeData<T>::init ( const VolumeInfo& info, const bool allocateMemory ) { this->deallocate(); this->getInfo().init ( info.getSize(), info.getPitch(), info.getOrigin() ); if ( allocateMemory ) { this->allocate(); } return *this; } template <typename T> VolumeData<T>& VolumeData<T>::fill ( const T& value ) { const Point3i& size = this->getInfo().getSize(); for ( int z = 0 ; z < size.z() ; ++z ) { for ( int y = 0 ; y < size.y() ; ++y ) { for ( int x = 0 ; x < size.x() ; ++x ) { this->set ( Point3i ( x, y, z ), value ); } } } return *this; } template <typename T> VolumeInfo& VolumeData<T>::getInfo ( void ) { return this->_impl->info(); } template <typename T> Point3i VolumeData<T>::getSize ( void ) { return this->getInfo().getSize(); } template <typename T> T VolumeData<T>::get ( const Point3i& p ) const { return this->get ( p.x(), p.y(), p.z() ); } template <typename T> T VolumeData<T>::get ( const int x, const int y, const int z ) const { return this->at ( x, y, z ); } template <typename T> void VolumeData<T>::set ( const Point3i& p, const T v ) { this->set ( p.x(), p.y(), p.z(), v ); return; } template <typename T> void VolumeData<T>::set ( const int x, const int y, const int z , const T v ) { this->at ( x, y, z ) = v; return; } template <typename T> T VolumeData<T>::at ( const Point3i& p ) const { return this->at ( p.x(), p.y(), p.z() ); } template <typename T> T& VolumeData<T>::at ( const Point3i& p ) { return this->at ( p.x(), p.y(), p.z() ); } template <typename T> T VolumeData<T>::at ( const int x, const int y, const int z ) const { return this->_impl->at ( x, y, z ); } template <typename T> T& VolumeData<T>::at ( const int x, const int y, const int z ) { return this->_impl->at ( x, y, z ); } template <typename T> void VolumeData<T>::clear ( void ) { this->fill ( T() ); return; } template <typename T> bool <<<<<<< HEAD VolumeData<T>::clone( const VolumeData<T>& that ) { // if ( that.getSize() != this->getSize() ) return false; const VolumeInfo & info = const_cast<VolumeData<T>&>(that).getInfo(); this->init( info, true); ======= VolumeData<T>::clone ( VolumeData<T>& that ) { if ( that.getSize() != this->getSize() ) { return false; } >>>>>>> 2b01e826d640dc4b42cc9e2e2be17c33824421c2 const Point3i& size = this->getSize(); for ( int z = 0 ; z < size.z() ; ++z ) { for ( int y = 0 ; y < size.y() ; ++y ) { for ( int x = 0 ; x < size.x() ; ++x ) { this->set ( x, y, z, that.get ( x, y, z ) ); } } } return true; } template <typename T> bool VolumeData<T>::allocate ( void ) { return this->_impl->allocate(); } template <typename T> bool VolumeData<T>::deallocate ( void ) { this->_impl->deallocate(); return true; } template <typename T> bool VolumeData<T>::isReadable ( void ) const { return this->_impl->isReadable(); } /* template <typename T> VolumeData<T>::iterator VolumeData<T>::begin( void ) { return VolumeData<T>::iterator( &( this->_data ), true ); } template <typename T> VolumeData<T>::iterator VolumeData<T>::end( void ) { return VolumeData<T>::iterator( &( this->_data ), false ); } */ template <typename T> std::string VolumeData<T>::createFileName ( const std::string& name, const std::string& ext ) { const Point3i& size = this->getInfo().getSize(); const Point3d& pitch = this->getInfo().getPitch(); std::stringstream ss; ss << name << "-" << size.x() << "x" << size.y() << "x" << size.z() << "-" << pitch.x() << "x" << pitch.y() << "x" << pitch.z() << "." << ext; return ss.str(); } #define VOLUME_DATA(TYPE) template class VolumeData<TYPE>; VOLUME_DATA ( unsigned char ); VOLUME_DATA ( char ); VOLUME_DATA ( unsigned short ); VOLUME_DATA ( short ); VOLUME_DATA ( unsigned int ); VOLUME_DATA ( int ); VOLUME_DATA ( float ); VOLUME_DATA ( double ); // VOLUME_DATA( uint8_t ); // VOLUME_DATA( int8_t ); // VOLUME_DATA( uint16_t ); // VOLUME_DATA( int16_t ); // VOLUME_DATA( uint32_t ); // VOLUME_DATA( int32_t ); // VOLUME_DATA( uint64_t ); // VOLUME_DATA( int64_t ); VOLUME_DATA ( mi::Vector3s ); } <commit_msg> snapshot<commit_after>/** * @file VolumeData.cpp * @author Takashi Michikawa <michikawa@acm.org> */ #include <mi/VolumeData.hpp> namespace mi { template <typename T> class VolumeData<T>::Impl { public: Impl ( void ) : _isReadable ( false ) { return; } ~Impl ( void ) { return; } VolumeInfo& info ( void ) { return this->_info; } T& at ( const int x, const int y, const int z ) { return this->_data.at ( z ).at ( y ).at ( x ); } bool allocate ( void ) { if ( ! this->isReadable() ) { const Point3i& size = this->_info.getSize (); this->_isReadable = false; this->_data.assign ( size.z() , std::vector<std::vector<T> > ( size.y(), std::vector<T> ( size.x(), T() ) ) ); if ( this->_data.size() != static_cast<size_t> ( size.z() ) ) { return false; } this->_isReadable = true; } return true; } bool deallocate ( void ) { this->_data.erase ( this->_data.begin(), this->_data.end() ); this->_isReadable = false; return true; } bool isReadable ( void ) const { return this->_isReadable; } private: VolumeInfo _info; std::vector<std::vector<std::vector<T> > > _data; bool _isReadable; }; template <typename T> VolumeData<T>::VolumeData ( void ) : _impl ( new VolumeData<T>::Impl() ) { return; } template <typename T> VolumeData<T>::VolumeData ( const int x, const int y, const int z , const bool allocateMemory ) : _impl ( new VolumeData<T>::Impl() ) { const Point3i size ( x, y, z ); const VolumeInfo info ( size ); this->init ( info, allocateMemory ); return; } template <typename T> VolumeData<T>::VolumeData ( const Point3i& size, const bool allocateMemory ) : _impl ( new VolumeData<T>::Impl() ) { const VolumeInfo info ( size ); this->init ( info, allocateMemory ); return; } template <typename T> VolumeData<T>::VolumeData ( const VolumeInfo& info, const bool allocateMemory ) : _impl ( new VolumeData<T>::Impl() ) { this->init ( info, allocateMemory ); return; } template <typename T> VolumeData<T>::~VolumeData ( void ) { delete this->_impl; return; } template <typename T> VolumeData<T>& VolumeData<T>::init ( const Point3i& size, const bool allocateMemory ) { const VolumeInfo info ( size ); return this->init ( info, allocateMemory ); } template <typename T> VolumeData<T>& VolumeData<T>::init ( const VolumeInfo& info, const bool allocateMemory ) { this->deallocate(); this->getInfo().init ( info.getSize(), info.getPitch(), info.getOrigin() ); if ( allocateMemory ) { this->allocate(); } return *this; } template <typename T> VolumeData<T>& VolumeData<T>::fill ( const T& value ) { const Point3i& size = this->getInfo().getSize(); for ( int z = 0 ; z < size.z() ; ++z ) { for ( int y = 0 ; y < size.y() ; ++y ) { for ( int x = 0 ; x < size.x() ; ++x ) { this->set ( Point3i ( x, y, z ), value ); } } } return *this; } template <typename T> VolumeInfo& VolumeData<T>::getInfo ( void ) { return this->_impl->info(); } template <typename T> Point3i VolumeData<T>::getSize ( void ) { return this->getInfo().getSize(); } template <typename T> T VolumeData<T>::get ( const Point3i& p ) const { return this->get ( p.x(), p.y(), p.z() ); } template <typename T> T VolumeData<T>::get ( const int x, const int y, const int z ) const { return this->at ( x, y, z ); } template <typename T> void VolumeData<T>::set ( const Point3i& p, const T v ) { this->set ( p.x(), p.y(), p.z(), v ); return; } template <typename T> void VolumeData<T>::set ( const int x, const int y, const int z , const T v ) { this->at ( x, y, z ) = v; return; } template <typename T> T VolumeData<T>::at ( const Point3i& p ) const { return this->at ( p.x(), p.y(), p.z() ); } template <typename T> T& VolumeData<T>::at ( const Point3i& p ) { return this->at ( p.x(), p.y(), p.z() ); } template <typename T> T VolumeData<T>::at ( const int x, const int y, const int z ) const { return this->_impl->at ( x, y, z ); } template <typename T> T& VolumeData<T>::at ( const int x, const int y, const int z ) { return this->_impl->at ( x, y, z ); } template <typename T> void VolumeData<T>::clear ( void ) { this->fill ( T() ); return; } template <typename T> bool VolumeData<T>::clone( const VolumeData<T>& that ) { const VolumeInfo & info = const_cast<VolumeData<T>&>(that).getInfo(); this->init( info, true); const Point3i& size = this->getSize(); for ( int z = 0 ; z < size.z() ; ++z ) { for ( int y = 0 ; y < size.y() ; ++y ) { for ( int x = 0 ; x < size.x() ; ++x ) { this->set ( x, y, z, that.get ( x, y, z ) ); } } } return true; } template <typename T> bool VolumeData<T>::allocate ( void ) { return this->_impl->allocate(); } template <typename T> bool VolumeData<T>::deallocate ( void ) { this->_impl->deallocate(); return true; } template <typename T> bool VolumeData<T>::isReadable ( void ) const { return this->_impl->isReadable(); } /* template <typename T> VolumeData<T>::iterator VolumeData<T>::begin( void ) { return VolumeData<T>::iterator( &( this->_data ), true ); } template <typename T> VolumeData<T>::iterator VolumeData<T>::end( void ) { return VolumeData<T>::iterator( &( this->_data ), false ); } */ template <typename T> std::string VolumeData<T>::createFileName ( const std::string& name, const std::string& ext ) { const Point3i& size = this->getInfo().getSize(); const Point3d& pitch = this->getInfo().getPitch(); std::stringstream ss; ss << name << "-" << size.x() << "x" << size.y() << "x" << size.z() << "-" << pitch.x() << "x" << pitch.y() << "x" << pitch.z() << "." << ext; return ss.str(); } #define VOLUME_DATA(TYPE) template class VolumeData<TYPE>; VOLUME_DATA ( unsigned char ); VOLUME_DATA ( char ); VOLUME_DATA ( unsigned short ); VOLUME_DATA ( short ); VOLUME_DATA ( unsigned int ); VOLUME_DATA ( int ); VOLUME_DATA ( float ); VOLUME_DATA ( double ); // VOLUME_DATA( uint8_t ); // VOLUME_DATA( int8_t ); // VOLUME_DATA( uint16_t ); // VOLUME_DATA( int16_t ); // VOLUME_DATA( uint32_t ); // VOLUME_DATA( int32_t ); // VOLUME_DATA( uint64_t ); // VOLUME_DATA( int64_t ); VOLUME_DATA ( mi::Vector3s ); } <|endoftext|>
<commit_before>// // Created by ante on 10/28/16. // #include "algorithms.h" #include <iostream> #include <malloc.h> #include <queue> #include "divsufsort.h" using namespace std; /** * Function compute number of occurrences letters smaller than 'c' from alphabet defined at 'bigSigma'. * @param c: letter for searching number of all occurrances letters that are before 'c' in ordered alphaber 'bigSigma' * @return: int that represent number of occurrances * */ int computeNumberOfOccurrencesLetterSmallerThenC(const Alphabet &a, const BWTree &bwt, char c) { int index = a[c]; // index of char c int sum = 0; for (int i = 0; i < index; ++i) sum += bwt.get_symbol_count(a[i]); //number of occurrences letter bigSigma[i] in string S return sum; } /** * Function return number of occurrances bool value 'identity' in 'bitVec' in interval [start, end>. * @param identity: bool that represent value that we count in bitVector. It can be false(0) or true(1). * @param bitVec: indicator vector that tell us whatever char c goes in left or right subtree * @return: value that represents number of 'identity' value in bitVector * */ int rankFun(bool identity, const bitvector &bitVec, int start, int end) { int sum = 0; for (int i = start; i < end; ++i) sum += bitVec[i] == identity ? 1 : 0; return sum; } /** * Recurisve function that we need to compute all c-omega intervals. * @param bwt: bwt form what we try to get all c-omega intervals * @param ij: interval of bwt that we give to function * @param lr: interval of subalphabet * @param list: list of all c-omega intervals of given bwt * */ void getIntervalsRec(const Alphabet &a, const BWTree &bwt, int indexOfNode, interval &ij, interval &lr, std::vector<interval> &list) { if (lr.first == lr.second) { char c = a[lr.first]; int Cc = computeNumberOfOccurrencesLetterSmallerThenC(a, bwt, c); list.push_back(make_pair(Cc + ij.first, Cc + ij.second)); } else { int m = (lr.first + lr.second) / 2; auto &bitVec = bwt.get_bitvector_for_index(indexOfNode); int a0 = rankFun(0, bitVec, 0, ij.first - 1); int b0 = a0 + rankFun(0, bitVec, ij.first - 1, ij.second); int a1 = ij.first - 1 - a0; int b1 = ij.second - b0; if (b0 > a0) { interval int1 = make_pair(a0 + 1, b0); interval int2 = make_pair(lr.first, m); getIntervalsRec(a, bwt, indexOfNode * 2, int1, int2, list); } if (b1 > a1) { interval int1 = make_pair(a1 + 1, b1); interval int2 = make_pair(m + 1, lr.second); getIntervalsRec(a, bwt, indexOfNode * 2 + 1, int1, int2, list); } } } /** * Function that accept interval ij as argument and retunr all c-omega intervals. * @param ij: interval form which we want to get all c-omega subintervals * @return: all c-omega intervals * */ std::vector<interval> getIntervals(const Alphabet &a, const BWTree &bwt, interval ij) { std::vector<interval> list; interval alp = make_pair(0, a.length()); // func that compute all subinterval getIntervalsRec(a, bwt, 1, ij, alp, list); return list; } std::string bw_transformation(std::string S) { std::string BWTrans = std::string(); auto n = S.length(); int *SA = (int *) malloc(n * sizeof(int)); BWTrans.resize(n); // sort divsufsort((const unsigned char *) S.c_str(), SA, static_cast<int>(S.length()), 0); for (auto i = 0u, tmp = 0u; i < n; ++i) { tmp = SA[i]; BWTrans[i] = tmp == 0 ? '$' : S[tmp - 1]; } free(SA); return BWTrans; } vector<int> calculate_lcp(string s) { string BWTrans = bw_transformation(s); Alphabet a(s, true); BWTree bwt(BWTrans, a); auto n = s.length(); const int bottom = -2; vector<int> lcp(n + 1, bottom); lcp[0] = lcp[n] = -1; queue<pair<interval, int>> q; q.push(make_pair(make_pair(1, n), 0)); cout << "BWTrans:" << endl; cout << BWTrans << endl; cout << "BWTree:" << endl; cout << bwt.show() << endl; for (; !q.empty(); q.pop()) { auto dq = q.front(); auto list = (vector<interval> &&) getIntervals(a, bwt, dq.first); for (auto interv : list) { // NB: interval indices start from 1, but indexing in arrays starts from 0; hence we use interv.second not interv.second+1 if (lcp[interv.second] == bottom) { q.push(make_pair(interv, dq.second + 1)); lcp[interv.second] = dq.second; } } pretty_print(lcp); } return lcp; } <commit_msg>Debug getIntervals<commit_after>// // Created by ante on 10/28/16. // #include "algorithms.h" #include <iostream> #include <malloc.h> #include <queue> #include "divsufsort.h" using namespace std; /** * Function compute number of occurrences letters smaller than 'c' from alphabet defined at 'bigSigma'. * @param c: letter for searching number of all occurrances letters that are before 'c' in ordered alphaber 'bigSigma' * @return: int that represent number of occurrances * */ int computeNumberOfOccurrencesLetterSmallerThenC(const Alphabet &a, const BWTree &bwt, char c) { int index = a[c]; // index of char c int sum = 0; for (int i = 0; i < index; ++i) sum += bwt.get_symbol_count(a[i]); //number of occurrences letter bigSigma[i] in string S return sum; } /** * Function return number of occurrances bool value 'identity' in 'bitVec' in interval [start, end>. * @param identity: bool that represent value that we count in bitVector. It can be false(0) or true(1). * @param bitVec: indicator vector that tell us whatever char c goes in left or right subtree * @return: value that represents number of 'identity' value in bitVector * */ int rankFun(bool identity, const bitvector &bitVec, int start, int end) { int sum = 0; for (int i = start; i < end; ++i) sum += bitVec[i] == identity ? 1 : 0; return sum; } /** * Recurisve function that we need to compute all c-omega intervals. * @param bwt: bwt form what we try to get all c-omega intervals * @param ij: interval of bwt that we give to function * @param lr: interval of subalphabet * @param list: list of all c-omega intervals of given bwt * */ void getIntervalsRec(const Alphabet &a, const BWTree &bwt, int indexOfNode, interval &ij, interval &lr, std::vector<interval> &list) { if (lr.first == lr.second) { char c = a[lr.first]; int Cc = computeNumberOfOccurrencesLetterSmallerThenC(a, bwt, c); list.push_back(make_pair(Cc + ij.first, Cc + ij.second)); } else { int m = (lr.first + lr.second) / 2; auto &bitVec = bwt.get_bitvector_for_index(indexOfNode); int a0 = rankFun(0, bitVec, 0, ij.first - 1); int b0 = a0 + rankFun(0, bitVec, ij.first - 1, ij.second); int a1 = ij.first - 1 - a0; int b1 = ij.second - b0; if (b0 > a0) { interval int1 = make_pair(a0 + 1, b0); interval int2 = make_pair(lr.first, m); getIntervalsRec(a, bwt, indexOfNode * 2, int1, int2, list); } if (b1 > a1) { interval int1 = make_pair(a1 + 1, b1); interval int2 = make_pair(m + 1, lr.second); getIntervalsRec(a, bwt, indexOfNode * 2 + 1, int1, int2, list); } } } /** * Function that accept interval ij as argument and retunr all c-omega intervals. * @param ij: interval form which we want to get all c-omega subintervals * @return: all c-omega intervals * */ std::vector<interval> getIntervals(const Alphabet &a, const BWTree &bwt, interval ij) { std::vector<interval> list; interval alp = make_pair(0, a.length()); // func that compute all subinterval getIntervalsRec(a, bwt, 1, ij, alp, list); return list; } std::string bw_transformation(std::string S) { std::string BWTrans = std::string(); auto n = S.length(); int *SA = (int *) malloc(n * sizeof(int)); BWTrans.resize(n); // sort divsufsort((const unsigned char *) S.c_str(), SA, static_cast<int>(S.length()), 0); for (auto i = 0u, tmp = 0u; i < n; ++i) { tmp = SA[i]; BWTrans[i] = tmp == 0 ? '$' : S[tmp - 1]; } free(SA); return BWTrans; } vector<int> calculate_lcp(string s) { string BWTrans = bw_transformation(s); Alphabet a(s, true); BWTree bwt(BWTrans, a); auto n = s.length(); const int bottom = -2; vector<int> lcp(n + 1, bottom); lcp[0] = lcp[n] = -1; queue<pair<interval, int>> q; q.push(make_pair(make_pair(1, n), 0)); cout << "BWTrans:" << endl; cout << BWTrans << endl; cout << "BWTree:" << endl; cout << bwt.show() << endl; for (; !q.empty(); q.pop()) { auto dq = q.front(); cout << "q: " << dq.first.first << ", " << dq.first.second << endl; auto list = getIntervals(a, bwt, dq.first); for (auto interv : list) { cout << interv.first << ", " << interv.second << endl; // NB: interval indices start from 1, but indexing in arrays starts from 0; hence we use interv.second not interv.second+1 if (lcp[interv.second] == bottom) { q.push(make_pair(interv, dq.second + 1)); lcp[interv.second] = dq.second; } } pretty_print(lcp); } return lcp; } <|endoftext|>
<commit_before>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/api/app/app.h" #include "base/command_line.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/values.h" #include "content/nw/src/api/api_messages.h" #include "content/nw/src/browser/net_disk_cache_remover.h" #include "content/nw/src/nw_package.h" #include "content/nw/src/nw_shell.h" #include "content/nw/src/shell_browser_context.h" #include "content/common/view_messages.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/render_process_host.h" using base::MessageLoop; using content::Shell; using content::ShellBrowserContext; using content::RenderProcessHost; namespace api { namespace { // Get render process host. RenderProcessHost* GetRenderProcessHost() { RenderProcessHost* render_process_host = NULL; std::vector<Shell*> windows = Shell::windows(); for (size_t i = 0; i < windows.size(); ++i) { if (!windows[i]->is_devtools()) { render_process_host = windows[i]->web_contents()->GetRenderProcessHost(); break; } } return render_process_host; } void GetRenderProcessHosts(std::set<RenderProcessHost*>& rphs) { RenderProcessHost* render_process_host = NULL; std::vector<Shell*> windows = Shell::windows(); for (size_t i = 0; i < windows.size(); ++i) { if (!windows[i]->is_devtools()) { render_process_host = windows[i]->web_contents()->GetRenderProcessHost(); rphs.insert(render_process_host); } } } } // namespace // static void App::Call(const std::string& method, const base::ListValue& arguments) { if (method == "Quit") { Quit(); return; } else if (method == "CloseAllWindows") { CloseAllWindows(); return; } NOTREACHED() << "Calling unknown method " << method << " of App"; } // static void App::Call(Shell* shell, const std::string& method, const base::ListValue& arguments, base::ListValue* result) { if (method == "GetDataPath") { ShellBrowserContext* browser_context = static_cast<ShellBrowserContext*>(shell->web_contents()->GetBrowserContext()); result->AppendString(browser_context->GetPath().value()); return; }else if (method == "GetArgv") { nw::Package* package = shell->GetPackage(); CommandLine* command_line = CommandLine::ForCurrentProcess(); CommandLine::StringVector args = command_line->GetArgs(); CommandLine::StringVector argv = command_line->original_argv(); // Ignore first non-switch arg if it's not a standalone package. bool ignore_arg = !package->self_extract(); for (unsigned i = 1; i < argv.size(); ++i) { if (ignore_arg && argv[i] == args[0]) { ignore_arg = false; continue; } result->AppendString(argv[i]); } return; } else if (method == "ClearCache") { ClearCache(GetRenderProcessHost()); } else if (method == "GetPackage") { result->AppendString(shell->GetPackage()->package_string()); return; } NOTREACHED() << "Calling unknown sync method " << method << " of App"; } // static void App::CloseAllWindows(bool force) { std::vector<Shell*> windows = Shell::windows(); for (size_t i = 0; i < windows.size(); ++i) { // Only send close event to browser windows, since devtools windows will // be automatically closed. if (!windows[i]->is_devtools()) { // If there is no js object bound to the window, then just close. if (force || windows[i]->ShouldCloseWindow()) delete windows[i]; } } } // static void App::Quit(RenderProcessHost* render_process_host) { // Send the quit message. int no_use; if (render_process_host) { render_process_host->Send(new ViewMsg_WillQuit(&no_use)); }else{ std::set<RenderProcessHost*> rphs; std::set<RenderProcessHost*>::iterator it; GetRenderProcessHosts(rphs); for (it = rphs.begin(); it != rphs.end(); it++) { RenderProcessHost* rph = *it; DCHECK(rph != NULL); rph->Send(new ViewMsg_WillQuit(&no_use)); } CloseAllWindows(true); } // Then quit. MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); } // static void App::EmitOpenEvent(const std::string& path) { std::set<RenderProcessHost*> rphs; std::set<RenderProcessHost*>::iterator it; GetRenderProcessHosts(rphs); for (it = rphs.begin(); it != rphs.end(); it++) { RenderProcessHost* rph = *it; DCHECK(rph != NULL); rph->Send(new ShellViewMsg_Open(path)); } } void App::ClearCache(content::RenderProcessHost* render_process_host) { render_process_host->Send(new ShellViewMsg_ClearCache()); nw::RemoveHttpDiskCache(render_process_host->GetBrowserContext(), render_process_host->GetID()); } } // namespace api <commit_msg>Fix #486: should delete Shell object on native window destruction<commit_after>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/api/app/app.h" #include "base/command_line.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/values.h" #include "content/nw/src/api/api_messages.h" #include "content/nw/src/browser/native_window.h" #include "content/nw/src/browser/net_disk_cache_remover.h" #include "content/nw/src/nw_package.h" #include "content/nw/src/nw_shell.h" #include "content/nw/src/shell_browser_context.h" #include "content/common/view_messages.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/render_process_host.h" using base::MessageLoop; using content::Shell; using content::ShellBrowserContext; using content::RenderProcessHost; namespace api { namespace { // Get render process host. RenderProcessHost* GetRenderProcessHost() { RenderProcessHost* render_process_host = NULL; std::vector<Shell*> windows = Shell::windows(); for (size_t i = 0; i < windows.size(); ++i) { if (!windows[i]->is_devtools()) { render_process_host = windows[i]->web_contents()->GetRenderProcessHost(); break; } } return render_process_host; } void GetRenderProcessHosts(std::set<RenderProcessHost*>& rphs) { RenderProcessHost* render_process_host = NULL; std::vector<Shell*> windows = Shell::windows(); for (size_t i = 0; i < windows.size(); ++i) { if (!windows[i]->is_devtools()) { render_process_host = windows[i]->web_contents()->GetRenderProcessHost(); rphs.insert(render_process_host); } } } } // namespace // static void App::Call(const std::string& method, const base::ListValue& arguments) { if (method == "Quit") { Quit(); return; } else if (method == "CloseAllWindows") { CloseAllWindows(); return; } NOTREACHED() << "Calling unknown method " << method << " of App"; } // static void App::Call(Shell* shell, const std::string& method, const base::ListValue& arguments, base::ListValue* result) { if (method == "GetDataPath") { ShellBrowserContext* browser_context = static_cast<ShellBrowserContext*>(shell->web_contents()->GetBrowserContext()); result->AppendString(browser_context->GetPath().value()); return; }else if (method == "GetArgv") { nw::Package* package = shell->GetPackage(); CommandLine* command_line = CommandLine::ForCurrentProcess(); CommandLine::StringVector args = command_line->GetArgs(); CommandLine::StringVector argv = command_line->original_argv(); // Ignore first non-switch arg if it's not a standalone package. bool ignore_arg = !package->self_extract(); for (unsigned i = 1; i < argv.size(); ++i) { if (ignore_arg && argv[i] == args[0]) { ignore_arg = false; continue; } result->AppendString(argv[i]); } return; } else if (method == "ClearCache") { ClearCache(GetRenderProcessHost()); } else if (method == "GetPackage") { result->AppendString(shell->GetPackage()->package_string()); return; } NOTREACHED() << "Calling unknown sync method " << method << " of App"; } // static void App::CloseAllWindows(bool force) { std::vector<Shell*> windows = Shell::windows(); for (size_t i = 0; i < windows.size(); ++i) { // Only send close event to browser windows, since devtools windows will // be automatically closed. if (!windows[i]->is_devtools()) { // If there is no js object bound to the window, then just close. if (force || windows[i]->ShouldCloseWindow()) // we used to delete the Shell object here // but it should be deleted on native window destruction windows[i]->window()->Close(); } } } // static void App::Quit(RenderProcessHost* render_process_host) { // Send the quit message. int no_use; if (render_process_host) { render_process_host->Send(new ViewMsg_WillQuit(&no_use)); }else{ std::set<RenderProcessHost*> rphs; std::set<RenderProcessHost*>::iterator it; GetRenderProcessHosts(rphs); for (it = rphs.begin(); it != rphs.end(); it++) { RenderProcessHost* rph = *it; DCHECK(rph != NULL); rph->Send(new ViewMsg_WillQuit(&no_use)); } CloseAllWindows(true); } // Then quit. MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); } // static void App::EmitOpenEvent(const std::string& path) { std::set<RenderProcessHost*> rphs; std::set<RenderProcessHost*>::iterator it; GetRenderProcessHosts(rphs); for (it = rphs.begin(); it != rphs.end(); it++) { RenderProcessHost* rph = *it; DCHECK(rph != NULL); rph->Send(new ShellViewMsg_Open(path)); } } void App::ClearCache(content::RenderProcessHost* render_process_host) { render_process_host->Send(new ShellViewMsg_ClearCache()); nw::RemoveHttpDiskCache(render_process_host->GetBrowserContext(), render_process_host->GetID()); } } // namespace api <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite 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 <QtTest/QtTest> #include <qsystemlock.h> //TESTED_CLASS= //TESTED_FILES= #ifdef Q_OS_SYMBIAN // In Symbian OS test data is located in applications private dir // And underlying Open C have application private dir in default search path #define SRCDIR "" #endif #define EXISTING_SHARE "existing" class tst_QSystemLock : public QObject { Q_OBJECT public: tst_QSystemLock(); virtual ~tst_QSystemLock(); public Q_SLOTS: void init(); void cleanup(); private slots: void key_data(); void key(); void basicLock(); void complexLock(); void lockModes(); void sucessive(); void processes_data(); void processes(); private: QSystemLock *existingLock; }; tst_QSystemLock::tst_QSystemLock() { } tst_QSystemLock::~tst_QSystemLock() { } void tst_QSystemLock::init() { existingLock = new QSystemLock(EXISTING_SHARE); } void tst_QSystemLock::cleanup() { delete existingLock; } void tst_QSystemLock::key_data() { QTest::addColumn<QString>("constructorKey"); QTest::addColumn<QString>("setKey"); QTest::newRow("null, null") << QString() << QString(); QTest::newRow("null, one") << QString() << QString("one"); QTest::newRow("one, two") << QString("one") << QString("two"); } /*! Basic key testing */ void tst_QSystemLock::key() { QFETCH(QString, constructorKey); QFETCH(QString, setKey); QSystemLock sl(constructorKey); QCOMPARE(sl.key(), constructorKey); sl.setKey(setKey); QCOMPARE(sl.key(), setKey); } void tst_QSystemLock::basicLock() { QSystemLock lock("foo"); QVERIFY(lock.lock()); QVERIFY(lock.unlock()); } void tst_QSystemLock::complexLock() { QSystemLock lock("foo"); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.unlock()); QVERIFY(lock.lock(QSystemLock::ReadWrite)); QVERIFY(lock.unlock()); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); } void tst_QSystemLock::lockModes() { QSystemLock reader1("library"); QSystemLock reader2("library"); QSystemLock librarian("library"); QVERIFY(reader1.lock(QSystemLock::ReadOnly)); QVERIFY(reader2.lock(QSystemLock::ReadOnly)); QVERIFY(reader1.unlock()); QVERIFY(reader2.unlock()); QVERIFY(librarian.lock(QSystemLock::ReadWrite)); QVERIFY(librarian.unlock()); } void tst_QSystemLock::sucessive() { QSystemLock lock("library"); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); QVERIFY(!lock.unlock()); } void tst_QSystemLock::processes_data() { QTest::addColumn<int>("readOnly"); QTest::addColumn<int>("readWrite"); for (int i = 0; i < 5; ++i) { QTest::newRow("1/0 process") << 1 << 0; QTest::newRow("0/1 process") << 0 << 1; QTest::newRow("0/4 process") << 0 << 4; QTest::newRow("1/1 process") << 1 << 1; QTest::newRow("10/1 process") << 10 << 1; QTest::newRow("1/10 process") << 1 << 10; QTest::newRow("10/10 processes") << 10 << 10; } } /*! Create external processes */ void tst_QSystemLock::processes() { QFETCH(int, readOnly); QFETCH(int, readWrite); QStringList scripts; for (int i = 0; i < readOnly; ++i) scripts.append(QFileInfo(SRCDIR "lackey/scripts/ systemlock_read.js").absoluteFilePath() ); for (int i = 0; i < readWrite; ++i) scripts.append(QFileInfo(SRCDIR "lackey/scripts/systemlock_readwrite.js").absoluteFilePath()); QList<QProcess*> consumers; unsigned int failedProcesses = 0; for (int i = 0; i < scripts.count(); ++i) { QStringList arguments = QStringList() << scripts.at(i); QProcess *p = new QProcess; p->setProcessChannelMode(QProcess::ForwardedChannels); p->start(QFileInfo(SRCDIR "lackey/lackey").absoluteFilePath(), arguments); // test, if the process could be started. if (p->waitForStarted(2000)) consumers.append(p); else ++failedProcesses; } while (!consumers.isEmpty()) { consumers.first()->waitForFinished(3000); consumers.first()->kill(); QCOMPARE(consumers.first()->exitStatus(), QProcess::NormalExit); QCOMPARE(consumers.first()->exitCode(), 0); delete consumers.takeFirst(); } QCOMPARE(failedProcesses, (unsigned int)(0)); } QTEST_MAIN(tst_QSystemLock) #include "tst_qsystemlock.moc" <commit_msg>Fix tst_QSystemLock::processes<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite 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 <QtTest/QtTest> #include <qsystemlock.h> //TESTED_CLASS= //TESTED_FILES= #ifdef Q_OS_SYMBIAN // In Symbian OS test data is located in applications private dir // And underlying Open C have application private dir in default search path #define SRCDIR "" #endif #define EXISTING_SHARE "existing" class tst_QSystemLock : public QObject { Q_OBJECT public: tst_QSystemLock(); virtual ~tst_QSystemLock(); public Q_SLOTS: void init(); void cleanup(); private slots: void key_data(); void key(); void basicLock(); void complexLock(); void lockModes(); void sucessive(); void processes_data(); void processes(); private: QSystemLock *existingLock; }; tst_QSystemLock::tst_QSystemLock() { } tst_QSystemLock::~tst_QSystemLock() { } void tst_QSystemLock::init() { existingLock = new QSystemLock(EXISTING_SHARE); } void tst_QSystemLock::cleanup() { delete existingLock; } void tst_QSystemLock::key_data() { QTest::addColumn<QString>("constructorKey"); QTest::addColumn<QString>("setKey"); QTest::newRow("null, null") << QString() << QString(); QTest::newRow("null, one") << QString() << QString("one"); QTest::newRow("one, two") << QString("one") << QString("two"); } /*! Basic key testing */ void tst_QSystemLock::key() { QFETCH(QString, constructorKey); QFETCH(QString, setKey); QSystemLock sl(constructorKey); QCOMPARE(sl.key(), constructorKey); sl.setKey(setKey); QCOMPARE(sl.key(), setKey); } void tst_QSystemLock::basicLock() { QSystemLock lock("foo"); QVERIFY(lock.lock()); QVERIFY(lock.unlock()); } void tst_QSystemLock::complexLock() { QSystemLock lock("foo"); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.unlock()); QVERIFY(lock.lock(QSystemLock::ReadWrite)); QVERIFY(lock.unlock()); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); } void tst_QSystemLock::lockModes() { QSystemLock reader1("library"); QSystemLock reader2("library"); QSystemLock librarian("library"); QVERIFY(reader1.lock(QSystemLock::ReadOnly)); QVERIFY(reader2.lock(QSystemLock::ReadOnly)); QVERIFY(reader1.unlock()); QVERIFY(reader2.unlock()); QVERIFY(librarian.lock(QSystemLock::ReadWrite)); QVERIFY(librarian.unlock()); } void tst_QSystemLock::sucessive() { QSystemLock lock("library"); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.lock(QSystemLock::ReadOnly)); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); QVERIFY(lock.unlock()); QVERIFY(!lock.unlock()); } void tst_QSystemLock::processes_data() { QTest::addColumn<int>("readOnly"); QTest::addColumn<int>("readWrite"); for (int i = 0; i < 5; ++i) { QTest::newRow("1/0 process") << 1 << 0; QTest::newRow("0/1 process") << 0 << 1; QTest::newRow("0/4 process") << 0 << 4; QTest::newRow("1/1 process") << 1 << 1; QTest::newRow("10/1 process") << 10 << 1; QTest::newRow("1/10 process") << 1 << 10; QTest::newRow("10/10 processes") << 10 << 10; } } /*! Create external processes */ void tst_QSystemLock::processes() { QFETCH(int, readOnly); QFETCH(int, readWrite); QStringList scripts; for (int i = 0; i < readOnly; ++i) scripts.append(QFileInfo(SRCDIR "/../lackey/scripts/systemlock_read.js").absoluteFilePath() ); for (int i = 0; i < readWrite; ++i) scripts.append(QFileInfo(SRCDIR "/../lackey/scripts/systemlock_readwrite.js").absoluteFilePath()); QList<QProcess*> consumers; unsigned int failedProcesses = 0; for (int i = 0; i < scripts.count(); ++i) { QStringList arguments = QStringList() << scripts.at(i); QProcess *p = new QProcess; p->setProcessChannelMode(QProcess::ForwardedChannels); p->start("../lackey/lackey", arguments); // test, if the process could be started. if (p->waitForStarted(2000)) consumers.append(p); else ++failedProcesses; } while (!consumers.isEmpty()) { consumers.first()->waitForFinished(3000); consumers.first()->kill(); QCOMPARE(consumers.first()->exitStatus(), QProcess::NormalExit); QCOMPARE(consumers.first()->exitCode(), 0); delete consumers.takeFirst(); } QCOMPARE(failedProcesses, (unsigned int)(0)); } QTEST_MAIN(tst_QSystemLock) #include "tst_qsystemlock.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $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 <QtTest/QtTest> #include "qsysteminfo.h" QTM_USE_NAMESPACE class tst_QSystemDisplayInfo : public QObject { Q_OBJECT private slots: void tst_displayBrightness(); void tst_colorDepth(); // void tst_isScreenLockOn(); }; void tst_QSystemDisplayInfo::tst_displayBrightness() { QSystemDisplayInfo di; QVERIFY(di.displayBrightness(0) > -2); } void tst_QSystemDisplayInfo::tst_colorDepth() { QSystemDisplayInfo di; QVERIFY(di.colorDepth(0) > 0); } //void tst_QSystemDisplayInfo::tst_isScreenLockOn() //{ // QSystemDisplayInfo di; // bool lock = di.isScreenLockOn(); // QVERIFY(lock == true || lock == false); //} QTEST_MAIN(tst_QSystemDisplayInfo) #include "tst_qsystemdisplayinfo.moc" <commit_msg>allow 0 to be a true color depth.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $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 <QtTest/QtTest> #include "qsysteminfo.h" QTM_USE_NAMESPACE class tst_QSystemDisplayInfo : public QObject { Q_OBJECT private slots: void tst_displayBrightness(); void tst_colorDepth(); }; void tst_QSystemDisplayInfo::tst_displayBrightness() { QSystemDisplayInfo di; QVERIFY(di.displayBrightness(0) > -2); } void tst_QSystemDisplayInfo::tst_colorDepth() { QSystemDisplayInfo di; int depth = di.colorDepth(0); QVERIFY(depth == 0 || depth == 8 || depth == 16 || depth == 32 || depth == 64); } QTEST_MAIN(tst_QSystemDisplayInfo) #include "tst_qsystemdisplayinfo.moc" <|endoftext|>
<commit_before>#include "headers/dungeon_data.h" #define TAB "\t" using namespace std; string DungeonRoom::toString() { ostringstream sout; sout << "{" << endl; sout << TAB << TAB << TAB << "\"ID\":\"" << uid << "\"," << endl; sout << TAB << TAB << TAB << "\"Name\":\"" << name << "\"," << endl; sout << TAB << TAB << TAB << "\"Description\":\"" << description << "\"," << endl; sout << TAB << TAB << TAB << "\"Objects\":[" << endl; for (int i = 0; i < objects.size(); i++) { sout << TAB << TAB << TAB << TAB << "{" << objects[i]->toString() << "}," << endl; } sout << TAB << TAB << TAB << "]," << endl; sout << TAB << TAB << TAB << "\"Creatures\":[" << endl; for (int i = 0; i < creatures.size(); i++) { sout << TAB << TAB << TAB << TAB << "{" << creatures[i]->toString() << "}," << endl; } sout << TAB << TAB << TAB << "]," << endl; sout << TAB << TAB << TAB << "\"Exits\":[" << endl; for (int i = 0; i < exits.size(); i++) { sout << TAB << TAB << TAB << TAB << "{" << exits[i]->toString() << "}," << endl; } sout << TAB << TAB << TAB << "]" << endl; sout << TAB << TAB << "}" << endl; return sout.str(); } string DungeonExit::toString() { ostringstream sout; return sout.str(); } string DungeonObject::toString() { ostringstream sout; return sout.str(); } string DungeonCreature::toString() { ostringstream sout; return sout.str(); }<commit_msg>Now does one room JSON.<commit_after>#include "headers/dungeon_data.h" #define TAB "\t" using namespace std; string DungeonRoom::toString() { ostringstream sout; sout << "{" << endl; sout << TAB << TAB << TAB << "\"ID\":\"" << uid << "\"," << endl; sout << TAB << TAB << TAB << "\"Name\":\"" << name << "\"," << endl; sout << TAB << TAB << TAB << "\"Description\":\"" << description << "\"," << endl; sout << TAB << TAB << TAB << "\"Objects\":[" << endl; for (int i = 0; i < objects.size(); i++) { sout << TAB << TAB << TAB << TAB << "{" << objects[i]->toString() << "}," << endl; } sout << TAB << TAB << TAB << "]," << endl; sout << TAB << TAB << TAB << "\"Creatures\":[" << endl; for (int i = 0; i < creatures.size(); i++) { sout << TAB << TAB << TAB << TAB << "{" << creatures[i]->toString() << "}," << endl; } sout << TAB << TAB << TAB << "]," << endl; sout << TAB << TAB << TAB << "\"Exits\":[" << endl; for (int i = 0; i < exits.size(); i++) { sout << TAB << TAB << TAB << TAB << "{" << exits[i]->toString() << "}," << endl; } sout << TAB << TAB << TAB << "]" << endl; sout << TAB << TAB << "}" << endl; return sout.str(); } string DungeonExit::toString() { ostringstream sout; sout << "\"Name\":\"" << name << "\", \"Description\":\"" << description << "\", \"links\":" << room->uid; return sout.str(); } string DungeonObject::toString() { ostringstream sout; sout << "\"Name\":\"" << name << "\", \"Description\":\"" << description << "\""; return sout.str(); } string DungeonCreature::toString() { ostringstream sout; sout << "\"Name\":\"" << name << "\", \"Description\":\"" << description << "\", \"hitpoints\":" << hitpoints << ", \"Alignment\":" << alignment; return sout.str(); }<|endoftext|>
<commit_before> #include <QApplication> #include <QPixmap> #include <QImage> #include <QPainter> #include <QGLWidget> #include <QTextLayout> #include <QVBoxLayout> #include <QTime> #include <QDebug> #ifdef HAVE_STATICTEXT #include <private/qstatictext_p.h> #endif int iterations = 20; const int count = 6; const int lines = 12; const int spacing = 36; QSizeF size(1000, 800); const qreal lineWidth = 1000; QString strings[lines]; void paint_QTextLayout(QPainter &p, bool useCache) { static bool first = true; static QTextLayout *textLayout[lines]; if (first) { for (int i = 0; i < lines; ++i) { textLayout[i] = new QTextLayout(strings[i]); int leading = p.fontMetrics().leading(); qreal height = 0; qreal widthUsed = 0; textLayout[i]->setCacheEnabled(useCache); textLayout[i]->beginLayout(); while (1) { QTextLine line = textLayout[i]->createLine(); if (!line.isValid()) break; line.setLineWidth(lineWidth); height += leading; line.setPosition(QPointF(0, height)); height += line.height(); widthUsed = qMax(widthUsed, line.naturalTextWidth()); } textLayout[i]->endLayout(); } first = false; } for (int i = 0; i < count; ++i) { for (int j = 0; j < lines; ++j) { textLayout[j]->draw(&p, QPoint(0, j*spacing)); } } } void paint_QTextLayout_noCache(QPainter &p) { paint_QTextLayout(p, false); } void paint_QTextLayout_cache(QPainter &p) { paint_QTextLayout(p, true); } #ifdef HAVE_STATICTEXT void paint_QStaticText(QPainter &p, bool useOptimizations) { static QStaticText *staticText[lines]; static bool first = true; if (first) { for (int i = 0; i < lines; ++i) { staticText[i] = new QStaticText(strings[i]); staticText[i]->setUseBackendOptimizations(useOptimizations); } first = false; } for (int i = 0; i < count; ++i) { for (int j = 0; j < lines; ++j) { p.drawStaticText(QPointF(0, 30 + j*spacing), *staticText[j]); } } } void paint_QStaticText_noOptimizations(QPainter &p) { paint_QStaticText(p, false); } void paint_QStaticText_optimizations(QPainter &p) { paint_QStaticText(p, true); } #endif void paint_QPixmapCachedText(QPainter &p) { static bool first = true; static QPixmap cacheText[lines]; if (first) { for (int i = 0; i < lines; ++i) { QRectF trueSize; trueSize = p.boundingRect(QRectF(QPointF(0,0), size), 0, strings[i]); cacheText[i] = QPixmap(trueSize.size().toSize()); cacheText[i].fill(Qt::transparent); QPainter paint(&cacheText[i]); paint.setPen(Qt::black); paint.drawText(QRectF(QPointF(0,0), trueSize.size().toSize()), strings[i]); } first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap(0,j*spacing,cacheText[j]); } } } void paint_RoundedRect(QPainter &p) { p.setRenderHint(QPainter::Antialiasing, true); p.setPen(Qt::black); p.setBrush(Qt::red); for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { QSize size((j+1)*50, spacing-1); p.drawRoundedRect(QRectF(QPointF(0,j*spacing), size), 8, 8); } } } void paint_QPixmapCachedRoundedRect(QPainter &p) { static bool first = true; static QPixmap cacheRect[lines]; if (first) { for (int i = 0; i < lines; ++i) { QSize size((i+1)*50, spacing-1); cacheRect[i] = QPixmap(size); cacheRect[i].fill(Qt::transparent); QPainter paint(&cacheRect[i]); paint.setRenderHint(QPainter::Antialiasing); paint.setPen(Qt::black); paint.setBrush(Qt::red); paint.drawRoundedRect(QRect(QPoint(0,0), size), 8, 8); } first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap(0,j*spacing,cacheRect[j]); } } } typedef void(*PaintFunc)(QPainter &); struct { const char *name; PaintFunc func; } funcs[] = { { "QTextLayoutNoCache", &paint_QTextLayout_noCache }, { "QTextLayoutWithCache", &paint_QTextLayout_cache }, #ifdef HAVE_STATICTEXT { "QStaticTextNoBackendOptimizations", &paint_QStaticText_noOptimizations }, { "QStaticTextWithBackendOptimizations", &paint_QStaticText_optimizations }, #endif { "CachedText", &paint_QPixmapCachedText }, { "RoundedRect", &paint_RoundedRect }, { "CachedRoundedRect", &paint_QPixmapCachedRoundedRect }, { 0, 0 } }; PaintFunc testFunc = 0; class MyGLWidget : public QGLWidget { public: MyGLWidget(const QGLFormat &format) : QGLWidget(format), frames(0) { const char chars[] = "abcd efgh ijkl mnop qrst uvwx yz!$. ABCD 1234"; int len = strlen(chars); for (int i = 0; i < lines; ++i) { for (int j = 0; j < 60; j++) { strings[i] += QChar(chars[rand() % len]); } } } void paintEvent(QPaintEvent *) { static int last = 0; static bool firstRun = true; if (firstRun == 0) { timer.start(); firstRun = false; } else { int elapsed = timer.elapsed(); qDebug() << "frame elapsed:" << elapsed - last; last = elapsed; } QPainter p(this); p.fillRect(rect(), Qt::white); p.setPen(Qt::black); QTime drawTimer; drawTimer.start(); testFunc(p); qDebug() << "draw time" << drawTimer.elapsed(); if (iterations--) update(); else qApp->quit(); } QTime timer; int frames; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); bool sampleBuffers = false; for (int i = 1; i < argc; ++i) { QString arg = argv[i]; if (arg == "-test") { arg = argv[++i]; int j = 0; while (funcs[j].name) { if (arg == funcs[j].name) { testFunc = funcs[j].func; qDebug() << "Running test" << arg; break; } ++j; } } else if (arg == "-iterations") { arg = argv[++i]; iterations = arg.toInt(); } else if (arg == "-sampleBuffers") { sampleBuffers = true; } } if (testFunc == 0) { qDebug() << "Usage: textspeed -test <test> [-sampleBuffers] [-iterations n]"; qDebug() << "where <test> can be:"; int j = 0; while (funcs[j].name) { qDebug() << " " << funcs[j].name; ++j; } exit(1); } QWidget w; QGLFormat format = QGLFormat::defaultFormat(); format.setSampleBuffers(sampleBuffers); MyGLWidget *glw = new MyGLWidget(format); glw->setAutoFillBackground(false); QVBoxLayout *layout = new QVBoxLayout(&w); w.setLayout(layout); layout->addWidget(glw); w.showFullScreen(); app.exec(); return 0; } <commit_msg>Add license header.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module 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 <QApplication> #include <QPixmap> #include <QImage> #include <QPainter> #include <QGLWidget> #include <QTextLayout> #include <QVBoxLayout> #include <QTime> #include <QDebug> #ifdef HAVE_STATICTEXT #include <private/qstatictext_p.h> #endif int iterations = 20; const int count = 600; const int lines = 12; const int spacing = 36; QSizeF size(1000, 800); const qreal lineWidth = 1000; QString strings[lines]; void paint_QTextLayout(QPainter &p, bool useCache) { static bool first = true; static QTextLayout *textLayout[lines]; if (first) { for (int i = 0; i < lines; ++i) { textLayout[i] = new QTextLayout(strings[i]); int leading = p.fontMetrics().leading(); qreal height = 0; qreal widthUsed = 0; textLayout[i]->setCacheEnabled(useCache); textLayout[i]->beginLayout(); while (1) { QTextLine line = textLayout[i]->createLine(); if (!line.isValid()) break; line.setLineWidth(lineWidth); height += leading; line.setPosition(QPointF(0, height)); height += line.height(); widthUsed = qMax(widthUsed, line.naturalTextWidth()); } textLayout[i]->endLayout(); } first = false; } for (int i = 0; i < count; ++i) { for (int j = 0; j < lines; ++j) { textLayout[j]->draw(&p, QPoint(0, j*spacing)); } } } void paint_QTextLayout_noCache(QPainter &p) { paint_QTextLayout(p, false); } void paint_QTextLayout_cache(QPainter &p) { paint_QTextLayout(p, true); } #ifdef HAVE_STATICTEXT void paint_QStaticText(QPainter &p, bool useOptimizations) { static QStaticText *staticText[lines]; static bool first = true; if (first) { for (int i = 0; i < lines; ++i) { staticText[i] = new QStaticText(strings[i]); staticText[i]->setUseBackendOptimizations(useOptimizations); } first = false; } for (int i = 0; i < count; ++i) { for (int j = 0; j < lines; ++j) { p.drawStaticText(QPointF(0, 30 + j*spacing), *staticText[j]); } } } void paint_QStaticText_noOptimizations(QPainter &p) { paint_QStaticText(p, false); } void paint_QStaticText_optimizations(QPainter &p) { paint_QStaticText(p, true); } #endif void paint_QPixmapCachedText(QPainter &p) { static bool first = true; static QPixmap cacheText[lines]; if (first) { for (int i = 0; i < lines; ++i) { QRectF trueSize; trueSize = p.boundingRect(QRectF(QPointF(0,0), size), 0, strings[i]); cacheText[i] = QPixmap(trueSize.size().toSize()); cacheText[i].fill(Qt::transparent); QPainter paint(&cacheText[i]); paint.setPen(Qt::black); paint.drawText(QRectF(QPointF(0,0), trueSize.size().toSize()), strings[i]); } first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap(0,j*spacing,cacheText[j]); } } } void paint_RoundedRect(QPainter &p) { p.setRenderHint(QPainter::Antialiasing, true); p.setPen(Qt::black); p.setBrush(Qt::red); for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { QSize size((j+1)*50, spacing-1); p.drawRoundedRect(QRectF(QPointF(0,j*spacing), size), 8, 8); } } } void paint_QPixmapCachedRoundedRect(QPainter &p) { static bool first = true; static QPixmap cacheRect[lines]; if (first) { for (int i = 0; i < lines; ++i) { QSize size((i+1)*50, spacing-1); cacheRect[i] = QPixmap(size); cacheRect[i].fill(Qt::transparent); QPainter paint(&cacheRect[i]); paint.setRenderHint(QPainter::Antialiasing); paint.setPen(Qt::black); paint.setBrush(Qt::red); paint.drawRoundedRect(QRect(QPoint(0,0), size), 8, 8); } first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap(0,j*spacing,cacheRect[j]); } } } typedef void(*PaintFunc)(QPainter &); struct { const char *name; PaintFunc func; } funcs[] = { { "QTextLayoutNoCache", &paint_QTextLayout_noCache }, { "QTextLayoutWithCache", &paint_QTextLayout_cache }, #ifdef HAVE_STATICTEXT { "QStaticTextNoBackendOptimizations", &paint_QStaticText_noOptimizations }, { "QStaticTextWithBackendOptimizations", &paint_QStaticText_optimizations }, #endif { "CachedText", &paint_QPixmapCachedText }, { "RoundedRect", &paint_RoundedRect }, { "CachedRoundedRect", &paint_QPixmapCachedRoundedRect }, { 0, 0 } }; PaintFunc testFunc = 0; class MyGLWidget : public QGLWidget { public: MyGLWidget(const QGLFormat &format) : QGLWidget(format), frames(0) { const char chars[] = "abcd efgh ijkl mnop qrst uvwx yz!$. ABCD 1234"; int len = strlen(chars); for (int i = 0; i < lines; ++i) { for (int j = 0; j < 60; j++) { strings[i] += QChar(chars[rand() % len]); } } } void paintEvent(QPaintEvent *) { static int last = 0; static bool firstRun = true; if (firstRun == 0) { timer.start(); firstRun = false; } else { int elapsed = timer.elapsed(); qDebug() << "frame elapsed:" << elapsed - last; last = elapsed; } QPainter p(this); p.fillRect(rect(), Qt::white); p.setPen(Qt::black); QTime drawTimer; drawTimer.start(); testFunc(p); qDebug() << "draw time" << drawTimer.elapsed(); if (iterations--) update(); else qApp->quit(); } QTime timer; int frames; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); bool sampleBuffers = false; for (int i = 1; i < argc; ++i) { QString arg = argv[i]; if (arg == "-test") { arg = argv[++i]; int j = 0; while (funcs[j].name) { if (arg == funcs[j].name) { testFunc = funcs[j].func; qDebug() << "Running test" << arg; break; } ++j; } } else if (arg == "-iterations") { arg = argv[++i]; iterations = arg.toInt(); } else if (arg == "-sampleBuffers") { sampleBuffers = true; } } if (testFunc == 0) { qDebug() << "Usage: textspeed -test <test> [-sampleBuffers] [-iterations n]"; qDebug() << "where <test> can be:"; int j = 0; while (funcs[j].name) { qDebug() << " " << funcs[j].name; ++j; } exit(1); } QWidget w; QGLFormat format = QGLFormat::defaultFormat(); format.setSampleBuffers(sampleBuffers); MyGLWidget *glw = new MyGLWidget(format); glw->setAutoFillBackground(false); QVBoxLayout *layout = new QVBoxLayout(&w); w.setLayout(layout); layout->addWidget(glw); w.showFullScreen(); app.exec(); return 0; } <|endoftext|>
<commit_before>#include <drafts/OpenCL/GL.hpp> #include <DO/Sara/Core/DebugUtilities.hpp> #include <DO/Sara/Core/HDF5.hpp> #include <DO/Sara/Core/StringFormat.hpp> #include <DO/Sara/Core/Timer.hpp> #include <DO/Sara/ImageIO.hpp> #include <DO/Sara/ImageProcessing/Flip.hpp> #include <DO/Kalpana/Math/Projection.hpp> #ifdef _WIN32 #include <windows.h> #endif #include <GLFW/glfw3.h> #include <Eigen/Geometry> #include <map> using namespace DO::Sara; using namespace std; namespace kalpana = DO::Kalpana; auto resize_framebuffer(GLFWwindow*, int width, int height) { // make sure the viewport matches the new window dimensions; note that width // and height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } inline auto init_glfw_boilerplate() { // Initialize the windows manager. if (!glfwInit()) throw std::runtime_error{"Error: failed to initialize GLFW!"}; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif } inline auto init_glew_boilerplate() { #ifndef __APPLE__ // Initialize GLEW. auto err = glewInit(); if (err != GLEW_OK) { std::cerr << format("Error: failed to initialize GLEW: %s", glewGetErrorString(err)) << std::endl; } #endif } struct View { View() { view.setIdentity(); view.translate(Vector3f{0.f, 0.f, -100.f}); } auto move_left(float delta) { view.translate(-scale * delta * Vector3f::UnitX()); } auto move_right(float delta) { view.translate(scale * delta * Vector3f::UnitX()); } auto move_backward(float delta) { view.translate(-scale * delta * Vector3f::UnitZ()); } auto move_forward(float delta) { view.translate(scale * delta * Vector3f::UnitZ()); } auto matrix() const -> const Matrix4f& { return view.matrix(); } Transform<float, 3, Eigen::Projective> view; float scale = 1e-1f; }; // Default camera values static const float YAW = -90.0f; static const float PITCH = 0.0f; static const float SPEED = 2.5f; static const float SENSITIVITY = 0.1f; static const float ZOOM = 45.0f; // The explorer's eye. struct Eye { Vector3f position{Vector3f::Zero()}; Vector3f front{-Vector3f::UnitZ()}; Vector3f up{Vector3f::UnitY()}; Vector3f right; Vector3f world_up; float yaw{YAW}; float pitch{PITCH}; float movement_speed{SPEED}; float movement_sensitivity{SENSITIVITY}; float zoom{ZOOM}; auto move_x(float delta) { position.x() += movement_speed * delta; } auto move_y(float delta) { position.y() += movement_speed * delta; } auto move_z(float delta) { position.z() += movement_speed * delta; } // pitch auto yes_head_move(float delta) { pitch += movement_sensitivity * delta; } // yaw auto no_head_movement(float delta) { yaw += movement_sensitivity * delta; } auto update() { Vector3f front1; front1 << cos(yaw * M_PI / 180) * cos(pitch * M_PI / 180.f), sin(pitch * M_PI / 180.f), sin(yaw * M_PI / 180.f) * cos(pitch * M_PI / 180.f); front = front1.normalized(); right = front.cross(world_up).normalized(); up = right.cross(front).normalized(); } auto view_matrix() -> Matrix4f { return {}; } }; struct Time { void update() { last_frame = current_frame; current_frame = timer.elapsed_ms(); delta_time = current_frame - last_frame; } Timer timer; float delta_time = 0.f; float last_frame = 0.f; float current_frame = 0.f; }; auto move_camera_from_keyboard(GLFWwindow* window, View& view, Time& time) { if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) view.move_forward(time.delta_time); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) view.move_backward(time.delta_time); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) view.move_left(time.delta_time); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) view.move_right(time.delta_time); } auto first_mouse = true; float last_x = 800.f / 2.f; float last_y = 600.f / 2.f; auto move_camera_from_mouse(GLFWwindow* window, double x_pos, double y_pos) { if (first_mouse) { last_x = x_pos; last_y = y_pos; first_mouse = false; } const auto xoff = x_pos - last_x; const auto yoff = y_pos - last_y; last_x = x_pos; last_y = y_pos; } auto read_point_cloud(const std::string& h5_filepath) -> Tensor_<float, 2> { auto h5_file = H5File{h5_filepath, H5F_ACC_RDONLY}; auto coords = Tensor_<double, 2>{}; h5_file.read_dataset("points", coords); coords.matrix() *= -1; auto colors = Tensor_<double, 2>{}; h5_file.read_dataset("colors", colors); SARA_DEBUG << "OK" << std::endl; // Concatenate the data. auto vertex_data = Tensor_<double, 2>{{coords.size(0), 6}}; vertex_data.matrix() << coords.matrix(), colors.matrix(); return vertex_data.cast<float>(); } auto make_point_cloud() { // Encode the vertex data in a tensor. #ifdef __APPLE__ const auto vertex_data = read_point_cloud("/Users/david/Desktop/geometry.h5"); #else const auto vertex_data = read_point_cloud("/home/david/Desktop/geometry.h5"); #endif SARA_DEBUG << "vertices =\n" << vertex_data.matrix() << std::endl; return vertex_data; } int main() { // ========================================================================== // Display initialization. // init_glfw_boilerplate(); // Create a window. const auto width = 800; const auto height = 600; auto window = glfwCreateWindow(width, height, "Hello Point Cloud", nullptr, nullptr); glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, resize_framebuffer); glfwSetCursorPosCallback(window, move_camera_from_mouse); init_glew_boilerplate(); // ========================================================================== // Shader program setup. // std::map<std::string, int> arg_pos = {{"in_coords", 0}, // {"in_color", 1}}; const auto vertex_shader_source = R"shader( #version 330 core layout (location = 0) in vec3 in_coords; layout (location = 1) in vec3 in_color; uniform mat4 transform; uniform mat4 view; uniform mat4 projection; out vec3 out_color; void main() { gl_Position = projection * view * transform * vec4(in_coords, 1.0); gl_PointSize = 5.0; out_color = in_color; } )shader"; auto vertex_shader = GL::Shader{}; vertex_shader.create_from_source(GL_VERTEX_SHADER, vertex_shader_source); const auto fragment_shader_source = R"shader( #version 330 core in vec3 out_color; out vec4 frag_color; void main() { vec2 circCoord = 2.0 * gl_PointCoord - 1.0; if (dot(circCoord, circCoord) > 1.0) discard; float dist = length(gl_PointCoord - vec2(0.5)); float alpha = 1.0 - smoothstep(0.2, 0.5, dist); frag_color = vec4(out_color, alpha); } )shader"; auto fragment_shader = GL::Shader{}; fragment_shader.create_from_source(GL_FRAGMENT_SHADER, fragment_shader_source); auto shader_program = GL::ShaderProgram{}; shader_program.create(); shader_program.attach(vertex_shader, fragment_shader); vertex_shader.destroy(); fragment_shader.destroy(); // ========================================================================== // Encode the vertex data in a tensor. // auto vertices = make_point_cloud(); const auto row_bytes = [](const TensorView_<float, 2>& data) { return data.size(1) * sizeof(float); }; const auto float_pointer = [](int offset) { return reinterpret_cast<void*>(offset * sizeof(float)); }; auto vao = GL::VertexArray{}; vao.generate(); // ========================================================================== // Setup Vertex attributes on the GPU side. // auto vbo = GL::Buffer{}; vbo.generate(); { glBindVertexArray(vao); // Copy vertex data. vbo.bind_vertex_data(vertices); // Map the parameters to the argument position for the vertex shader. // // Vertex coordinates. glVertexAttribPointer(arg_pos["in_coords"], 3 /* 3D points */, GL_FLOAT, GL_FALSE, row_bytes(vertices), float_pointer(0)); glEnableVertexAttribArray(arg_pos["in_coords"]); // Texture coordinates. glVertexAttribPointer(arg_pos["in_color"], 3 /* RGB_COLOR */, GL_FLOAT, GL_FALSE, row_bytes(vertices), float_pointer(3)); glEnableVertexAttribArray(arg_pos["in_color"]); } shader_program.use(true); // ========================================================================== // Setup options for point cloud rendering. glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_PROGRAM_POINT_SIZE); // You absolutely need this for 3D objects! glEnable(GL_DEPTH_TEST); auto view = View{}; auto time = Time{}; // Display image. glfwSwapInterval(1); while (!glfwWindowShouldClose(window)) { // Calculate the elapsed time. time.update(); if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); // Camera interaction with keyboard. move_camera_from_keyboard(window, view, time); view.view.matrix() = rot_mat * view.view.matrix(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // Important. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Transform matrix. auto transform = Transform<float, 3, Eigen::Projective>{}; transform.setIdentity(); //transform.rotate(AngleAxisf(std::pow(1.5, 5) * time.last_frame / 10000, // Vector3f{0.5f, 1.0f, 0.0f}.normalized())); shader_program.set_uniform_matrix4f("transform", transform.matrix().data()); // View matrix. shader_program.set_uniform_matrix4f("view", view.matrix().data()); // Projection matrix. const Matrix4f projection = kalpana::perspective(45., 800. / 600., .1, 1000.).cast<float>(); shader_program.set_uniform_matrix4f("projection", projection.data()); // Draw triangles. glBindVertexArray(vao); glDrawArrays(GL_POINTS, 0, vertices.size(0)); glfwSwapBuffers(window); glfwPollEvents(); } vao.destroy(); vbo.destroy(); // Clean up resources. glfwDestroyWindow(window); glfwTerminate(); return EXIT_SUCCESS; } <commit_msg>MAINT: add movable eye to explore the point cloud.<commit_after>#include <drafts/OpenCL/GL.hpp> #include <DO/Sara/Core/DebugUtilities.hpp> #include <DO/Sara/Core/HDF5.hpp> #include <DO/Sara/Core/StringFormat.hpp> #include <DO/Sara/Core/Timer.hpp> #include <DO/Sara/ImageIO.hpp> #include <DO/Sara/ImageProcessing/Flip.hpp> #include <DO/Kalpana/Math/Projection.hpp> #ifdef _WIN32 #include <windows.h> #endif #include <GLFW/glfw3.h> #include <Eigen/Geometry> #include <map> using namespace DO::Sara; using namespace std; namespace kalpana = DO::Kalpana; auto resize_framebuffer(GLFWwindow*, int width, int height) { // make sure the viewport matches the new window dimensions; note that width // and height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } inline auto init_glfw_boilerplate() { // Initialize the windows manager. if (!glfwInit()) throw std::runtime_error{"Error: failed to initialize GLFW!"}; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif } inline auto init_glew_boilerplate() { #ifndef __APPLE__ // Initialize GLEW. auto err = glewInit(); if (err != GLEW_OK) { std::cerr << format("Error: failed to initialize GLEW: %s", glewGetErrorString(err)) << std::endl; } #endif } // Default camera values static const float YAW = -90.0f; static const float PITCH = 0.0f; static const float SPEED = 1e-1f; static const float SENSITIVITY = 1e-1f; static const float ZOOM = 45.0f; // The explorer's eye. struct Eye { Vector3f position{Vector3f::Zero()}; Vector3f front{-Vector3f::UnitZ()}; Vector3f up{Vector3f::UnitY()}; Vector3f right; Vector3f world_up{Vector3f::UnitY()}; float yaw{YAW}; float pitch{PITCH}; float roll{0.f}; float movement_speed{SPEED}; float movement_sensitivity{SENSITIVITY}; float zoom{ZOOM}; auto move_left(float delta) { position -= movement_speed * delta * right; } auto move_right(float delta) { position += movement_speed * delta * right; } auto move_forward(float delta) { position += movement_speed * delta * front; } auto move_backward(float delta) { position -= movement_speed * delta * front; } auto move_up(float delta) { position += movement_speed * delta * up; } auto move_down(float delta) { position -= movement_speed * delta * up; } // pitch auto yes_head_movement(float delta) { pitch += movement_sensitivity * delta; } // yaw auto no_head_movement(float delta) { yaw += movement_sensitivity * delta; } auto maybe_head_movement(float delta) { roll += movement_sensitivity * delta; } auto update() { Vector3f front1; front1 << cos(yaw * M_PI / 180) * cos(pitch * M_PI / 180.f), sin(pitch * M_PI / 180.f), sin(yaw * M_PI / 180.f) * cos(pitch * M_PI / 180.f); front = front1.normalized(); right = front.cross(world_up).normalized(); up = right.cross(front).normalized(); SARA_DEBUG << "front = " << front.transpose() << std::endl; SARA_DEBUG << "right = " << right.transpose() << std::endl; SARA_DEBUG << "up = " << up.transpose() << std::endl; } auto view_matrix() -> Matrix4f { return look_at(position, position + front, up); } auto look_at(const Vector3f& eye, const Vector3f& center, const Vector3f& up) -> Matrix4f { Vector3f f = (center - eye).normalized(); Vector3f u = up.normalized(); Vector3f s = f.cross(u).normalized(); u = s.cross(f); Matrix4f res; res << s.x(), s.y(), s.z(), -s.dot(eye), u.x(), u.y(), u.z(), -u.dot(eye), -f.x(), -f.y(), -f.z(), f.dot(eye), 0, 0, 0, 1; return res; } }; struct Time { void update() { last_frame = current_frame; current_frame = timer.elapsed_ms(); delta_time = current_frame - last_frame; } Timer timer; float delta_time = 0.f; float last_frame = 0.f; float current_frame = 0.f; }; auto move_camera_from_keyboard(GLFWwindow* window, Eye& eye, Time& time) { if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) eye.move_forward(time.delta_time); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) eye.move_backward(time.delta_time); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) eye.move_left(time.delta_time); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) eye.move_right(time.delta_time); if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) eye.no_head_movement(-time.delta_time); // CCW if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) eye.no_head_movement(+time.delta_time); // CW if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) eye.yes_head_movement(+time.delta_time); if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS) eye.yes_head_movement(-time.delta_time); if (glfwGetKey(window, GLFW_KEY_T) == GLFW_PRESS) eye.move_up(time.delta_time); if (glfwGetKey(window, GLFW_KEY_G) == GLFW_PRESS) eye.move_down(time.delta_time); eye.update(); } auto read_point_cloud(const std::string& h5_filepath) -> Tensor_<float, 2> { auto h5_file = H5File{h5_filepath, H5F_ACC_RDONLY}; auto coords = Tensor_<double, 2>{}; h5_file.read_dataset("points", coords); coords.matrix() *= -1; auto colors = Tensor_<double, 2>{}; h5_file.read_dataset("colors", colors); SARA_DEBUG << "OK" << std::endl; // Concatenate the data. auto vertex_data = Tensor_<double, 2>{{coords.size(0), 6}}; vertex_data.matrix() << coords.matrix(), colors.matrix(); return vertex_data.cast<float>(); } auto make_point_cloud() { // Encode the vertex data in a tensor. #ifdef __APPLE__ const auto vertex_data = read_point_cloud("/Users/david/Desktop/geometry.h5"); #else const auto vertex_data = read_point_cloud("/home/david/Desktop/geometry.h5"); #endif SARA_DEBUG << "vertices =\n" << vertex_data.matrix() << std::endl; return vertex_data; } int main() { // ========================================================================== // Display initialization. // init_glfw_boilerplate(); // Create a window. const auto width = 800; const auto height = 600; auto window = glfwCreateWindow(width, height, "Hello Point Cloud", nullptr, nullptr); glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, resize_framebuffer); //glfwSetCursorPosCallback(window, move_camera_from_mouse); init_glew_boilerplate(); // ========================================================================== // Shader program setup. // std::map<std::string, int> arg_pos = {{"in_coords", 0}, // {"in_color", 1}}; const auto vertex_shader_source = R"shader( #version 330 core layout (location = 0) in vec3 in_coords; layout (location = 1) in vec3 in_color; uniform mat4 transform; uniform mat4 view; uniform mat4 projection; out vec3 out_color; void main() { gl_Position = projection * view * transform * vec4(in_coords, 1.0); gl_PointSize = 5.0; out_color = in_color; } )shader"; auto vertex_shader = GL::Shader{}; vertex_shader.create_from_source(GL_VERTEX_SHADER, vertex_shader_source); const auto fragment_shader_source = R"shader( #version 330 core in vec3 out_color; out vec4 frag_color; void main() { vec2 circCoord = 2.0 * gl_PointCoord - 1.0; if (dot(circCoord, circCoord) > 1.0) discard; float dist = length(gl_PointCoord - vec2(0.5)); float alpha = 1.0 - smoothstep(0.2, 0.5, dist); frag_color = vec4(out_color, alpha); } )shader"; auto fragment_shader = GL::Shader{}; fragment_shader.create_from_source(GL_FRAGMENT_SHADER, fragment_shader_source); auto shader_program = GL::ShaderProgram{}; shader_program.create(); shader_program.attach(vertex_shader, fragment_shader); vertex_shader.destroy(); fragment_shader.destroy(); // ========================================================================== // Encode the vertex data in a tensor. // auto vertices = make_point_cloud(); const auto row_bytes = [](const TensorView_<float, 2>& data) { return data.size(1) * sizeof(float); }; const auto float_pointer = [](int offset) { return reinterpret_cast<void*>(offset * sizeof(float)); }; auto vao = GL::VertexArray{}; vao.generate(); // ========================================================================== // Setup Vertex attributes on the GPU side. // auto vbo = GL::Buffer{}; vbo.generate(); { glBindVertexArray(vao); // Copy vertex data. vbo.bind_vertex_data(vertices); // Map the parameters to the argument position for the vertex shader. // // Vertex coordinates. glVertexAttribPointer(arg_pos["in_coords"], 3 /* 3D points */, GL_FLOAT, GL_FALSE, row_bytes(vertices), float_pointer(0)); glEnableVertexAttribArray(arg_pos["in_coords"]); // Texture coordinates. glVertexAttribPointer(arg_pos["in_color"], 3 /* RGB_COLOR */, GL_FLOAT, GL_FALSE, row_bytes(vertices), float_pointer(3)); glEnableVertexAttribArray(arg_pos["in_color"]); } shader_program.use(true); // ========================================================================== // Setup options for point cloud rendering. glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_PROGRAM_POINT_SIZE); // You absolutely need this for 3D objects! glEnable(GL_DEPTH_TEST); auto eye = Eye{}; auto time = Time{}; // Display image. glfwSwapInterval(1); while (!glfwWindowShouldClose(window)) { // Calculate the elapsed time. time.update(); if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); // Camera interaction with keyboard. move_camera_from_keyboard(window, eye, time); auto view_matrix = eye.view_matrix(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // Important. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Transform matrix. auto transform = Transform<float, 3, Eigen::Projective>{}; transform.setIdentity(); transform.rotate(AngleAxisf(std::pow(1.5, 5) * time.last_frame / 10000, Vector3f{0.5f, 1.0f, 0.0f}.normalized())); shader_program.set_uniform_matrix4f("transform", transform.matrix().data()); // View matrix. shader_program.set_uniform_matrix4f("view", view_matrix.data()); // Projection matrix. const Matrix4f projection = kalpana::perspective(45., 800. / 600., .1, 1000.).cast<float>(); shader_program.set_uniform_matrix4f("projection", projection.data()); // Draw triangles. glBindVertexArray(vao); glDrawArrays(GL_POINTS, 0, vertices.size(0)); glfwSwapBuffers(window); glfwPollEvents(); } vao.destroy(); vbo.destroy(); // Clean up resources. glfwDestroyWindow(window); glfwTerminate(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** \file augment_canones_references.cc * \brief A tool for adding numerical canon law references to MARC-21 datasets. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2019, 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 <string> #include <unordered_map> #include <cstdlib> #include "BibleUtil.h" #include "Compiler.h" #include "MARC.h" #include "StringUtil.h" #include "UBTools.h" #include "util.h" namespace { void ParseRanges(const std::string &ppn, const std::string &ranges, unsigned * const range_start, unsigned * const range_end) { std::vector<std::string> parts; if (unlikely(StringUtil::SplitThenTrimWhite(ranges, ',', &parts, /* suppress_empty_components = */false) > 3)) LOG_ERROR("bad codex parts \"" + ranges + "\"! (PPN: " + ppn + ")"); unsigned canones; if (parts.size() == 1) { const auto dash_pos(parts[0].find('-')); if (dash_pos == std::string::npos) { if (unlikely(not StringUtil::ToUnsigned(parts[0], &canones))) LOG_ERROR("bad codex canones \"" + parts[0] + "\"! (PPN: " + ppn + ")"); *range_start = canones * 10000; *range_end = canones * 10000 + 9999; } else { if (unlikely(not StringUtil::ToUnsigned(parts[0].substr(0, dash_pos), range_start) or not StringUtil::ToUnsigned(parts[0].substr(dash_pos + 1), range_end))) LOG_ERROR("bad canones range \"" + parts[0] + "\"! (PPN: " + ppn + ")"); *range_start *= 10000; *range_end *= 10000; } return; } else if (parts.size() == 2) { if (unlikely(not StringUtil::ToUnsigned(parts[0], &canones))) LOG_ERROR("bad codex canones \"" + parts[0] + "\"! (PPN: " + ppn + ")"); const auto dash_pos(parts[1].find('-')); if (dash_pos == std::string::npos) { unsigned pars; if (unlikely(not StringUtil::ToUnsigned(parts[1], &pars))) LOG_ERROR("bad codex pars \"" + parts[1] + "\"! (PPN: " + ppn + ")"); *range_start = canones * 10000 + pars * 100; *range_end = canones * 10000 + 9999; } else { unsigned start_pars, end_pars; if (unlikely(not StringUtil::ToUnsigned(parts[1].substr(0, dash_pos), &start_pars) or not StringUtil::ToUnsigned(parts[1].substr(dash_pos + 1), &end_pars))) LOG_ERROR("bad pars range \"" + parts[1] + "\"! (PPN: " + ppn + ")"); *range_start = canones * 10000 + start_pars * 100; *range_end = canones * 10000 + end_pars * 100 + 99; } return; } LOG_ERROR("don't know how to parse codex parts \"" + ranges + "\"! (PPN: " + ppn + ")"); } // To understand this code read https://github.com/ubtue/tuefind/wiki/Codices std::string FieldToCanonLawCode(const std::string &ppn, const MARC::Record::Field &_110_field) { const std::string t_subfield(_110_field.getFirstSubfieldWithCode('t')); const std::string year(_110_field.getFirstSubfieldWithCode('f')); const std::string p_subfield(_110_field.getFirstSubfieldWithCode('p')); enum Codex { CIC1917, CIC1983, CCEO } codex; if (t_subfield == "Codex canonum ecclesiarum orientalium") codex = CCEO; else { if (unlikely(year.empty())) LOG_ERROR("missing year for Codex Iuris Canonici!"); if (year == "1917") codex = CIC1917; else if (year == "1983") codex = CIC1983; else LOG_ERROR("bad year for Codex Iuris Canonici \"" + year + "\"!"); } unsigned range_start, range_end; if (p_subfield.empty()) { range_start = 0; range_end = 99999999; } else ParseRanges(ppn, p_subfield, &range_start, &range_end); switch (codex) { case CIC1917: return StringUtil::ToString(100000000 + range_start) + "_" + StringUtil::ToString(100000000 + range_end); case CIC1983: return StringUtil::ToString(200000000 + range_start) + "_" + StringUtil::ToString(200000000 + range_end); case CCEO: return StringUtil::ToString(300000000 + range_start) + "_" + StringUtil::ToString(300000000 + range_end); } } void LoadAuthorityData(MARC::Reader * const reader, std::unordered_map<std::string, std::string> * const authority_ppns_to_canon_law_codes_map) { unsigned total_count(0); while (auto record = reader->read()) { ++total_count; const auto _110_field(record.findTag("110")); if (_110_field == record.end() or _110_field->getFirstSubfieldWithCode('a') != "Katholische Kirche") continue; const std::string t_subfield(_110_field->getFirstSubfieldWithCode('t')); if (t_subfield != "Codex Iuris Canonici" and t_subfield != "Codex canonum ecclesiarum orientalium") continue; (*authority_ppns_to_canon_law_codes_map)[record.getControlNumber()] = FieldToCanonLawCode(record.getControlNumber(), *_110_field); } LOG_INFO("found " + std::to_string(authority_ppns_to_canon_law_codes_map->size()) + " canon law records among " + std::to_string(total_count) + " authority records."); } void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer, const std::unordered_map<std::string, std::string> &authority_ppns_to_canon_law_codes_map) { unsigned total_count(0), augmented_count(0); while (auto record = reader->read()) { ++total_count; bool augmented_record(false); for (const auto &_689_field : record.getTagRange("689")) { if (_689_field.getFirstSubfieldWithCode('2') != "gnd") continue; std::vector<std::string> authority_ppns; for (const auto &subfield : _689_field.getSubfields()) { if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-576)")) authority_ppns.emplace_back(subfield.value_.substr(__builtin_strlen("(DE-576)"))); } for (const auto &authority_ppn : authority_ppns) { const auto ppn_and_canon_law_code(authority_ppns_to_canon_law_codes_map.find(authority_ppn)); if (ppn_and_canon_law_code != authority_ppns_to_canon_law_codes_map.cend()) { record.insertField("CAL", { { 'a', ppn_and_canon_law_code->second } }); augmented_record = true; } } } if (augmented_record) ++augmented_count; writer->write(record); } LOG_INFO("augmented " + std::to_string(augmented_count) + " of " + std::to_string(total_count) + " records."); } } // unnamed namespace int Main(int argc, char **argv) { if (argc != 4) ::Usage("ix_theo_titles authority_records augmented_ix_theo_titles"); const std::string title_input_filename(argv[1]); const std::string authority_filename(argv[2]); const std::string title_output_filename(argv[3]); if (unlikely(title_input_filename == title_output_filename)) LOG_ERROR("Title input file name equals title output file name!"); if (unlikely(title_input_filename == authority_filename)) LOG_ERROR("Title input file name equals authority file name!"); if (unlikely(title_output_filename == authority_filename)) LOG_ERROR("Title output file name equals authority file name!"); auto authority_reader(MARC::Reader::Factory(authority_filename)); std::unordered_map<std::string, std::string> authority_ppns_to_canon_law_codes_map; LoadAuthorityData(authority_reader.get(), &authority_ppns_to_canon_law_codes_map); auto title_reader(MARC::Reader::Factory(title_input_filename)); auto title_writer(MARC::Writer::Factory(title_output_filename)); ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_canon_law_codes_map); return EXIT_SUCCESS; } <commit_msg>Update augment_canones_references.cc<commit_after>/** \file augment_canones_references.cc * \brief A tool for adding numerical canon law references to MARC-21 datasets. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2019, 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 <string> #include <unordered_map> #include <cstdlib> #include "BibleUtil.h" #include "Compiler.h" #include "MARC.h" #include "StringUtil.h" #include "UBTools.h" #include "util.h" namespace { void ParseRanges(const std::string &ppn, const std::string &ranges, unsigned * const range_start, unsigned * const range_end) { std::vector<std::string> parts; if (unlikely(StringUtil::SplitThenTrimWhite(ranges, ',', &parts, /* suppress_empty_components = */false) > 3)) LOG_ERROR("bad codex parts \"" + ranges + "\"! (PPN: " + ppn + ")"); unsigned canones; if (parts.size() == 1) { const auto dash_pos(parts[0].find('-')); if (dash_pos == std::string::npos) { if (unlikely(not StringUtil::ToUnsigned(parts[0], &canones))) LOG_ERROR("bad codex canones \"" + parts[0] + "\"! (PPN: " + ppn + ")"); *range_start = canones * 10000; *range_end = canones * 10000 + 9999; } else { if (unlikely(not StringUtil::ToUnsigned(parts[0].substr(0, dash_pos), range_start) or not StringUtil::ToUnsigned(parts[0].substr(dash_pos + 1), range_end))) LOG_ERROR("bad canones range \"" + parts[0] + "\"! (PPN: " + ppn + ")"); *range_start *= 10000; *range_end *= 10000; } return; } else if (parts.size() == 2) { if (unlikely(not StringUtil::ToUnsigned(parts[0], &canones))) LOG_ERROR("bad codex canones \"" + parts[0] + "\"! (PPN: " + ppn + ")"); const auto dash_pos(parts[1].find('-')); if (dash_pos == std::string::npos) { unsigned pars; if (unlikely(not StringUtil::ToUnsigned(parts[1], &pars))) LOG_ERROR("bad codex pars \"" + parts[1] + "\"! (PPN: " + ppn + ")"); *range_start = canones * 10000 + pars * 100; *range_end = canones * 10000 + 9999; } else { unsigned start_pars, end_pars; if (unlikely(not StringUtil::ToUnsigned(parts[1].substr(0, dash_pos), &start_pars) or not StringUtil::ToUnsigned(parts[1].substr(dash_pos + 1), &end_pars))) LOG_ERROR("bad pars range \"" + parts[1] + "\"! (PPN: " + ppn + ")"); *range_start = canones * 10000 + start_pars * 100; *range_end = canones * 10000 + end_pars * 100 + 99; } return; } LOG_ERROR("don't know how to parse codex parts \"" + ranges + "\"! (PPN: " + ppn + ")"); } // To understand this code read https://github.com/ubtue/tuefind/wiki/Codices std::string FieldToCanonLawCode(const std::string &ppn, const MARC::Record::Field &_110_field) { const std::string t_subfield(_110_field.getFirstSubfieldWithCode('t')); const std::string year(_110_field.getFirstSubfieldWithCode('f')); const std::string p_subfield(_110_field.getFirstSubfieldWithCode('p')); enum Codex { CIC1917, CIC1983, CCEO } codex; if (t_subfield == "Codex canonum ecclesiarum orientalium") codex = CCEO; else { if (unlikely(year.empty())) LOG_ERROR("missing year for Codex Iuris Canonici!"); if (year == "1917") codex = CIC1917; else if (year == "1983") codex = CIC1983; else LOG_ERROR("bad year for Codex Iuris Canonici \"" + year + "\"!"); } unsigned range_start, range_end; if (p_subfield.empty()) { range_start = 0; range_end = 99999999; } else ParseRanges(ppn, p_subfield, &range_start, &range_end); switch (codex) { case CIC1917: return StringUtil::ToString(100000000 + range_start) + "_" + StringUtil::ToString(100000000 + range_end); case CIC1983: return StringUtil::ToString(200000000 + range_start) + "_" + StringUtil::ToString(200000000 + range_end); case CCEO: return StringUtil::ToString(300000000 + range_start) + "_" + StringUtil::ToString(300000000 + range_end); } } void LoadAuthorityData(MARC::Reader * const reader, std::unordered_map<std::string, std::string> * const authority_ppns_to_canon_law_codes_map) { unsigned total_count(0); while (auto record = reader->read()) { ++total_count; const auto _110_field(record.findTag("110")); if (_110_field == record.end() or _110_field->getFirstSubfieldWithCode('a') != "Katholische Kirche") continue; const std::string t_subfield(_110_field->getFirstSubfieldWithCode('t')); if (t_subfield != "Codex Iuris Canonici" and t_subfield != "Codex canonum ecclesiarum orientalium") continue; (*authority_ppns_to_canon_law_codes_map)[record.getControlNumber()] = FieldToCanonLawCode(record.getControlNumber(), *_110_field); } LOG_INFO("found " + std::to_string(authority_ppns_to_canon_law_codes_map->size()) + " canon law records among " + std::to_string(total_count) + " authority records."); } void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer, const std::unordered_map<std::string, std::string> &authority_ppns_to_canon_law_codes_map) { unsigned total_count(0), augmented_count(0); while (auto record = reader->read()) { ++total_count; bool augmented_record(false); for (const auto &_689_field : record.getTagRange("689")) { if (_689_field.getFirstSubfieldWithCode('2') != "gnd") continue; std::vector<std::string> authority_ppns; for (const auto &subfield : _689_field.getSubfields()) { if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-576)")) authority_ppns.emplace_back(subfield.value_.substr(__builtin_strlen("(DE-576)"))); } for (const auto &authority_ppn : authority_ppns) { const auto ppn_and_canon_law_code(authority_ppns_to_canon_law_codes_map.find(authority_ppn)); if (ppn_and_canon_law_code != authority_ppns_to_canon_law_codes_map.cend()) { record.insertField("CAL", { { 'a', ppn_and_canon_law_code->second } }); augmented_record = true; } } } if (augmented_record) ++augmented_count; writer->write(record); } LOG_INFO("augmented " + std::to_string(augmented_count) + " of " + std::to_string(total_count) + " records."); } } // unnamed namespace int Main(int argc, char **argv) { if (argc != 4) ::Usage("ixtheo_titles authority_records augmented_ixtheo_titles"); const std::string title_input_filename(argv[1]); const std::string authority_filename(argv[2]); const std::string title_output_filename(argv[3]); if (unlikely(title_input_filename == title_output_filename)) LOG_ERROR("Title input file name equals title output file name!"); if (unlikely(title_input_filename == authority_filename)) LOG_ERROR("Title input file name equals authority file name!"); if (unlikely(title_output_filename == authority_filename)) LOG_ERROR("Title output file name equals authority file name!"); auto authority_reader(MARC::Reader::Factory(authority_filename)); std::unordered_map<std::string, std::string> authority_ppns_to_canon_law_codes_map; LoadAuthorityData(authority_reader.get(), &authority_ppns_to_canon_law_codes_map); auto title_reader(MARC::Reader::Factory(title_input_filename)); auto title_writer(MARC::Writer::Factory(title_output_filename)); ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_canon_law_codes_map); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: lineaction.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 08:18:40 $ * * 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 * ************************************************************************/ #include <lineaction.hxx> #include <outdevstate.hxx> #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif #ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP_ #include <com/sun/star/rendering/XCanvas.hpp> #endif #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef _VCL_CANVASTOOLS_HXX #include <vcl/canvastools.hxx> #endif #ifndef _BGFX_RANGE_B2DRANGE_HXX #include <basegfx/range/b2drange.hxx> #endif #ifndef _BGFX_TOOLS_CANVASTOOLS_HXX #include <basegfx/tools/canvastools.hxx> #endif #ifndef _CANVAS_CANVASTOOLS_HXX #include <canvas/canvastools.hxx> #endif #include <boost/utility.hpp> #include <cppcanvas/canvas.hxx> #include <mtftools.hxx> using namespace ::com::sun::star; namespace cppcanvas { namespace internal { namespace { class LineAction : public Action, private ::boost::noncopyable { public: LineAction( const ::Point&, const ::Point&, const CanvasSharedPtr&, const OutDevState& ); virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual sal_Int32 getActionCount() const; private: Point maStartPoint; Point maEndPoint; CanvasSharedPtr mpCanvas; rendering::RenderState maState; }; LineAction::LineAction( const ::Point& rStartPoint, const ::Point& rEndPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) : maStartPoint( rStartPoint ), maEndPoint( rEndPoint ), mpCanvas( rCanvas ), maState() { tools::initRenderState(maState,rState); maState.DeviceColor = rState.lineColor; } bool LineAction::render( const ::basegfx::B2DHomMatrix& rTransformation ) const { RTL_LOGFILE_CONTEXT( aLog, "::cppcanvas::internal::LineAction::render()" ); RTL_LOGFILE_CONTEXT_TRACE1( aLog, "::cppcanvas::internal::LineAction: 0x%X", this ); rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); mpCanvas->getUNOCanvas()->drawLine( ::vcl::unotools::point2DFromPoint(maStartPoint), ::vcl::unotools::point2DFromPoint(maEndPoint), mpCanvas->getViewState(), aLocalState ); return true; } bool LineAction::render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // line only contains a single action, fail if subset // requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return false; return render( rTransformation ); } ::basegfx::B2DRange LineAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const { rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); return tools::calcDevicePixelBounds( ::basegfx::B2DRange( maStartPoint.X(), maStartPoint.Y(), maEndPoint.X(), maEndPoint.Y() ), mpCanvas->getViewState(), aLocalState ); } ::basegfx::B2DRange LineAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // line only contains a single action, empty bounds // if subset requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return ::basegfx::B2DRange(); return getBounds( rTransformation ); } sal_Int32 LineAction::getActionCount() const { return 1; } } ActionSharedPtr LineActionFactory::createLineAction( const ::Point& rStartPoint, const ::Point& rEndPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) { return ActionSharedPtr( new LineAction( rStartPoint, rEndPoint, rCanvas, rState) ); } } } <commit_msg>INTEGRATION: CWS canvas02 (1.6.4); FILE MERGED 2005/10/09 09:11:49 thb 1.6.4.2: RESYNC: (1.6-1.7); FILE MERGED 2005/08/24 23:02:57 thb 1.6.4.1: #i52876# Added CachedPrimitiveBase base class for common XCachedPrimitive handling; removed external header guards from cxx files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: lineaction.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2005-11-02 13:40:30 $ * * 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 * ************************************************************************/ #include <lineaction.hxx> #include <outdevstate.hxx> #include <rtl/logfile.hxx> #include <com/sun/star/rendering/XCanvas.hpp> #include <tools/gen.hxx> #include <vcl/canvastools.hxx> #include <basegfx/range/b2drange.hxx> #include <basegfx/tools/canvastools.hxx> #include <canvas/canvastools.hxx> #include <boost/utility.hpp> #include <cppcanvas/canvas.hxx> #include <mtftools.hxx> using namespace ::com::sun::star; namespace cppcanvas { namespace internal { namespace { class LineAction : public Action, private ::boost::noncopyable { public: LineAction( const ::Point&, const ::Point&, const CanvasSharedPtr&, const OutDevState& ); virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual sal_Int32 getActionCount() const; private: Point maStartPoint; Point maEndPoint; CanvasSharedPtr mpCanvas; rendering::RenderState maState; }; LineAction::LineAction( const ::Point& rStartPoint, const ::Point& rEndPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) : maStartPoint( rStartPoint ), maEndPoint( rEndPoint ), mpCanvas( rCanvas ), maState() { tools::initRenderState(maState,rState); maState.DeviceColor = rState.lineColor; } bool LineAction::render( const ::basegfx::B2DHomMatrix& rTransformation ) const { RTL_LOGFILE_CONTEXT( aLog, "::cppcanvas::internal::LineAction::render()" ); RTL_LOGFILE_CONTEXT_TRACE1( aLog, "::cppcanvas::internal::LineAction: 0x%X", this ); rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); mpCanvas->getUNOCanvas()->drawLine( ::vcl::unotools::point2DFromPoint(maStartPoint), ::vcl::unotools::point2DFromPoint(maEndPoint), mpCanvas->getViewState(), aLocalState ); return true; } bool LineAction::render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // line only contains a single action, fail if subset // requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return false; return render( rTransformation ); } ::basegfx::B2DRange LineAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const { rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); return tools::calcDevicePixelBounds( ::basegfx::B2DRange( maStartPoint.X(), maStartPoint.Y(), maEndPoint.X(), maEndPoint.Y() ), mpCanvas->getViewState(), aLocalState ); } ::basegfx::B2DRange LineAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // line only contains a single action, empty bounds // if subset requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return ::basegfx::B2DRange(); return getBounds( rTransformation ); } sal_Int32 LineAction::getActionCount() const { return 1; } } ActionSharedPtr LineActionFactory::createLineAction( const ::Point& rStartPoint, const ::Point& rEndPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) { return ActionSharedPtr( new LineAction( rStartPoint, rEndPoint, rCanvas, rState) ); } } } <|endoftext|>
<commit_before>#include "n_text_list_selector.h" #include <window/n_list_dialog.h> #include <n_project.h> NTextListSelector::NTextListSelector(QWidget *parent) : QPushButton(parent) { connect(this, SIGNAL(clicked()), this, SLOT(execListDialog())); this->setFlat(true); this->setStyleSheet("QPushButton { \ background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(230, 230, 230, 255), stop:1 rgba(200, 200, 200, 255)); \ border: 1px solid #aaaaaa; \ text-align: left;\ }"); } NTextListSelector::NTextListSelector(TYPE type, QWidget *parent) : NTextListSelector(parent) { mType = type; } void NTextListSelector::setType(TYPE type) { mType = type; } NTextListSelector::TYPE NTextListSelector::getType() { return mType; } void NTextListSelector::setText(const QString &text) { QString oldText = this->text(); QPushButton::setText(text); this->setToolTip(text); if (oldText != text) { emit this->textChanged(text); } } void NTextListSelector::execListDialog() { NListDialog dialog; QStringList list; switch(mType) { case LAYOUT: list = NProject::instance()->layouts(); break; case PAGE: list = NProject::instance()->pages(); break; case SCENE: list = NProject::instance()->scenes(); break; case LINK: list = NProject::instance()->links(); break; case IMAGE: list = NProject::instance()->images(); break; } dialog.setTextList(list); dialog.setCurrentText(this->text()); int exec = dialog.exec(); if (exec == NListDialog::Accepted) { QString text = dialog.selectedText(); this->setText(text); } } <commit_msg>styleをちょっと変更.<commit_after>#include "n_text_list_selector.h" #include <window/n_list_dialog.h> #include <n_project.h> NTextListSelector::NTextListSelector(QWidget *parent) : QPushButton(parent) { connect(this, SIGNAL(clicked()), this, SLOT(execListDialog())); this->setFlat(true); this->setStyleSheet("QPushButton { \ text-align: left;\ }"); } NTextListSelector::NTextListSelector(TYPE type, QWidget *parent) : NTextListSelector(parent) { mType = type; } void NTextListSelector::setType(TYPE type) { mType = type; } NTextListSelector::TYPE NTextListSelector::getType() { return mType; } void NTextListSelector::setText(const QString &text) { QString oldText = this->text(); QPushButton::setText(text); this->setToolTip(text); if (oldText != text) { emit this->textChanged(text); } } void NTextListSelector::execListDialog() { NListDialog dialog; QStringList list; switch(mType) { case LAYOUT: list = NProject::instance()->layouts(); break; case PAGE: list = NProject::instance()->pages(); break; case SCENE: list = NProject::instance()->scenes(); break; case LINK: list = NProject::instance()->links(); break; case IMAGE: list = NProject::instance()->images(); break; } dialog.setTextList(list); dialog.setCurrentText(this->text()); int exec = dialog.exec(); if (exec == NListDialog::Accepted) { QString text = dialog.selectedText(); this->setText(text); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: querydlg.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2006-09-17 07:27:09 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_QUERYDLG_HXX #include "querydlg.hxx" #endif #ifndef _DBU_QRY_HRC_ #include "dbu_qry.hrc" #endif #ifndef DBAUI_QUERYDLG_HRC #include "querydlg.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef DBAUI_QTABLECONNECTIONDATA_HXX #include "QTableConnectionData.hxx" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef DBAUI_QUERYCONTROLLER_HXX #include "querycontroller.hxx" #endif #ifndef DBAUI_QUERYTABLEVIEW_HXX #include "QueryTableView.hxx" #endif #ifndef DBAUI_QUERYDESIGNVIEW_HXX #include "QueryDesignView.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_ #include <com/sun/star/sdbc/XDatabaseMetaData.hpp> #endif #ifndef DBAUI_RELATIONCONTROL_HXX #include "RelationControl.hxx" #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif using namespace dbaui; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; DBG_NAME(DlgQryJoin) DlgQryJoin::DlgQryJoin( Window * pParent, OQueryTableConnectionData* _pData, OJoinTableView::OTableWindowMap* _pTableMap, const Reference< XConnection >& _xConnection, BOOL _bAllowTableSelect) :ModalDialog( pParent, ModuleRes(DLG_QRY_JOIN) ) ,aFL_Join( this, ResId( FL_JOIN ) ) ,aFT_Title( this, ResId(FT_LISTBOXTITLE) ) ,aLB_JoinType( this, ResId(LB_JOINTYPE) ) ,aML_HelpText( this, ResId(ML_HELPTEXT) ) ,aPB_OK( this, ResId( PB_OK ) ) ,aPB_CANCEL( this, ResId( PB_CANCEL ) ) ,aPB_HELP( this, ResId( PB_HELP ) ) ,m_pTableControl( NULL ) ,m_pTableMap(_pTableMap) ,eJoinType(_pData->GetJoinType()) ,m_pConnData(NULL) ,m_pOrigConnData(_pData) ,m_xConnection(_xConnection) { DBG_CTOR(DlgQryJoin,NULL); aML_HelpText.SetControlBackground( GetSettings().GetStyleSettings().GetFaceColor() ); ////////////////////////////////////////////////////////////////////// // Connection kopieren m_pConnData = static_cast<OQueryTableConnectionData*>(_pData->NewInstance()); m_pConnData->CopyFrom(*_pData); m_pTableControl = new OTableListBoxControl(this,ModuleRes(WND_CONTROL),m_pTableMap,this); if( _bAllowTableSelect ) { m_pTableControl->Init( m_pConnData ); m_pTableControl->fillListBoxes(); } else { m_pTableControl->fillAndDisable(m_pConnData); m_pTableControl->Init( m_pConnData ); } m_pTableControl->lateInit(); sal_Bool bFull = sal_False; sal_Bool bOuter = sal_False; Reference<XDatabaseMetaData> xMeta; try { xMeta = m_xConnection->getMetaData(); if ( xMeta.is() ) bFull = xMeta->supportsFullOuterJoins(); } catch(SQLException&) { } try { if ( xMeta.is() ) bOuter= xMeta->supportsOuterJoins(); } catch(SQLException&) { } setJoinType(eJoinType); aPB_OK.SetClickHdl( LINK(this, DlgQryJoin, OKClickHdl) ); aLB_JoinType.SetSelectHdl(LINK(this,DlgQryJoin,LBChangeHdl)); if ( static_cast<OQueryTableView*>(pParent)->getDesignView()->getController()->isReadOnly() ) { aLB_JoinType.Disable(); m_pTableControl->Disable(); } else if ( !bFull && !bOuter ) aLB_JoinType.Disable(); else { if ( !bFull ) aLB_JoinType.RemoveEntry(3); if ( !bOuter ) { aLB_JoinType.RemoveEntry(0); aLB_JoinType.RemoveEntry(0); aLB_JoinType.RemoveEntry(0); } m_pTableControl->NotifyCellChange(); } FreeResource(); } //------------------------------------------------------------------------ DlgQryJoin::~DlgQryJoin() { DBG_DTOR(DlgQryJoin,NULL); delete m_pTableControl; delete m_pConnData; } // ----------------------------------------------------------------------------- IMPL_LINK( DlgQryJoin, LBChangeHdl, ListBox*, /*pListBox*/ ) { DBG_CHKTHIS(DlgQryJoin,NULL); aML_HelpText.SetText(String()); String sFirstWinName,sSecondWinName; USHORT nResId = 0; USHORT nPos = aLB_JoinType.GetSelectEntryPos(); sal_Bool bAddHint = sal_True; switch ( nPos ) { default: case 0: nResId = STR_QUERY_INNER_JOIN; bAddHint = sal_False; break; case 1: nResId = STR_QUERY_LEFTRIGHT_JOIN; sFirstWinName = m_pConnData->GetSourceWinName(); sSecondWinName = m_pConnData->GetDestWinName(); break; case 2: case 3: nResId = (nPos == 2) ? STR_QUERY_LEFTRIGHT_JOIN : STR_QUERY_FULL_JOIN; sFirstWinName = m_pConnData->GetDestWinName(); sSecondWinName = m_pConnData->GetSourceWinName(); break; } String sHelpText = String( ModuleRes( nResId ) ); if( sFirstWinName.Len() ) { sHelpText.SearchAndReplace( String( RTL_CONSTASCII_STRINGPARAM( "%1" ) ), sFirstWinName ); sHelpText.SearchAndReplace( String( RTL_CONSTASCII_STRINGPARAM( "%2" ) ), sSecondWinName ); } if ( bAddHint ) { sHelpText += String( RTL_CONSTASCII_STRINGPARAM( "\n" ) ); sHelpText += String( ModuleRes( STR_JOIN_TYPE_HINT ) ); } aML_HelpText.SetText( sHelpText ); return 1; } // ----------------------------------------------------------------------------- IMPL_LINK( DlgQryJoin, OKClickHdl, Button*, /*pButton*/ ) { DBG_CHKTHIS(DlgQryJoin,NULL); USHORT nPos = aLB_JoinType.GetSelectEntryPos(); switch ( nPos ) { case 0: eJoinType = INNER_JOIN; break; case 1: eJoinType = LEFT_JOIN; break; case 2: eJoinType = RIGHT_JOIN; break; case 3: eJoinType = FULL_JOIN; break; } m_pConnData->Update(); m_pOrigConnData->CopyFrom( *m_pConnData ); EndDialog(RET_OK); return 1; } // ----------------------------------------------------------------------------- OTableConnectionData* DlgQryJoin::getConnectionData() const { return m_pConnData; } // ----------------------------------------------------------------------------- void DlgQryJoin::setValid(sal_Bool _bValid) { LBChangeHdl(&aLB_JoinType); aPB_OK.Enable(_bValid); } // ----------------------------------------------------------------------------- void DlgQryJoin::notifyConnectionChange( ) { setJoinType( m_pConnData->GetJoinType() ); } // ----------------------------------------------------------------------------- void DlgQryJoin::setJoinType(EJoinType _eNewJoinType) { eJoinType = _eNewJoinType; USHORT nPos = 0; switch(eJoinType) { case INNER_JOIN: break; case LEFT_JOIN: nPos = 1; break; case RIGHT_JOIN: nPos = 2; break; case FULL_JOIN: nPos = 3; break; default: break; } aLB_JoinType.SelectEntryPos(nPos); LBChangeHdl(&aLB_JoinType); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS residcleanup (1.13.80); FILE MERGED 2007/02/26 22:58:52 pl 1.13.80.1: #i74635# no more ResMgr default<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: querydlg.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: rt $ $Date: 2007-04-26 08:03:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_QUERYDLG_HXX #include "querydlg.hxx" #endif #ifndef _DBU_QRY_HRC_ #include "dbu_qry.hrc" #endif #ifndef DBAUI_QUERYDLG_HRC #include "querydlg.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef DBAUI_QTABLECONNECTIONDATA_HXX #include "QTableConnectionData.hxx" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef DBAUI_QUERYCONTROLLER_HXX #include "querycontroller.hxx" #endif #ifndef DBAUI_QUERYTABLEVIEW_HXX #include "QueryTableView.hxx" #endif #ifndef DBAUI_QUERYDESIGNVIEW_HXX #include "QueryDesignView.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_ #include <com/sun/star/sdbc/XDatabaseMetaData.hpp> #endif #ifndef DBAUI_RELATIONCONTROL_HXX #include "RelationControl.hxx" #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif using namespace dbaui; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; DBG_NAME(DlgQryJoin) DlgQryJoin::DlgQryJoin( Window * pParent, OQueryTableConnectionData* _pData, OJoinTableView::OTableWindowMap* _pTableMap, const Reference< XConnection >& _xConnection, BOOL _bAllowTableSelect) :ModalDialog( pParent, ModuleRes(DLG_QRY_JOIN) ) ,aFL_Join( this, ModuleRes( FL_JOIN ) ) ,aFT_Title( this, ModuleRes(FT_LISTBOXTITLE) ) ,aLB_JoinType( this, ModuleRes(LB_JOINTYPE) ) ,aML_HelpText( this, ModuleRes(ML_HELPTEXT) ) ,aPB_OK( this, ModuleRes( PB_OK ) ) ,aPB_CANCEL( this, ModuleRes( PB_CANCEL ) ) ,aPB_HELP( this, ModuleRes( PB_HELP ) ) ,m_pTableControl( NULL ) ,m_pTableMap(_pTableMap) ,eJoinType(_pData->GetJoinType()) ,m_pConnData(NULL) ,m_pOrigConnData(_pData) ,m_xConnection(_xConnection) { DBG_CTOR(DlgQryJoin,NULL); aML_HelpText.SetControlBackground( GetSettings().GetStyleSettings().GetFaceColor() ); ////////////////////////////////////////////////////////////////////// // Connection kopieren m_pConnData = static_cast<OQueryTableConnectionData*>(_pData->NewInstance()); m_pConnData->CopyFrom(*_pData); m_pTableControl = new OTableListBoxControl(this,ModuleRes(WND_CONTROL),m_pTableMap,this); if( _bAllowTableSelect ) { m_pTableControl->Init( m_pConnData ); m_pTableControl->fillListBoxes(); } else { m_pTableControl->fillAndDisable(m_pConnData); m_pTableControl->Init( m_pConnData ); } m_pTableControl->lateInit(); sal_Bool bFull = sal_False; sal_Bool bOuter = sal_False; Reference<XDatabaseMetaData> xMeta; try { xMeta = m_xConnection->getMetaData(); if ( xMeta.is() ) bFull = xMeta->supportsFullOuterJoins(); } catch(SQLException&) { } try { if ( xMeta.is() ) bOuter= xMeta->supportsOuterJoins(); } catch(SQLException&) { } setJoinType(eJoinType); aPB_OK.SetClickHdl( LINK(this, DlgQryJoin, OKClickHdl) ); aLB_JoinType.SetSelectHdl(LINK(this,DlgQryJoin,LBChangeHdl)); if ( static_cast<OQueryTableView*>(pParent)->getDesignView()->getController()->isReadOnly() ) { aLB_JoinType.Disable(); m_pTableControl->Disable(); } else if ( !bFull && !bOuter ) aLB_JoinType.Disable(); else { if ( !bFull ) aLB_JoinType.RemoveEntry(3); if ( !bOuter ) { aLB_JoinType.RemoveEntry(0); aLB_JoinType.RemoveEntry(0); aLB_JoinType.RemoveEntry(0); } m_pTableControl->NotifyCellChange(); } FreeResource(); } //------------------------------------------------------------------------ DlgQryJoin::~DlgQryJoin() { DBG_DTOR(DlgQryJoin,NULL); delete m_pTableControl; delete m_pConnData; } // ----------------------------------------------------------------------------- IMPL_LINK( DlgQryJoin, LBChangeHdl, ListBox*, /*pListBox*/ ) { DBG_CHKTHIS(DlgQryJoin,NULL); aML_HelpText.SetText(String()); String sFirstWinName,sSecondWinName; USHORT nResId = 0; USHORT nPos = aLB_JoinType.GetSelectEntryPos(); sal_Bool bAddHint = sal_True; switch ( nPos ) { default: case 0: nResId = STR_QUERY_INNER_JOIN; bAddHint = sal_False; break; case 1: nResId = STR_QUERY_LEFTRIGHT_JOIN; sFirstWinName = m_pConnData->GetSourceWinName(); sSecondWinName = m_pConnData->GetDestWinName(); break; case 2: case 3: nResId = (nPos == 2) ? STR_QUERY_LEFTRIGHT_JOIN : STR_QUERY_FULL_JOIN; sFirstWinName = m_pConnData->GetDestWinName(); sSecondWinName = m_pConnData->GetSourceWinName(); break; } String sHelpText = String( ModuleRes( nResId ) ); if( sFirstWinName.Len() ) { sHelpText.SearchAndReplace( String( RTL_CONSTASCII_STRINGPARAM( "%1" ) ), sFirstWinName ); sHelpText.SearchAndReplace( String( RTL_CONSTASCII_STRINGPARAM( "%2" ) ), sSecondWinName ); } if ( bAddHint ) { sHelpText += String( RTL_CONSTASCII_STRINGPARAM( "\n" ) ); sHelpText += String( ModuleRes( STR_JOIN_TYPE_HINT ) ); } aML_HelpText.SetText( sHelpText ); return 1; } // ----------------------------------------------------------------------------- IMPL_LINK( DlgQryJoin, OKClickHdl, Button*, /*pButton*/ ) { DBG_CHKTHIS(DlgQryJoin,NULL); USHORT nPos = aLB_JoinType.GetSelectEntryPos(); switch ( nPos ) { case 0: eJoinType = INNER_JOIN; break; case 1: eJoinType = LEFT_JOIN; break; case 2: eJoinType = RIGHT_JOIN; break; case 3: eJoinType = FULL_JOIN; break; } m_pConnData->Update(); m_pOrigConnData->CopyFrom( *m_pConnData ); EndDialog(RET_OK); return 1; } // ----------------------------------------------------------------------------- OTableConnectionData* DlgQryJoin::getConnectionData() const { return m_pConnData; } // ----------------------------------------------------------------------------- void DlgQryJoin::setValid(sal_Bool _bValid) { LBChangeHdl(&aLB_JoinType); aPB_OK.Enable(_bValid); } // ----------------------------------------------------------------------------- void DlgQryJoin::notifyConnectionChange( ) { setJoinType( m_pConnData->GetJoinType() ); } // ----------------------------------------------------------------------------- void DlgQryJoin::setJoinType(EJoinType _eNewJoinType) { eJoinType = _eNewJoinType; USHORT nPos = 0; switch(eJoinType) { case INNER_JOIN: break; case LEFT_JOIN: nPos = 1; break; case RIGHT_JOIN: nPos = 2; break; case FULL_JOIN: nPos = 3; break; default: break; } aLB_JoinType.SelectEntryPos(nPos); LBChangeHdl(&aLB_JoinType); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "Var.h" void *Var::operator new (size_t n, Pool *pool) { return pool -> palloc(sizeof(Var)); } void Var::operator delete(void* ptr, Pool *pool) { free(ptr); } void Var::get_expression(ostream &out, string wrapEntity, Position position) { if (wrapEntity == "App" && position == _right) out << ' '; out << variable; } vector<string> Var::get_tree_view(int shift) { vector<string> treeAll; treeAll.push_back(string(shift, ' ') + variable); return treeAll; } Node *Var::reduce(Pool *pool) { return this; } Node *Var::substitute(Pool *pool, Node *substituteTo, Var *substituteThis) { if (this == substituteThis) return substituteTo->copy(pool); else return this; } bool Var::is_redex() { return false; } Var *Var::copy(Pool *pool) { return new(pool) Var(variable); } <commit_msg>Changed get_tree_view function to print adresses of variables<commit_after>#include "Var.h" #include <sstream> void *Var::operator new (size_t n, Pool *pool) { return pool -> palloc(sizeof(Var)); } void Var::operator delete(void* ptr, Pool *pool) { free(ptr); } void Var::get_expression(ostream &out, string wrapEntity, Position position) { if (wrapEntity == "App" && position == _right) out << ' '; out << variable; } vector<string> Var::get_tree_view(int shift) { stringstream convert; convert << this; vector<string> treeAll; treeAll.push_back(string(shift, ' ') + variable + ' ' + convert.str() + ' '); return treeAll; } Node *Var::reduce(Pool *pool) { return this; } Node *Var::substitute(Pool *pool, Node *substituteTo, Var *substituteThis) { if (this == substituteThis) return substituteTo->copy(pool); else return this; } bool Var::is_redex() { return false; } Var *Var::copy(Pool *pool) { return new(pool) Var(variable); } <|endoftext|>
<commit_before>//===--- Term.cpp - A term in the generics rewrite system -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/AST/Decl.h" #include "swift/AST/Types.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <vector> #include "RewriteContext.h" #include "Symbol.h" #include "Term.h" using namespace swift; using namespace rewriting; /// Terms are uniqued and immutable, stored as a single pointer; /// the Storage type is the allocated backing storage. struct Term::Storage final : public llvm::FoldingSetNode, public llvm::TrailingObjects<Storage, Symbol> { friend class Symbol; unsigned Size; explicit Storage(unsigned size) : Size(size) {} size_t numTrailingObjects(OverloadToken<Symbol>) const { return Size; } MutableArrayRef<Symbol> getElements() { return {getTrailingObjects<Symbol>(), Size}; } ArrayRef<Symbol> getElements() const { return {getTrailingObjects<Symbol>(), Size}; } void Profile(llvm::FoldingSetNodeID &id) const; }; size_t Term::size() const { return Ptr->Size; } const Symbol *Term::begin() const { return Ptr->getElements().begin(); } const Symbol *Term::end() const { return Ptr->getElements().end(); } std::reverse_iterator<const Symbol *> Term::rbegin() const { return Ptr->getElements().rbegin(); } std::reverse_iterator<const Symbol *> Term::rend() const { return Ptr->getElements().rend(); } Symbol Term::back() const { return Ptr->getElements().back(); } Symbol Term::operator[](size_t index) const { return Ptr->getElements()[index]; } void Term::dump(llvm::raw_ostream &out) const { MutableTerm(*this).dump(out); } Term Term::get(const MutableTerm &mutableTerm, RewriteContext &ctx) { unsigned size = mutableTerm.size(); assert(size > 0 && "Term must have at least one symbol"); llvm::FoldingSetNodeID id; id.AddInteger(size); for (auto symbol : mutableTerm) id.AddPointer(symbol.getOpaquePointer()); void *insertPos = nullptr; if (auto *term = ctx.Terms.FindNodeOrInsertPos(id, insertPos)) return term; void *mem = ctx.Allocator.Allocate( Storage::totalSizeToAlloc<Symbol>(size), alignof(Storage)); auto *term = new (mem) Storage(size); for (unsigned i = 0; i < size; ++i) term->getElements()[i] = mutableTerm[i]; ctx.Terms.InsertNode(term, insertPos); ctx.TermHistogram.add(size); return term; } void Term::Storage::Profile(llvm::FoldingSetNodeID &id) const { id.AddInteger(Size); for (auto symbol : getElements()) id.AddPointer(symbol.getOpaquePointer()); } bool Term::containsUnresolvedSymbols() const { for (auto symbol : *this) { if (symbol.getKind() == Symbol::Kind::Name) return true; } return false; } /// Shortlex order on symbol ranges. /// /// First we compare length, then perform a lexicographic comparison /// on symbols if the two ranges have the same length. /// /// This is used to implement Term::compare() and MutableTerm::compare() /// below. static Optional<int> shortlexCompare(const Symbol *lhsBegin, const Symbol *lhsEnd, const Symbol *rhsBegin, const Symbol *rhsEnd, RewriteContext &ctx) { unsigned lhsSize = (lhsEnd - lhsBegin); unsigned rhsSize = (rhsEnd - rhsBegin); if (lhsSize != rhsSize) return lhsSize < rhsSize ? -1 : 1; while (lhsBegin != lhsEnd) { auto lhs = *lhsBegin; auto rhs = *rhsBegin; ++lhsBegin; ++rhsBegin; Optional<int> result = lhs.compare(rhs, ctx); if (!result.hasValue() || *result != 0) { assert(lhs != rhs); return result; } assert(lhs == rhs); } return 0; } /// Shortlex order on terms. Returns None if the terms are identical except /// for an incomparable superclass or concrete type symbol at the end. Optional<int> Term::compare(Term other, RewriteContext &ctx) const { return shortlexCompare(begin(), end(), other.begin(), other.end(), ctx); } /// Shortlex order on mutable terms. Returns None if the terms are identical /// except for an incomparable superclass or concrete type symbol at the end. Optional<int> MutableTerm::compare(const MutableTerm &other, RewriteContext &ctx) const { return shortlexCompare(begin(), end(), other.begin(), other.end(), ctx); } /// Replace the subterm in the range [from,to) with \p rhs. The subrange must /// be part of this term itself. /// /// Note that \p rhs must precede [from,to) in the linear order on terms. void MutableTerm::rewriteSubTerm(Symbol *from, Symbol *to, Term rhs) { auto oldSize = size(); unsigned lhsLength = (unsigned)(to - from); assert(rhs.size() <= lhsLength); // Overwrite the occurrence of the left hand side with the // right hand side. auto newIter = std::copy(rhs.begin(), rhs.end(), from); // If the right hand side is shorter than the left hand side, // then newIter will point to a location before oldIter, eg // if this term is 'T.A.B.C', lhs is 'A.B' and rhs is 'X', // then we now have: // // T.X .C // ^--- oldIter // ^--- newIter // // Shift everything over to close the gap (by one location, // in this case). if (newIter != to) { auto newEnd = std::copy(to, end(), newIter); // Now, we've moved the gap to the end of the term; close // it by shortening the term. Symbols.erase(newEnd, end()); } assert(size() == oldSize - lhsLength + rhs.size()); } void MutableTerm::dump(llvm::raw_ostream &out) const { bool first = true; for (auto symbol : Symbols) { if (!first) out << "."; else first = false; symbol.dump(out); } }<commit_msg>RequirementMachine: Allow MutableTerm::rewriteSubTerm() to make the term longer<commit_after>//===--- Term.cpp - A term in the generics rewrite system -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/AST/Decl.h" #include "swift/AST/Types.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <vector> #include "RewriteContext.h" #include "Symbol.h" #include "Term.h" using namespace swift; using namespace rewriting; /// Terms are uniqued and immutable, stored as a single pointer; /// the Storage type is the allocated backing storage. struct Term::Storage final : public llvm::FoldingSetNode, public llvm::TrailingObjects<Storage, Symbol> { friend class Symbol; unsigned Size; explicit Storage(unsigned size) : Size(size) {} size_t numTrailingObjects(OverloadToken<Symbol>) const { return Size; } MutableArrayRef<Symbol> getElements() { return {getTrailingObjects<Symbol>(), Size}; } ArrayRef<Symbol> getElements() const { return {getTrailingObjects<Symbol>(), Size}; } void Profile(llvm::FoldingSetNodeID &id) const; }; size_t Term::size() const { return Ptr->Size; } const Symbol *Term::begin() const { return Ptr->getElements().begin(); } const Symbol *Term::end() const { return Ptr->getElements().end(); } std::reverse_iterator<const Symbol *> Term::rbegin() const { return Ptr->getElements().rbegin(); } std::reverse_iterator<const Symbol *> Term::rend() const { return Ptr->getElements().rend(); } Symbol Term::back() const { return Ptr->getElements().back(); } Symbol Term::operator[](size_t index) const { return Ptr->getElements()[index]; } void Term::dump(llvm::raw_ostream &out) const { MutableTerm(*this).dump(out); } Term Term::get(const MutableTerm &mutableTerm, RewriteContext &ctx) { unsigned size = mutableTerm.size(); assert(size > 0 && "Term must have at least one symbol"); llvm::FoldingSetNodeID id; id.AddInteger(size); for (auto symbol : mutableTerm) id.AddPointer(symbol.getOpaquePointer()); void *insertPos = nullptr; if (auto *term = ctx.Terms.FindNodeOrInsertPos(id, insertPos)) return term; void *mem = ctx.Allocator.Allocate( Storage::totalSizeToAlloc<Symbol>(size), alignof(Storage)); auto *term = new (mem) Storage(size); for (unsigned i = 0; i < size; ++i) term->getElements()[i] = mutableTerm[i]; ctx.Terms.InsertNode(term, insertPos); ctx.TermHistogram.add(size); return term; } void Term::Storage::Profile(llvm::FoldingSetNodeID &id) const { id.AddInteger(Size); for (auto symbol : getElements()) id.AddPointer(symbol.getOpaquePointer()); } bool Term::containsUnresolvedSymbols() const { for (auto symbol : *this) { if (symbol.getKind() == Symbol::Kind::Name) return true; } return false; } /// Shortlex order on symbol ranges. /// /// First we compare length, then perform a lexicographic comparison /// on symbols if the two ranges have the same length. /// /// This is used to implement Term::compare() and MutableTerm::compare() /// below. static Optional<int> shortlexCompare(const Symbol *lhsBegin, const Symbol *lhsEnd, const Symbol *rhsBegin, const Symbol *rhsEnd, RewriteContext &ctx) { unsigned lhsSize = (lhsEnd - lhsBegin); unsigned rhsSize = (rhsEnd - rhsBegin); if (lhsSize != rhsSize) return lhsSize < rhsSize ? -1 : 1; while (lhsBegin != lhsEnd) { auto lhs = *lhsBegin; auto rhs = *rhsBegin; ++lhsBegin; ++rhsBegin; Optional<int> result = lhs.compare(rhs, ctx); if (!result.hasValue() || *result != 0) { assert(lhs != rhs); return result; } assert(lhs == rhs); } return 0; } /// Shortlex order on terms. Returns None if the terms are identical except /// for an incomparable superclass or concrete type symbol at the end. Optional<int> Term::compare(Term other, RewriteContext &ctx) const { return shortlexCompare(begin(), end(), other.begin(), other.end(), ctx); } /// Shortlex order on mutable terms. Returns None if the terms are identical /// except for an incomparable superclass or concrete type symbol at the end. Optional<int> MutableTerm::compare(const MutableTerm &other, RewriteContext &ctx) const { return shortlexCompare(begin(), end(), other.begin(), other.end(), ctx); } /// Replace the subterm in the range [from,to) of this term with \p rhs. void MutableTerm::rewriteSubTerm(Symbol *from, Symbol *to, Term rhs) { auto oldSize = size(); unsigned lhsLength = (unsigned)(to - from); if (lhsLength == rhs.size()) { // Copy the RHS to the LHS. auto newTo = std::copy(rhs.begin(), rhs.end(), from); // The RHS has the same length as the LHS, so we're done. assert(newTo == to); (void) newTo; } else if (lhsLength > rhs.size()) { // Copy the RHS to the LHS. auto newTo = std::copy(rhs.begin(), rhs.end(), from); // Shorten the term. Symbols.erase(newTo, to); } else { assert(lhsLength < rhs.size()); // Copy the LHS-sized prefix of RHS to the LHS. auto newTo = std::copy(rhs.begin(), rhs.begin() + lhsLength, from); assert(newTo == to); // Insert the remainder of the RHS term. Symbols.insert(to, rhs.begin() + lhsLength, rhs.end()); } assert(size() == oldSize - lhsLength + rhs.size()); } void MutableTerm::dump(llvm::raw_ostream &out) const { bool first = true; for (auto symbol : Symbols) { if (!first) out << "."; else first = false; symbol.dump(out); } }<|endoftext|>
<commit_before>/** \brief Importer for full text documents. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * 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 <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "FullTextImport.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] fulltext_file1 [fulltext_file2 .. fulltext_fileN]\n"; std::exit(EXIT_FAILURE); } bool ImportDocument(ControlNumberGuesser &control_number_guesser, const std::string &filename) { const auto input(FileUtil::OpenInputFileOrDie(filename)); FullTextImport::FullTextData full_text_data; FullTextImport::ReadExtractedTextFromDisk(input.get(), &full_text_data); std::string ppn; if (not FullTextImport::CorrelateFullTextData(control_number_guesser, full_text_data, &ppn)) return false; return true; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 2) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; if (argc < 2) Usage(); ControlNumberGuesser control_number_guesser; unsigned total_count(0), failure_count(0); for (int arg_no(1); arg_no < argc; ++arg_no) { ++total_count; if (not ImportDocument(control_number_guesser, argv[arg_no])) ++failure_count; } LOG_INFO("Failed to import " + std::to_string(failure_count) + " documents of " + std::to_string(total_count) + "."); return EXIT_SUCCESS; } <commit_msg>Used our Usage library function.<commit_after>/** \brief Importer for full text documents. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * 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 <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "FullTextImport.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("[--verbose] fulltext_file1 [fulltext_file2 .. fulltext_fileN]"); } bool ImportDocument(ControlNumberGuesser &control_number_guesser, const std::string &filename) { const auto input(FileUtil::OpenInputFileOrDie(filename)); FullTextImport::FullTextData full_text_data; FullTextImport::ReadExtractedTextFromDisk(input.get(), &full_text_data); std::string ppn; if (not FullTextImport::CorrelateFullTextData(control_number_guesser, full_text_data, &ppn)) return false; return true; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 2) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; if (argc < 2) Usage(); ControlNumberGuesser control_number_guesser; unsigned total_count(0), failure_count(0); for (int arg_no(1); arg_no < argc; ++arg_no) { ++total_count; if (not ImportDocument(control_number_guesser, argv[arg_no])) ++failure_count; } LOG_INFO("Failed to import " + std::to_string(failure_count) + " documents of " + std::to_string(total_count) + "."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//===-- TargetInstrInfoImpl.cpp - Target Instruction Information ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TargetInstrInfoImpl class, it just provides default // implementations of various methods. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetInstrInfo.h" #include "llvm/ADT/SmallVector.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" using namespace llvm; // commuteInstruction - The default implementation of this method just exchanges // operand 1 and 2. MachineInstr *TargetInstrInfoImpl::commuteInstruction(MachineInstr *MI, bool NewMI) const { assert(MI->getOperand(1).isRegister() && MI->getOperand(2).isRegister() && "This only knows how to commute register operands so far"); unsigned Reg1 = MI->getOperand(1).getReg(); unsigned Reg2 = MI->getOperand(2).getReg(); bool Reg1IsKill = MI->getOperand(1).isKill(); bool Reg2IsKill = MI->getOperand(2).isKill(); bool ChangeReg0 = false; if (MI->getOperand(0).getReg() == Reg1) { // Must be two address instruction! assert(MI->getDesc().getOperandConstraint(0, TOI::TIED_TO) && "Expecting a two-address instruction!"); Reg2IsKill = false; ChangeReg0 = true; } if (NewMI) { // Create a new instruction. unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg(); bool Reg0IsDead = MI->getOperand(0).isDead(); MachineFunction &MF = *MI->getParent()->getParent(); return BuildMI(MF, MI->getDesc()) .addReg(Reg0, true, false, false, Reg0IsDead) .addReg(Reg2, false, false, Reg2IsKill) .addReg(Reg1, false, false, Reg1IsKill); } if (ChangeReg0) MI->getOperand(0).setReg(Reg2); MI->getOperand(2).setReg(Reg1); MI->getOperand(1).setReg(Reg2); MI->getOperand(2).setIsKill(Reg1IsKill); MI->getOperand(1).setIsKill(Reg2IsKill); return MI; } /// CommuteChangesDestination - Return true if commuting the specified /// instruction will also changes the destination operand. Also return the /// current operand index of the would be new destination register by /// reference. This can happen when the commutable instruction is also a /// two-address instruction. bool TargetInstrInfoImpl::CommuteChangesDestination(MachineInstr *MI, unsigned &OpIdx) const{ assert(MI->getOperand(1).isRegister() && MI->getOperand(2).isRegister() && "This only knows how to commute register operands so far"); if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) { // Must be two address instruction! assert(MI->getDesc().getOperandConstraint(0, TOI::TIED_TO) && "Expecting a two-address instruction!"); OpIdx = 2; return true; } return false; } bool TargetInstrInfoImpl::PredicateInstruction(MachineInstr *MI, const SmallVectorImpl<MachineOperand> &Pred) const { bool MadeChange = false; const TargetInstrDesc &TID = MI->getDesc(); if (!TID.isPredicable()) return false; for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) { if (TID.OpInfo[i].isPredicate()) { MachineOperand &MO = MI->getOperand(i); if (MO.isReg()) { MO.setReg(Pred[j].getReg()); MadeChange = true; } else if (MO.isImm()) { MO.setImm(Pred[j].getImm()); MadeChange = true; } else if (MO.isMBB()) { MO.setMBB(Pred[j].getMBB()); MadeChange = true; } ++j; } } return MadeChange; } void TargetInstrInfoImpl::reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, const MachineInstr *Orig) const { MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig); MI->getOperand(0).setReg(DestReg); MBB.insert(I, MI); } unsigned TargetInstrInfoImpl::GetFunctionSizeInBytes(const MachineFunction &MF) const { unsigned FnSize = 0; for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end(); MBBI != E; ++MBBI) { const MachineBasicBlock &MBB = *MBBI; for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end(); I != E; ++I) FnSize += GetInstSizeInBytes(I); } return FnSize; } <commit_msg>Fix a 80 column violation.<commit_after>//===-- TargetInstrInfoImpl.cpp - Target Instruction Information ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TargetInstrInfoImpl class, it just provides default // implementations of various methods. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetInstrInfo.h" #include "llvm/ADT/SmallVector.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" using namespace llvm; // commuteInstruction - The default implementation of this method just exchanges // operand 1 and 2. MachineInstr *TargetInstrInfoImpl::commuteInstruction(MachineInstr *MI, bool NewMI) const { assert(MI->getOperand(1).isRegister() && MI->getOperand(2).isRegister() && "This only knows how to commute register operands so far"); unsigned Reg1 = MI->getOperand(1).getReg(); unsigned Reg2 = MI->getOperand(2).getReg(); bool Reg1IsKill = MI->getOperand(1).isKill(); bool Reg2IsKill = MI->getOperand(2).isKill(); bool ChangeReg0 = false; if (MI->getOperand(0).getReg() == Reg1) { // Must be two address instruction! assert(MI->getDesc().getOperandConstraint(0, TOI::TIED_TO) && "Expecting a two-address instruction!"); Reg2IsKill = false; ChangeReg0 = true; } if (NewMI) { // Create a new instruction. unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg(); bool Reg0IsDead = MI->getOperand(0).isDead(); MachineFunction &MF = *MI->getParent()->getParent(); return BuildMI(MF, MI->getDesc()) .addReg(Reg0, true, false, false, Reg0IsDead) .addReg(Reg2, false, false, Reg2IsKill) .addReg(Reg1, false, false, Reg1IsKill); } if (ChangeReg0) MI->getOperand(0).setReg(Reg2); MI->getOperand(2).setReg(Reg1); MI->getOperand(1).setReg(Reg2); MI->getOperand(2).setIsKill(Reg1IsKill); MI->getOperand(1).setIsKill(Reg2IsKill); return MI; } /// CommuteChangesDestination - Return true if commuting the specified /// instruction will also changes the destination operand. Also return the /// current operand index of the would be new destination register by /// reference. This can happen when the commutable instruction is also a /// two-address instruction. bool TargetInstrInfoImpl::CommuteChangesDestination(MachineInstr *MI, unsigned &OpIdx) const{ assert(MI->getOperand(1).isRegister() && MI->getOperand(2).isRegister() && "This only knows how to commute register operands so far"); if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) { // Must be two address instruction! assert(MI->getDesc().getOperandConstraint(0, TOI::TIED_TO) && "Expecting a two-address instruction!"); OpIdx = 2; return true; } return false; } bool TargetInstrInfoImpl::PredicateInstruction(MachineInstr *MI, const SmallVectorImpl<MachineOperand> &Pred) const { bool MadeChange = false; const TargetInstrDesc &TID = MI->getDesc(); if (!TID.isPredicable()) return false; for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) { if (TID.OpInfo[i].isPredicate()) { MachineOperand &MO = MI->getOperand(i); if (MO.isReg()) { MO.setReg(Pred[j].getReg()); MadeChange = true; } else if (MO.isImm()) { MO.setImm(Pred[j].getImm()); MadeChange = true; } else if (MO.isMBB()) { MO.setMBB(Pred[j].getMBB()); MadeChange = true; } ++j; } } return MadeChange; } void TargetInstrInfoImpl::reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, const MachineInstr *Orig) const { MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig); MI->getOperand(0).setReg(DestReg); MBB.insert(I, MI); } unsigned TargetInstrInfoImpl::GetFunctionSizeInBytes(const MachineFunction &MF) const { unsigned FnSize = 0; for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end(); MBBI != E; ++MBBI) { const MachineBasicBlock &MBB = *MBBI; for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end(); I != E; ++I) FnSize += GetInstSizeInBytes(I); } return FnSize; } <|endoftext|>
<commit_before>//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCJIT.h" #include "MCJITMemoryManager.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Target/TargetData.h" using namespace llvm; namespace { static struct RegisterJIT { RegisterJIT() { MCJIT::Register(); } } JITRegistrator; } extern "C" void LLVMLinkInMCJIT() { } ExecutionEngine *MCJIT::createJIT(Module *M, std::string *ErrorStr, JITMemoryManager *JMM, CodeGenOpt::Level OptLevel, bool GVsWithCode, TargetMachine *TM) { // Try to register the program as a source of symbols to resolve against. // // FIXME: Don't do this here. sys::DynamicLibrary::LoadLibraryPermanently(0, NULL); // If the target supports JIT code generation, create the JIT. if (TargetJITInfo *TJ = TM->getJITInfo()) return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM, M), OptLevel, GVsWithCode); if (ErrorStr) *ErrorStr = "target does not support JIT code generation"; return 0; } MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji, RTDyldMemoryManager *MM, CodeGenOpt::Level OptLevel, bool AllocateGVsWithCode) : ExecutionEngine(m), TM(tm), MemMgr(MM), M(m), OS(Buffer), Dyld(MM) { PM.add(new TargetData(*TM->getTargetData())); // Turn the machine code intermediate representation into bytes in memory // that may be executed. if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) { report_fatal_error("Target does not support MC emission!"); } // Initialize passes. // FIXME: When we support multiple modules, we'll want to move the code // gen and finalization out of the constructor here and do it more // on-demand as part of getPointerToFunction(). PM.run(*M); // Flush the output buffer so the SmallVector gets its data. OS.flush(); // Load the object into the dynamic linker. // FIXME: It would be nice to avoid making yet another copy. MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(), Buffer.size())); if (Dyld.loadObject(MB)) report_fatal_error(Dyld.getErrorString()); // Resolve any relocations. Dyld.resolveRelocations(); } MCJIT::~MCJIT() { delete MemMgr; } void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) { report_fatal_error("not yet implemented"); return 0; } void *MCJIT::getPointerToFunction(Function *F) { if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) { bool AbortOnFailure = !F->hasExternalWeakLinkage(); void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure); addGlobalMapping(F, Addr); return Addr; } // FIXME: Should we be using the mangler for this? Probably. StringRef BaseName = F->getName(); if (BaseName[0] == '\1') BaseName = BaseName.substr(1); else Twine Name = TM->getMCAsmInfo()->getGlobalPrefix() + BaseName; return (void*)Dyld.getSymbolAddress(Name.str()); } void *MCJIT::recompileAndRelinkFunction(Function *F) { report_fatal_error("not yet implemented"); } void MCJIT::freeMachineCodeForFunction(Function *F) { report_fatal_error("not yet implemented"); } GenericValue MCJIT::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert(F && "Function *F was null at entry to run()"); void *FPtr = getPointerToFunction(F); assert(FPtr && "Pointer to fn's code was null after getPointerToFunction"); const FunctionType *FTy = F->getFunctionType(); const Type *RetTy = FTy->getReturnType(); assert((FTy->getNumParams() == ArgValues.size() || (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) && "Wrong number of arguments passed into function!"); assert(FTy->getNumParams() == ArgValues.size() && "This doesn't support passing arguments through varargs (yet)!"); // Handle some common cases first. These cases correspond to common `main' // prototypes. if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) { switch (ArgValues.size()) { case 3: if (FTy->getParamType(0)->isIntegerTy(32) && FTy->getParamType(1)->isPointerTy() && FTy->getParamType(2)->isPointerTy()) { int (*PF)(int, char **, const char **) = (int(*)(int, char **, const char **))(intptr_t)FPtr; // Call the function. GenericValue rv; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), (char **)GVTOP(ArgValues[1]), (const char **)GVTOP(ArgValues[2]))); return rv; } break; case 2: if (FTy->getParamType(0)->isIntegerTy(32) && FTy->getParamType(1)->isPointerTy()) { int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr; // Call the function. GenericValue rv; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), (char **)GVTOP(ArgValues[1]))); return rv; } break; case 1: if (FTy->getNumParams() == 1 && FTy->getParamType(0)->isIntegerTy(32)) { GenericValue rv; int (*PF)(int) = (int(*)(int))(intptr_t)FPtr; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue())); return rv; } break; } } // Handle cases where no arguments are passed first. if (ArgValues.empty()) { GenericValue rv; switch (RetTy->getTypeID()) { default: llvm_unreachable("Unknown return type for function call!"); case Type::IntegerTyID: { unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth(); if (BitWidth == 1) rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)()); else if (BitWidth <= 8) rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)()); else if (BitWidth <= 16) rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)()); else if (BitWidth <= 32) rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)()); else if (BitWidth <= 64) rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)()); else llvm_unreachable("Integer types > 64 bits not supported"); return rv; } case Type::VoidTyID: rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)()); return rv; case Type::FloatTyID: rv.FloatVal = ((float(*)())(intptr_t)FPtr)(); return rv; case Type::DoubleTyID: rv.DoubleVal = ((double(*)())(intptr_t)FPtr)(); return rv; case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID: llvm_unreachable("long double not supported yet"); return rv; case Type::PointerTyID: return PTOGV(((void*(*)())(intptr_t)FPtr)()); } } assert("Full-featured argument passing not supported yet!"); return GenericValue(); } <commit_msg>Restore sanity to 131601.<commit_after>//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCJIT.h" #include "MCJITMemoryManager.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Target/TargetData.h" using namespace llvm; namespace { static struct RegisterJIT { RegisterJIT() { MCJIT::Register(); } } JITRegistrator; } extern "C" void LLVMLinkInMCJIT() { } ExecutionEngine *MCJIT::createJIT(Module *M, std::string *ErrorStr, JITMemoryManager *JMM, CodeGenOpt::Level OptLevel, bool GVsWithCode, TargetMachine *TM) { // Try to register the program as a source of symbols to resolve against. // // FIXME: Don't do this here. sys::DynamicLibrary::LoadLibraryPermanently(0, NULL); // If the target supports JIT code generation, create the JIT. if (TargetJITInfo *TJ = TM->getJITInfo()) return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM, M), OptLevel, GVsWithCode); if (ErrorStr) *ErrorStr = "target does not support JIT code generation"; return 0; } MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji, RTDyldMemoryManager *MM, CodeGenOpt::Level OptLevel, bool AllocateGVsWithCode) : ExecutionEngine(m), TM(tm), MemMgr(MM), M(m), OS(Buffer), Dyld(MM) { PM.add(new TargetData(*TM->getTargetData())); // Turn the machine code intermediate representation into bytes in memory // that may be executed. if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) { report_fatal_error("Target does not support MC emission!"); } // Initialize passes. // FIXME: When we support multiple modules, we'll want to move the code // gen and finalization out of the constructor here and do it more // on-demand as part of getPointerToFunction(). PM.run(*M); // Flush the output buffer so the SmallVector gets its data. OS.flush(); // Load the object into the dynamic linker. // FIXME: It would be nice to avoid making yet another copy. MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(), Buffer.size())); if (Dyld.loadObject(MB)) report_fatal_error(Dyld.getErrorString()); // Resolve any relocations. Dyld.resolveRelocations(); } MCJIT::~MCJIT() { delete MemMgr; } void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) { report_fatal_error("not yet implemented"); return 0; } void *MCJIT::getPointerToFunction(Function *F) { if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) { bool AbortOnFailure = !F->hasExternalWeakLinkage(); void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure); addGlobalMapping(F, Addr); return Addr; } // FIXME: Should we be using the mangler for this? Probably. StringRef BaseName = F->getName(); Twine Name; if (BaseName[0] == '\1') Name = BaseName.substr(1); else Name = TM->getMCAsmInfo()->getGlobalPrefix() + BaseName; return (void*)Dyld.getSymbolAddress(Name.str()); } void *MCJIT::recompileAndRelinkFunction(Function *F) { report_fatal_error("not yet implemented"); } void MCJIT::freeMachineCodeForFunction(Function *F) { report_fatal_error("not yet implemented"); } GenericValue MCJIT::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert(F && "Function *F was null at entry to run()"); void *FPtr = getPointerToFunction(F); assert(FPtr && "Pointer to fn's code was null after getPointerToFunction"); const FunctionType *FTy = F->getFunctionType(); const Type *RetTy = FTy->getReturnType(); assert((FTy->getNumParams() == ArgValues.size() || (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) && "Wrong number of arguments passed into function!"); assert(FTy->getNumParams() == ArgValues.size() && "This doesn't support passing arguments through varargs (yet)!"); // Handle some common cases first. These cases correspond to common `main' // prototypes. if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) { switch (ArgValues.size()) { case 3: if (FTy->getParamType(0)->isIntegerTy(32) && FTy->getParamType(1)->isPointerTy() && FTy->getParamType(2)->isPointerTy()) { int (*PF)(int, char **, const char **) = (int(*)(int, char **, const char **))(intptr_t)FPtr; // Call the function. GenericValue rv; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), (char **)GVTOP(ArgValues[1]), (const char **)GVTOP(ArgValues[2]))); return rv; } break; case 2: if (FTy->getParamType(0)->isIntegerTy(32) && FTy->getParamType(1)->isPointerTy()) { int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr; // Call the function. GenericValue rv; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), (char **)GVTOP(ArgValues[1]))); return rv; } break; case 1: if (FTy->getNumParams() == 1 && FTy->getParamType(0)->isIntegerTy(32)) { GenericValue rv; int (*PF)(int) = (int(*)(int))(intptr_t)FPtr; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue())); return rv; } break; } } // Handle cases where no arguments are passed first. if (ArgValues.empty()) { GenericValue rv; switch (RetTy->getTypeID()) { default: llvm_unreachable("Unknown return type for function call!"); case Type::IntegerTyID: { unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth(); if (BitWidth == 1) rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)()); else if (BitWidth <= 8) rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)()); else if (BitWidth <= 16) rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)()); else if (BitWidth <= 32) rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)()); else if (BitWidth <= 64) rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)()); else llvm_unreachable("Integer types > 64 bits not supported"); return rv; } case Type::VoidTyID: rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)()); return rv; case Type::FloatTyID: rv.FloatVal = ((float(*)())(intptr_t)FPtr)(); return rv; case Type::DoubleTyID: rv.DoubleVal = ((double(*)())(intptr_t)FPtr)(); return rv; case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID: llvm_unreachable("long double not supported yet"); return rv; case Type::PointerTyID: return PTOGV(((void*(*)())(intptr_t)FPtr)()); } } assert("Full-featured argument passing not supported yet!"); return GenericValue(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015-2016 WinT 3794 <http://wint3794.org> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "LibDS/DriverStation.h" #include "LibDS/Core/ProtocolBase.h" using namespace DS_Core; //============================================================================= // NetConsole warnings/information texts //============================================================================= const QString CHECK_FIREWALL = "<p>" "<font color=#FE755C><b>ERROR:</b></font> " "<font color=#FFFFFF>Cannot connect to robot</font><br/>" "<font color=#20C9FF>The robot is slow to respond. " "Check firewall settings.</font>" "</p>"; const QString PARTIAL_COMM = "<p>" "<font color=#FFF959><b>WARNING:</b></font> " "<font color=#FFFFFF>%1 responds to ping requests, " "but does not respond to DS packets.</font>" "</p>"; const QString INFO_NOTE = "<p>" "<font color=#20C9FF><b>NOTE:</b></font> " "<font color=#FFFFFF>" "The DS may take up to 20 seconds to detect " "your robot, please be patient.</font>" "</p>"; const QString CODE_CRASH = "<p>" "<font color=#FFF959><b>WARNING:</b></font> " "<font color=#FFFFFF>" "The robot code seems to have crashed.</font>" "</p>"; const QString COMM_ESTABLISH = "<p>" "<font color=#59FF59><b>INFO:</b></font> " "<font color=#FFFFFF>" "Robot communications established</font></p>"; //============================================================================= //ProtocolBase:DS_ProtocolBase //============================================================================= ProtocolBase::ProtocolBase() { m_team = 0; m_radioIterator = 0; m_robotIterator = 0; m_sentFMSPackets = 0; m_sentRobotPackets = 0; m_robotAddress = ""; m_alliance = DS::kAllianceRed1; m_controlMode = DS::kControlInvalid; m_communicationStatus = DS::kFailing; m_enabled = false; m_robotCode = false; m_emergencyStop = false; m_radioConnected = false; m_radioPing.setObjectName ("Radio Ping"); m_robotPing.setObjectName ("Robot Ping"); connect (&m_watchdog, &Watchdog::timeout, this, &ProtocolBase::reset); connect (this, &ProtocolBase::packetReceived, &m_watchdog, &Watchdog::restart); connect (&m_robotPing, &QTcpSocket::stateChanged, this, &ProtocolBase::onPingResponse); connect (&m_radioPing, &QTcpSocket::stateChanged, this, &ProtocolBase::onPingResponse); reset(); QTimer::singleShot (500, Qt::CoarseTimer, this, SLOT (showPatienceMsg())); } //============================================================================= //ProtocolBase::team //============================================================================= int ProtocolBase::team() const { return m_team; } //============================================================================= //ProtocolBase::hasCode //============================================================================= bool ProtocolBase::hasCode() const { return m_robotCode; } //============================================================================= //ProtocolBase::sentFMSPackets //============================================================================= int ProtocolBase::sentFmsPackets() const { return m_sentFMSPackets; } //============================================================================= //ProtocolBase::sentRobotPackets //============================================================================= int ProtocolBase::sentRobotPackets() const { return m_sentRobotPackets; } //============================================================================= //ProtocolBase::isEnabled //============================================================================= bool ProtocolBase::isEnabled() const { return m_enabled; } //============================================================================= //ProtocolBase::isConnectedToRobot //============================================================================= bool ProtocolBase::isConnectedToRobot() const { return communicationStatus() == DS::kFull; } //============================================================================= //ProtocolBase::isConnectedToRadio //============================================================================= bool ProtocolBase::isConnectedToRadio() const { return m_radioConnected; } //============================================================================= //ProtocolBase::sendDateTime //============================================================================= bool ProtocolBase::sendDateTime() const { return m_sendDateTime; } //============================================================================= //ProtocolBase::hasVoltageBrownout //============================================================================= bool ProtocolBase::hasVoltageBrownout() const { return m_voltageBrownout; } //============================================================================= //ProtocolBase::isEmergencyStopped //============================================================================= bool ProtocolBase::isEmergencyStopped() const { return m_emergencyStop; } //============================================================================= //ProtocolBase::batteryVoltage //============================================================================= float ProtocolBase::batteryVoltage() const { return m_voltage; } //============================================================================= //ProtocolBase::alliance //============================================================================= DS::Alliance ProtocolBase::alliance() const { return m_alliance; } //============================================================================= //ProtocolBase::controlMode //============================================================================= DS::ControlMode ProtocolBase::controlMode() const { return m_controlMode; } //============================================================================= //ProtocolBase::communicationStatus //============================================================================= DS::DS_CommStatus ProtocolBase::communicationStatus() const { return m_communicationStatus; } //============================================================================= //ProtocolBase::joysticks //============================================================================= QList<DS::Joystick>* ProtocolBase::joysticks() const { return DriverStation::getInstance()->joysticks(); } //============================================================================= //ProtocolBase::radioAddress //============================================================================= QString ProtocolBase::radioAddress() { if (m_radioAddress.isEmpty()) return defaultRadioAddress().at (m_radioIterator); return m_radioAddress; } //============================================================================= //ProtocolBase::robotAddress //============================================================================= QString ProtocolBase::robotAddress() { if (m_robotAddress.isEmpty()) return defaultRobotAddress().at (m_robotIterator); return m_robotAddress; } //============================================================================= //ProtocolBase::createFMSPacket //============================================================================= QByteArray ProtocolBase::createFmsPacket() { m_sentFMSPackets += 1; return _getFmsPacket(); } //============================================================================= //ProtocolBase::createPacket //============================================================================= QByteArray ProtocolBase::createRobotPacket() { m_sentRobotPackets += 1; return _getClientPacket(); } //============================================================================= //ProtocolBase::reset //============================================================================= void ProtocolBase::reset() { /* Try another robot address */ if (m_robotIterator >= defaultRobotAddress().count() - 1) m_robotIterator = 0; else m_robotIterator += 1; /* Try another radio address */ if (m_radioIterator >= defaultRadioAddress().count() - 1) m_radioIterator = 0; else m_radioIterator += 1; /* Custom reset procedures for each protocol */ _resetProtocol(); /* Emit appropiate signals */ updateVoltage (0, 0); updateRobotCode (false); updateRadioStatus (false); updateSendDateTime (false); updateCommStatus (DS::kFailing); /* Figure out the robot address and ping the robot */ QHostInfo::lookupHost (robotAddress(), this, SLOT (lookupFinished (QHostInfo))); /* Ping robot & radio */ pingRadio(); pingRobot(); /* Lower the watchdog tolerance time to try more robot addresses faster */ emit robotAddressChanged (robotAddress()); m_watchdog.setTimeout (125); } //============================================================================= //ProtocolBase::setTeam //============================================================================= void ProtocolBase::setTeam (int team) { if (team != m_team) { m_team = team; emit robotAddressChanged (robotAddress()); DS::log (DS::kLibLevel, "Team number set to: " + QString::number (m_team)); } } //============================================================================= //ProtocolBase::setEnabled //============================================================================= void ProtocolBase::setEnabled (bool enabled) { m_enabled = enabled; emit enabledChanged (isEnabled()); } //============================================================================= //ProtocolBase::setEmergencyStop //============================================================================= void ProtocolBase::setEmergencyStop (bool emergency_stop) { m_emergencyStop = emergency_stop; emit emergencyStoppedChanged (isEmergencyStopped()); /* Stop sending e-stop packets after 1 second */ if (m_emergencyStop) QTimer::singleShot (1000, this, SLOT (disableEmergencyStop())); emit emergencyStopped(); } //============================================================================= //ProtocolBase::setRobotAddress //============================================================================= void ProtocolBase::setRobotAddress (QString address) { m_robotAddress = address; emit robotAddressChanged (robotAddress()); } //============================================================================= //ProtocolBase::setAlliance //============================================================================= void ProtocolBase::setAlliance (DS::Alliance alliance) { m_alliance = alliance; } //============================================================================= //ProtocolBase::setControlMode //============================================================================= void ProtocolBase::setControlMode (DS::ControlMode mode) { if (!isEmergencyStopped()) { m_controlMode = mode; emit controlModeChanged (controlMode()); } } //============================================================================= //ProtocolBase::readFMSPacket //============================================================================= void ProtocolBase::readFmsPacket (QByteArray data) { if (_readFMSPacket (data)) emit fmsChanged (true); } //============================================================================= //ProtocolBase::readRobotPacket //============================================================================= void ProtocolBase::readRobotPacket (QByteArray data) { if (!data.isEmpty()) { /* We just have connected to the robot, update internal values */ if (!isConnectedToRobot()) { _getRobotInformation(); setEnabled (false); updateCommStatus (DS::kFull); setControlMode (DS::kControlTeleoperated); DS::sendMessage (COMM_ESTABLISH); DS::log (DS::kLibLevel, "Robot/DS connection established!"); /* Make the watchdog tolerance higher to avoid temporary resets */ m_watchdog.setTimeout (2000); } /* Let the protocol implementation read the rest of the data */ if (_readRobotPacket (data)) emit packetReceived(); } } //============================================================================= //ProtocolBase::updateRobotCode //============================================================================= void ProtocolBase::updateRobotCode (bool available) { /* Robot code just crashed/failed */ if (m_robotCode && !available) { setEnabled (false); DS::sendMessage (CODE_CRASH); DS::log (DS::kWarnLevel, "It seems that the robot code crashed"); } /* Update DS information */ m_robotCode = available; emit codeChanged (m_robotCode); } //============================================================================= //ProtocolBase::updateSendDateTime //============================================================================= void ProtocolBase::updateSendDateTime (bool sendDT) { m_sendDateTime = sendDT; } //============================================================================= //ProtocolBase::updateRadioStatus //============================================================================= void ProtocolBase::updateRadioStatus (bool connected) { m_radioConnected = connected; emit radioCommChanged (m_radioConnected); } //============================================================================= //ProtocolBase::updateCommStatus //============================================================================= void ProtocolBase::updateCommStatus (DS::DS_CommStatus status) { m_communicationStatus = status; emit communicationsChanged (m_communicationStatus); } //============================================================================= //ProtocolBase::updateVoltageBrownout //============================================================================= void ProtocolBase::updateVoltageBrownout (bool brownout) { m_voltageBrownout = brownout; emit voltageBrownoutChanged (m_voltageBrownout); } //============================================================================= //ProtocolBase::updateVoltage //============================================================================= void ProtocolBase::updateVoltage (QString digit, QString decimal) { /* Voltage is smaller than 10v, add 0 before the digit (e.g. to 09) */ if (digit.length() < 2) digit.prepend ("0"); /* Decimal voltage is less than 0.1v, add 0 to decimal (e.g 0.01) */ if (decimal.length() < 2) decimal.prepend ("0"); /* Decimal is too detailed, obtain only first two digits */ else if (decimal.length() > 2) decimal = QString (decimal.at (0)) + QString (decimal.at (1)); /* Construct voltage string */ QString voltage = QString ("%1.%2").arg (digit, decimal); /* Update values & emit signals */ m_voltage = voltage.toFloat(); emit voltageChanged (voltage); } //============================================================================= //ProtocolBase::pingRobot //============================================================================= void ProtocolBase::pingRobot() { m_robotPing.abort(); m_robotPing.connectToHost (robotAddress(), tcpProbesPort(), QTcpSocket::ReadOnly); } //============================================================================= //ProtocolBase::pingRadio //============================================================================= void ProtocolBase::pingRadio() { m_radioPing.abort(); m_radioPing.connectToHost (radioAddress(), 80, QTcpSocket::ReadOnly); } //============================================================================= //ProtocolBase::showPatienceMsg //============================================================================= void ProtocolBase::showPatienceMsg() { DS::sendMessage (INFO_NOTE); } //============================================================================= //ProtocolBase::disableEmergencyStop //============================================================================= void ProtocolBase::disableEmergencyStop() { setEmergencyStop (false); } //============================================================================= //ProtocolBase::updateRobotIP //============================================================================= void ProtocolBase::lookupFinished (QHostInfo info) { if (!info.addresses().isEmpty()) emit robotAddressChanged (info.addresses().first().toString()); pingRobot(); } //============================================================================= //ProtocolBase::onPingResponse //============================================================================= void ProtocolBase::onPingResponse (QAbstractSocket::SocketState state) { bool isAlive = (state == QAbstractSocket::ConnectedState); /* Emitter is robot socket */ if (sender()->objectName() == m_robotPing.objectName()) { if (communicationStatus() == DS::kFailing && isAlive) updateCommStatus (DS::kPartial); } /* Emitter is radio socket */ else if (sender()->objectName() == m_radioPing.objectName()) updateRadioStatus (isAlive); } <commit_msg>Update ProtocolBase.cpp<commit_after>/* * Copyright (c) 2015-2016 WinT 3794 <http://wint3794.org> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "LibDS/DriverStation.h" #include "LibDS/Core/ProtocolBase.h" using namespace DS_Core; //============================================================================= // NetConsole warnings/information texts //============================================================================= const QString CHECK_FIREWALL = "<p>" "<font color=#FE755C><b>ERROR:</b></font> " "<font color=#FFFFFF>Cannot connect to robot</font><br/>" "<font color=#20C9FF>The robot is slow to respond. " "Check firewall settings.</font>" "</p>"; const QString PARTIAL_COMM = "<p>" "<font color=#FFF959><b>WARNING:</b></font> " "<font color=#FFFFFF>%1 responds to ping requests, " "but does not respond to DS packets.</font>" "</p>"; const QString INFO_NOTE = "<p>" "<font color=#20C9FF><b>NOTE:</b></font> " "<font color=#FFFFFF>" "The DS may take up to 20 seconds to detect " "your robot, please be patient.</font>" "</p>"; const QString COMM_ESTABLISH = "<p>" "<font color=#59FF59><b>INFO:</b></font> " "<font color=#FFFFFF>" "Robot communications established</font></p>"; //============================================================================= //ProtocolBase:DS_ProtocolBase //============================================================================= ProtocolBase::ProtocolBase() { m_team = 0; m_radioIterator = 0; m_robotIterator = 0; m_sentFMSPackets = 0; m_sentRobotPackets = 0; m_robotAddress = ""; m_alliance = DS::kAllianceRed1; m_controlMode = DS::kControlInvalid; m_communicationStatus = DS::kFailing; m_enabled = false; m_robotCode = false; m_emergencyStop = false; m_radioConnected = false; m_radioPing.setObjectName ("Radio Ping"); m_robotPing.setObjectName ("Robot Ping"); connect (&m_watchdog, &Watchdog::timeout, this, &ProtocolBase::reset); connect (this, &ProtocolBase::packetReceived, &m_watchdog, &Watchdog::restart); connect (&m_robotPing, &QTcpSocket::stateChanged, this, &ProtocolBase::onPingResponse); connect (&m_radioPing, &QTcpSocket::stateChanged, this, &ProtocolBase::onPingResponse); reset(); QTimer::singleShot (500, Qt::CoarseTimer, this, SLOT (showPatienceMsg())); } //============================================================================= //ProtocolBase::team //============================================================================= int ProtocolBase::team() const { return m_team; } //============================================================================= //ProtocolBase::hasCode //============================================================================= bool ProtocolBase::hasCode() const { return m_robotCode; } //============================================================================= //ProtocolBase::sentFMSPackets //============================================================================= int ProtocolBase::sentFmsPackets() const { return m_sentFMSPackets; } //============================================================================= //ProtocolBase::sentRobotPackets //============================================================================= int ProtocolBase::sentRobotPackets() const { return m_sentRobotPackets; } //============================================================================= //ProtocolBase::isEnabled //============================================================================= bool ProtocolBase::isEnabled() const { return m_enabled; } //============================================================================= //ProtocolBase::isConnectedToRobot //============================================================================= bool ProtocolBase::isConnectedToRobot() const { return communicationStatus() == DS::kFull; } //============================================================================= //ProtocolBase::isConnectedToRadio //============================================================================= bool ProtocolBase::isConnectedToRadio() const { return m_radioConnected; } //============================================================================= //ProtocolBase::sendDateTime //============================================================================= bool ProtocolBase::sendDateTime() const { return m_sendDateTime; } //============================================================================= //ProtocolBase::hasVoltageBrownout //============================================================================= bool ProtocolBase::hasVoltageBrownout() const { return m_voltageBrownout; } //============================================================================= //ProtocolBase::isEmergencyStopped //============================================================================= bool ProtocolBase::isEmergencyStopped() const { return m_emergencyStop; } //============================================================================= //ProtocolBase::batteryVoltage //============================================================================= float ProtocolBase::batteryVoltage() const { return m_voltage; } //============================================================================= //ProtocolBase::alliance //============================================================================= DS::Alliance ProtocolBase::alliance() const { return m_alliance; } //============================================================================= //ProtocolBase::controlMode //============================================================================= DS::ControlMode ProtocolBase::controlMode() const { return m_controlMode; } //============================================================================= //ProtocolBase::communicationStatus //============================================================================= DS::DS_CommStatus ProtocolBase::communicationStatus() const { return m_communicationStatus; } //============================================================================= //ProtocolBase::joysticks //============================================================================= QList<DS::Joystick>* ProtocolBase::joysticks() const { return DriverStation::getInstance()->joysticks(); } //============================================================================= //ProtocolBase::radioAddress //============================================================================= QString ProtocolBase::radioAddress() { if (m_radioAddress.isEmpty()) return defaultRadioAddress().at (m_radioIterator); return m_radioAddress; } //============================================================================= //ProtocolBase::robotAddress //============================================================================= QString ProtocolBase::robotAddress() { if (m_robotAddress.isEmpty()) return defaultRobotAddress().at (m_robotIterator); return m_robotAddress; } //============================================================================= //ProtocolBase::createFMSPacket //============================================================================= QByteArray ProtocolBase::createFmsPacket() { m_sentFMSPackets += 1; return _getFmsPacket(); } //============================================================================= //ProtocolBase::createPacket //============================================================================= QByteArray ProtocolBase::createRobotPacket() { m_sentRobotPackets += 1; return _getClientPacket(); } //============================================================================= //ProtocolBase::reset //============================================================================= void ProtocolBase::reset() { /* Try another robot address */ if (m_robotIterator >= defaultRobotAddress().count() - 1) m_robotIterator = 0; else m_robotIterator += 1; /* Try another radio address */ if (m_radioIterator >= defaultRadioAddress().count() - 1) m_radioIterator = 0; else m_radioIterator += 1; /* Custom reset procedures for each protocol */ _resetProtocol(); /* Emit appropiate signals */ updateVoltage (0, 0); updateRobotCode (false); updateRadioStatus (false); updateSendDateTime (false); updateCommStatus (DS::kFailing); /* Figure out the robot address and ping the robot */ QHostInfo::lookupHost (robotAddress(), this, SLOT (lookupFinished (QHostInfo))); /* Ping robot & radio */ pingRadio(); pingRobot(); /* Lower the watchdog tolerance time to try more robot addresses faster */ emit robotAddressChanged (robotAddress()); m_watchdog.setTimeout (125); } //============================================================================= //ProtocolBase::setTeam //============================================================================= void ProtocolBase::setTeam (int team) { if (team != m_team) { m_team = team; emit robotAddressChanged (robotAddress()); DS::log (DS::kLibLevel, "Team number set to: " + QString::number (m_team)); } } //============================================================================= //ProtocolBase::setEnabled //============================================================================= void ProtocolBase::setEnabled (bool enabled) { m_enabled = enabled; emit enabledChanged (isEnabled()); } //============================================================================= //ProtocolBase::setEmergencyStop //============================================================================= void ProtocolBase::setEmergencyStop (bool emergency_stop) { m_emergencyStop = emergency_stop; emit emergencyStoppedChanged (isEmergencyStopped()); /* Stop sending e-stop packets after 1 second */ if (m_emergencyStop) QTimer::singleShot (1000, this, SLOT (disableEmergencyStop())); emit emergencyStopped(); } //============================================================================= //ProtocolBase::setRobotAddress //============================================================================= void ProtocolBase::setRobotAddress (QString address) { m_robotAddress = address; emit robotAddressChanged (robotAddress()); } //============================================================================= //ProtocolBase::setAlliance //============================================================================= void ProtocolBase::setAlliance (DS::Alliance alliance) { m_alliance = alliance; } //============================================================================= //ProtocolBase::setControlMode //============================================================================= void ProtocolBase::setControlMode (DS::ControlMode mode) { if (!isEmergencyStopped()) { m_controlMode = mode; emit controlModeChanged (controlMode()); } } //============================================================================= //ProtocolBase::readFMSPacket //============================================================================= void ProtocolBase::readFmsPacket (QByteArray data) { if (_readFMSPacket (data)) emit fmsChanged (true); } //============================================================================= //ProtocolBase::readRobotPacket //============================================================================= void ProtocolBase::readRobotPacket (QByteArray data) { if (!data.isEmpty()) { /* We just have connected to the robot, update internal values */ if (!isConnectedToRobot()) { _getRobotInformation(); setEnabled (false); updateCommStatus (DS::kFull); setControlMode (DS::kControlTeleoperated); DS::sendMessage (COMM_ESTABLISH); DS::log (DS::kLibLevel, "Robot/DS connection established!"); /* Make the watchdog tolerance higher to avoid temporary resets */ m_watchdog.setTimeout (2000); } /* Let the protocol implementation read the rest of the data */ if (_readRobotPacket (data)) emit packetReceived(); } } //============================================================================= //ProtocolBase::updateRobotCode //============================================================================= void ProtocolBase::updateRobotCode (bool available) { /* Robot code just crashed/failed */ if (m_robotCode && !available) setEnabled (false); /* Update DS information */ m_robotCode = available; emit codeChanged (m_robotCode); } //============================================================================= //ProtocolBase::updateSendDateTime //============================================================================= void ProtocolBase::updateSendDateTime (bool sendDT) { m_sendDateTime = sendDT; } //============================================================================= //ProtocolBase::updateRadioStatus //============================================================================= void ProtocolBase::updateRadioStatus (bool connected) { m_radioConnected = connected; emit radioCommChanged (m_radioConnected); } //============================================================================= //ProtocolBase::updateCommStatus //============================================================================= void ProtocolBase::updateCommStatus (DS::DS_CommStatus status) { m_communicationStatus = status; emit communicationsChanged (m_communicationStatus); } //============================================================================= //ProtocolBase::updateVoltageBrownout //============================================================================= void ProtocolBase::updateVoltageBrownout (bool brownout) { m_voltageBrownout = brownout; emit voltageBrownoutChanged (m_voltageBrownout); } //============================================================================= //ProtocolBase::updateVoltage //============================================================================= void ProtocolBase::updateVoltage (QString digit, QString decimal) { /* Voltage is smaller than 10v, add 0 before the digit (e.g. to 09) */ if (digit.length() < 2) digit.prepend ("0"); /* Decimal voltage is less than 0.1v, add 0 to decimal (e.g 0.01) */ if (decimal.length() < 2) decimal.prepend ("0"); /* Decimal is too detailed, obtain only first two digits */ else if (decimal.length() > 2) decimal = QString (decimal.at (0)) + QString (decimal.at (1)); /* Construct voltage string */ QString voltage = QString ("%1.%2").arg (digit, decimal); /* Update values & emit signals */ m_voltage = voltage.toFloat(); emit voltageChanged (voltage); } //============================================================================= //ProtocolBase::pingRobot //============================================================================= void ProtocolBase::pingRobot() { m_robotPing.abort(); m_robotPing.connectToHost (robotAddress(), tcpProbesPort(), QTcpSocket::ReadOnly); } //============================================================================= //ProtocolBase::pingRadio //============================================================================= void ProtocolBase::pingRadio() { m_radioPing.abort(); m_radioPing.connectToHost (radioAddress(), 80, QTcpSocket::ReadOnly); } //============================================================================= //ProtocolBase::showPatienceMsg //============================================================================= void ProtocolBase::showPatienceMsg() { DS::sendMessage (INFO_NOTE); } //============================================================================= //ProtocolBase::disableEmergencyStop //============================================================================= void ProtocolBase::disableEmergencyStop() { setEmergencyStop (false); } //============================================================================= //ProtocolBase::updateRobotIP //============================================================================= void ProtocolBase::lookupFinished (QHostInfo info) { if (!info.addresses().isEmpty()) emit robotAddressChanged (info.addresses().first().toString()); pingRobot(); } //============================================================================= //ProtocolBase::onPingResponse //============================================================================= void ProtocolBase::onPingResponse (QAbstractSocket::SocketState state) { bool isAlive = (state == QAbstractSocket::ConnectedState); /* Emitter is robot socket */ if (sender()->objectName() == m_robotPing.objectName()) { if (communicationStatus() == DS::kFailing && isAlive) updateCommStatus (DS::kPartial); } /* Emitter is radio socket */ else if (sender()->objectName() == m_radioPing.objectName()) updateRadioStatus (isAlive); } <|endoftext|>
<commit_before>/* Adam Austin 4/22/2016 TA: Quesada */ #include "Person.h" #include "FamilyTree.h" #include <iostream> #include <string> using namespace std; int main() { FamilyTree *myFamilyTree = new FamilyTree(); // Create an instance of familyTree Person *unknownPerson = new Person("Unknown"); unknownPerson -> setVisited(true); myFamilyTree -> setUnknownPerson(unknownPerson); bool done = false; while (!done) //write menu { cout << "======Main Menu======" << endl; cout << "1. Add a Person" << endl; cout << "2. Print Persons Information" << endl; cout << "3. Print Persons Family" << endl; cout << "4. Print All Familys" << endl; cout << "5. Print all Roots" << endl; cout << "6. Quit" << endl; string userChoiceString; cin >> userChoiceString; // Check user input if (userChoiceString == "1") { cout << "What is the persons full name(\"First Last)\"?:" << endl; cin.ignore(); string name; getline(cin, name); cout << "What is " << name << "'s biological mothers full name, \"First Last\"? If you do not know put \"Unknown\"." << endl; string mothersName; getline(cin, mothersName); cout << "What is " << name << "'s biological fathers full name, \"First Last\"? If you do not know put \"Unknown\"." << endl; string fathersName; getline(cin, fathersName); cout << "Does " << name << " have a spouse? If so, enter their full name, \"First Last\", if not enter \"None\", and if you do not know, enter \"Unknown\"." << endl; string spouse; getline(cin, spouse); cout << "Is " << name << " a male or female? For male enter \"m\" and for female enter \"f\"." << endl; string gender = ""; bool doneWithGender = false; while (!doneWithGender) { getline(cin, gender); if (gender == "m" || gender == "f") { //cout << endl; doneWithGender = true; } else cout << "This is not a recognized input, please try again:"; } Person *newPerson = new Person(name, mothersName, fathersName, spouse, gender); cout << "Does " << newPerson -> getFullName() << " have any siblings? "; bool doneWithSiblings = false; while (!doneWithSiblings) { cout << "If not enter \"No\", otherwise enter their full name, \"First Last\": "; //cin.ignore(); string userInput; getline(cin, userInput); //cout << "answer was " << userInput << endl; if (userInput == "No") { doneWithSiblings = true; //cout << "SAID NO" << endl; } else { cout << userInput << " is a sibling? Enter \"Yes \" or \"No\": "; string confirm; getline(cin, confirm); if (confirm == "Yes") { cout << userInput << " has been added! " << endl; Person *newSib = new Person(userInput, myFamilyTree); newSib -> addSibling(newPerson); newPerson -> addSibling(newSib); } else cout << userInput << " has not been added as a sibling." << endl; cout << "Does " << newPerson -> getFullName() << " have any more siblings? "; } } cout << "Does " << newPerson -> getFullName() << " have any children?"; bool doneWithChildren = false; while (!doneWithChildren) { cout << "If not enter \"No\", otherwise enter their full name, \"First Last\": "; //cin.ignore(); string userInput; getline(cin, userInput); //cout << "answer was " << userInput << endl; if (userInput == "No") { doneWithChildren = true; //cout << "SAID NO" << endl; } else { cout << userInput << " is a child? Enter \"Yes \" or \"No\": "; string confirm; getline(cin, confirm); if (confirm == "Yes") { cout << userInput << " has been added!" << endl; Person *newChild = new Person(userInput, myFamilyTree); //newChild -> setBi(newPerson); newPerson -> addChild(newChild); } else cout << userInput << " has not been added as a child" << endl; cout << "Does " << newPerson -> getFullName() << " have any more children?"; } } myFamilyTree -> addToTree(newPerson); } else if (userChoiceString == "2") { cout << "What is the persons full name(\"First Last)\"?:" << endl; cin.ignore(); string name; getline(cin, name); //myFamilyTree -> resetVisited(); Person *person = myFamilyTree -> findPerson(name); if (person != NULL) { person -> printInformation(); } } else if (userChoiceString == "3") { cout << "What is the persons full name(\"First Last)\"?:" << endl; cin.ignore(); string name; getline(cin, name); //myFamilyTree -> resetVisited(); Person *person = myFamilyTree -> findPerson(name); if (person != NULL) { myFamilyTree -> printPersonsFamily(person); } } else if (userChoiceString == "5") { myFamilyTree -> printAllFamilies(); } else if (userChoiceString == "4") { myFamilyTree -> printAllRoots(); } else if (userChoiceString == "5") { cout << "Goodbye!" << endl; done = true; } } return 0; } <commit_msg>added comments to driver<commit_after>/* Adam Austin 4/22/2016 TA: Quesada */ #include "Person.h" #include "FamilyTree.h" #include <iostream> #include <string> using namespace std; int main() { FamilyTree *myFamilyTree = new FamilyTree(); // Create an instance of familyTree Person *unknownPerson = new Person("Unknown"); // Make an unknown node for the tree whose visited will always be true. This will help with people with unknown relatives unknownPerson -> setVisited(true); myFamilyTree -> setUnknownPerson(unknownPerson); // Set the unknown person to myFamilyTree bool done = false; while (!done) //write menu { cout << "======Main Menu======" << endl; cout << "1. Add a Person" << endl; cout << "2. Print Persons Information" << endl; cout << "3. Print Persons Family" << endl; cout << "4. Print All Familys" << endl; cout << "5. Print all Roots" << endl; cout << "6. Quit" << endl; string userChoiceString; cin >> userChoiceString; // Check user input if (userChoiceString == "1") // Add person { // Get all of the user input to make a new person cout << "What is the persons full name(\"First Last)\"?:" << endl; cin.ignore(); string name; getline(cin, name); cout << "What is " << name << "'s biological mothers full name, \"First Last\"? If you do not know put \"Unknown\"." << endl; string mothersName; getline(cin, mothersName); cout << "What is " << name << "'s biological fathers full name, \"First Last\"? If you do not know put \"Unknown\"." << endl; string fathersName; getline(cin, fathersName); cout << "Does " << name << " have a spouse? If so, enter their full name, \"First Last\", if not enter \"None\", and if you do not know, enter \"Unknown\"." << endl; string spouse; getline(cin, spouse); cout << "Is " << name << " a male or female? For male enter \"m\" and for female enter \"f\"." << endl; string gender = ""; bool doneWithGender = false; while (!doneWithGender) { getline(cin, gender); if (gender == "m" || gender == "f") { //cout << endl; doneWithGender = true; } else cout << "This is not a recognized input, please try again:"; } Person *newPerson = new Person(name, mothersName, fathersName, spouse, gender); // Make a new instance of person with the user input cout << "Does " << newPerson -> getFullName() << " have any siblings? "; bool doneWithSiblings = false; while (!doneWithSiblings) // Get user input for all siblings { cout << "If not enter \"No\", otherwise enter their full name, \"First Last\": "; string userInput; getline(cin, userInput); if (userInput == "No" || userInput == "no") // Check if the person is done with siblings yet { doneWithSiblings = true; } else { cout << userInput << " is a sibling? Enter \"Yes \" or \"No\": "; string confirm; getline(cin, confirm); if (confirm == "Yes" || userInput == "yes") // If the current input is a sibling { cout << userInput << " has been added! " << endl; // Add that sibling to the new persons sibList Person *newSib = new Person(userInput, myFamilyTree); newSib -> addSibling(newPerson); newPerson -> addSibling(newSib); } else cout << userInput << " has not been added as a sibling." << endl; cout << "Does " << newPerson -> getFullName() << " have any more siblings? "; } } cout << "Does " << newPerson -> getFullName() << " have any children?"; bool doneWithChildren = false; while (!doneWithChildren) { cout << "If not enter \"No\", otherwise enter their full name, \"First Last\": "; string userInput; getline(cin, userInput); if (userInput == "No" || userInput == "no") // Check if the person is done with children yet { doneWithChildren = true; } else { cout << userInput << " is a child? Enter \"Yes \" or \"No\": "; string confirm; getline(cin, confirm); if (confirm == "Yes" || userInput == "yes") // If the current input is a child { cout << userInput << " has been added!" << endl; // Add the child to the new persons childList Person *newChild = new Person(userInput, myFamilyTree); newPerson -> addChild(newChild); } else cout << userInput << " has not been added as a child" << endl; cout << "Does " << newPerson -> getFullName() << " have any more children?"; } } myFamilyTree -> addToTree(newPerson); // Add the new person to the tree } else if (userChoiceString == "2") // Print Person information { cout << "What is the persons full name(\"First Last)\"?:" << endl; cin.ignore(); string name; // Get user input getline(cin, name); Person *person = myFamilyTree -> findPerson(name); if (person != NULL) { person -> printInformation(); // Print persons information } } else if (userChoiceString == "3") // Print persons family { cout << "What is the persons full name(\"First Last)\"?:" << endl; cin.ignore(); string name; // Get user input getline(cin, name); Person *person = myFamilyTree -> findPerson(name); if (person != NULL) { myFamilyTree -> printPersonsFamily(person); // Print persons family } } else if (userChoiceString == "4") // Print all families { myFamilyTree -> printAllFamilies(); } else if (userChoiceString == "5") // Print all family roots { myFamilyTree -> printAllRoots(); } else if (userChoiceString == "6") // Quit { cout << "Goodbye!" << endl; done = true; } } return 0; } <|endoftext|>
<commit_before>#pragma once #include <cmath> template <typename Type> class Flock { public: Flock(); Type num1; Type num2; Type num3; Flock(Type a, Type b, Type c) { this->num1 = a; this->num2 = b; this->num3 = c; } bool checkFlock() { // ab + c^a = (a + b - c) + ac^2 * b bool condition = this->num1 * this->num2 + std::pow(this->num3, this->num1) == (this->num1 + this->num2 - this->num3) + this->num1 * std::pow(this->num3, 2) * this->num2; return condition; } Type expand() { Type expandedForm = this->num1 * this->num2 * std::pow(this->num3, 2); return expandedForm; } Type add(Flock a, Flock b) { Type sum = (a.num1 + b.num1) + (a.num2 + b.num2) + (a.num3 + b.num3); return sum; } Type multiply(Flock a, Flock b) { Type product = (a.num1 * b.num1) * (a.num2 * b.num2) * (a.num3 * b.num3); return product; } Type subtract(Flock a, Flock b) { Type diff = (a.num1 - b.num1) - (a.num2 - b.num2) - (a.num3 - b.num3); return diff; } };<commit_msg>Clean up some code<commit_after>#pragma once #include <cmath> template <typename Type> class Flock { public: Flock(); Type num1; Type num2; Type num3; Flock(Type a, Type b, Type c) { this->num1 = a; this->num2 = b; this->num3 = c; } bool checkFlock() { // ab + c^a = (a + b - c) + ac^2 * b bool condition = num1 * num2 + std::pow(num3, num1) == (num1 + num2 - num3) + num1 * std::pow(num3, 2) * num2; return condition; } Type expand() { Type expandedForm = num1 * num2 * std::pow(num3, 2); return expandedForm; } Type add(Flock a, Flock b) { Type sum = (a.num1 + b.num1) + (a.num2 + b.num2) + (a.num3 + b.num3); return sum; } Type multiply(Flock a, Flock b) { Type product = (a.num1 * b.num1) * (a.num2 * b.num2) * (a.num3 * b.num3); return product; } Type subtract(Flock a, Flock b) { Type diff = (a.num1 - b.num1) - (a.num2 - b.num2) - (a.num3 - b.num3); return diff; } }; <|endoftext|>
<commit_before>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the "Instituto Nokia de Tecnologia" and // is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "ARMTargetMachine.h" #include "ARMTargetAsmInfo.h" #include "ARMFrameInfo.h" #include "ARM.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl::opt<bool> DisableLdStOpti("disable-arm-loadstore-opti", cl::Hidden, cl::desc("Disable load store optimization pass")); namespace { // Register the target. RegisterTarget<ARMTargetMachine> X("arm", " ARM"); } /// TargetMachine ctor - Create an ILP32 architecture model /// ARMTargetMachine::ARMTargetMachine(const Module &M, const std::string &FS) : Subtarget(M, FS), DataLayout(Subtarget.isTargetDarwin() ? std::string("e-p:32:32-d:32:32-l:32:32") : std::string("e-p:32:32-d:32:64-l:32:64")), InstrInfo(Subtarget), FrameInfo(Subtarget) {} unsigned ARMTargetMachine::getModuleMatchQuality(const Module &M) { std::string TT = M.getTargetTriple(); if (TT.size() >= 4 && std::string(TT.begin(), TT.begin()+4) == "arm-") return 20; if (M.getPointerSize() == Module::Pointer32) return 1; else return 0; } const TargetAsmInfo *ARMTargetMachine::createTargetAsmInfo() const { return new ARMTargetAsmInfo(*this); } // Pass Pipeline Configuration bool ARMTargetMachine::addInstSelector(FunctionPassManager &PM, bool Fast) { PM.add(createARMISelDag(*this)); return false; } bool ARMTargetMachine::addPreEmitPass(FunctionPassManager &PM, bool Fast) { // FIXME: temporarily disabling load / store optimization pass for Thumb mode. if (!Fast && !DisableLdStOpti && !Subtarget.isThumb()) PM.add(createARMLoadStoreOptimizationPass()); PM.add(createARMConstantIslandPass()); return true; } bool ARMTargetMachine::addAssemblyEmitter(FunctionPassManager &PM, bool Fast, std::ostream &Out) { // Output assembly language. PM.add(createARMCodePrinterPass(Out, *this)); return false; } <commit_msg>Thumb add sp, #imm requires the immediate value be multiple of 4. For now, change preferred alignment of short, byte, bool to 4.<commit_after>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the "Instituto Nokia de Tecnologia" and // is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "ARMTargetMachine.h" #include "ARMTargetAsmInfo.h" #include "ARMFrameInfo.h" #include "ARM.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl::opt<bool> DisableLdStOpti("disable-arm-loadstore-opti", cl::Hidden, cl::desc("Disable load store optimization pass")); namespace { // Register the target. RegisterTarget<ARMTargetMachine> X("arm", " ARM"); } /// TargetMachine ctor - Create an ILP32 architecture model /// ARMTargetMachine::ARMTargetMachine(const Module &M, const std::string &FS) : Subtarget(M, FS), DataLayout(Subtarget.isTargetDarwin() ? (Subtarget.isThumb() ? std::string("e-p:32:32-d:32:32-l:32:32-s:16:32-b:8:32-B:8:32") : std::string("e-p:32:32-d:32:32-l:32:32")) : (Subtarget.isThumb() ? std::string("e-p:32:32-d:32:64-l:32:64-s:16:32-b:8:32-B:8:32") : std::string("e-p:32:32-d:32:64-l:32:64"))), InstrInfo(Subtarget), FrameInfo(Subtarget) {} unsigned ARMTargetMachine::getModuleMatchQuality(const Module &M) { std::string TT = M.getTargetTriple(); if (TT.size() >= 4 && std::string(TT.begin(), TT.begin()+4) == "arm-") return 20; if (M.getPointerSize() == Module::Pointer32) return 1; else return 0; } const TargetAsmInfo *ARMTargetMachine::createTargetAsmInfo() const { return new ARMTargetAsmInfo(*this); } // Pass Pipeline Configuration bool ARMTargetMachine::addInstSelector(FunctionPassManager &PM, bool Fast) { PM.add(createARMISelDag(*this)); return false; } bool ARMTargetMachine::addPreEmitPass(FunctionPassManager &PM, bool Fast) { // FIXME: temporarily disabling load / store optimization pass for Thumb mode. if (!Fast && !DisableLdStOpti && !Subtarget.isThumb()) PM.add(createARMLoadStoreOptimizationPass()); PM.add(createARMConstantIslandPass()); return true; } bool ARMTargetMachine::addAssemblyEmitter(FunctionPassManager &PM, bool Fast, std::ostream &Out) { // Output assembly language. PM.add(createARMCodePrinterPass(Out, *this)); return false; } <|endoftext|>
<commit_before>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the X86 specific subclass of TargetMachine. // //===----------------------------------------------------------------------===// #include "X86TargetMachine.h" #include "X86.h" #include "X86TargetObjectFile.h" #include "X86TargetTransformInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/IR/Function.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner", cl::desc("Enable the machine combiner pass"), cl::init(true), cl::Hidden); namespace llvm { void initializeWinEHStatePassPass(PassRegistry &); } extern "C" void LLVMInitializeX86Target() { // Register the target. RegisterTargetMachine<X86TargetMachine> X(TheX86_32Target); RegisterTargetMachine<X86TargetMachine> Y(TheX86_64Target); PassRegistry &PR = *PassRegistry::getPassRegistry(); initializeWinEHStatePassPass(PR); initializeFixupBWInstPassPass(PR); } static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { if (TT.isOSBinFormatMachO()) { if (TT.getArch() == Triple::x86_64) return make_unique<X86_64MachoTargetObjectFile>(); return make_unique<TargetLoweringObjectFileMachO>(); } if (TT.isOSLinux() || TT.isOSNaCl()) return make_unique<X86LinuxNaClTargetObjectFile>(); if (TT.isOSBinFormatELF()) return make_unique<X86ELFTargetObjectFile>(); if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment()) return make_unique<X86WindowsTargetObjectFile>(); if (TT.isOSBinFormatCOFF()) return make_unique<TargetLoweringObjectFileCOFF>(); llvm_unreachable("unknown subtarget type"); } static std::string computeDataLayout(const Triple &TT) { // X86 is little endian std::string Ret = "e"; Ret += DataLayout::getManglingComponent(TT); // X86 and x32 have 32 bit pointers. if ((TT.isArch64Bit() && (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) || !TT.isArch64Bit()) Ret += "-p:32:32"; // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32. if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl()) Ret += "-i64:64"; else if (TT.isOSIAMCU()) Ret += "-i64:32-f64:32"; else Ret += "-f64:32:64"; // Some ABIs align long double to 128 bits, others to 32. if (TT.isOSNaCl() || TT.isOSIAMCU()) ; // No f80 else if (TT.isArch64Bit() || TT.isOSDarwin()) Ret += "-f80:128"; else Ret += "-f80:32"; if (TT.isOSIAMCU()) Ret += "-f128:32"; // The registers can hold 8, 16, 32 or, in x86-64, 64 bits. if (TT.isArch64Bit()) Ret += "-n8:16:32:64"; else Ret += "-n8:16:32"; // The stack is aligned to 32 bits on some ABIs and 128 bits on others. if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU()) Ret += "-a:0:32-S32"; else Ret += "-S128"; return Ret; } static Reloc::Model getEffectiveRelocModel(const Triple &TT, Optional<Reloc::Model> RM) { bool is64Bit = TT.getArch() == Triple::x86_64; if (!RM.hasValue()) { // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode. // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we // use static relocation model by default. if (TT.isOSDarwin()) { if (is64Bit) return Reloc::PIC_; return Reloc::DynamicNoPIC; } if (TT.isOSWindows() && is64Bit) return Reloc::PIC_; return Reloc::Static; } // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC // is defined as a model for code which may be used in static or dynamic // executables but not necessarily a shared library. On X86-32 we just // compile in -static mode, in x86-64 we use PIC. if (*RM == Reloc::DynamicNoPIC) { if (is64Bit) return Reloc::PIC_; if (!TT.isOSDarwin()) return Reloc::Static; } // If we are on Darwin, disallow static relocation model in X86-64 mode, since // the Mach-O file format doesn't support it. if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit) return Reloc::PIC_; return *RM; } /// Create an X86 target. /// X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional<Reloc::Model> RM, CodeModel::Model CM, CodeGenOpt::Level OL) : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM, OL), TLOF(createTLOF(getTargetTriple())), Subtarget(TT, CPU, FS, *this, Options.StackAlignmentOverride) { // Windows stack unwinder gets confused when execution flow "falls through" // after a call to 'noreturn' function. // To prevent that, we emit a trap for 'unreachable' IR instructions. // (which on X86, happens to be the 'ud2' instruction) // On PS4, the "return address" of a 'noreturn' call must still be within // the calling function, and TrapUnreachable is an easy way to get that. if (Subtarget.isTargetWin64() || Subtarget.isTargetPS4()) this->Options.TrapUnreachable = true; // By default (and when -ffast-math is on), enable estimate codegen for // everything except scalar division. By default, use 1 refinement step for // all operations. Defaults may be overridden by using command-line options. // Scalar division estimates are disabled because they break too much // real-world code. These defaults match GCC behavior. this->Options.Reciprocals.setDefaults("sqrtf", true, 1); this->Options.Reciprocals.setDefaults("divf", false, 1); this->Options.Reciprocals.setDefaults("vec-sqrtf", true, 1); this->Options.Reciprocals.setDefaults("vec-divf", true, 1); initAsmInfo(); } X86TargetMachine::~X86TargetMachine() {} const X86Subtarget * X86TargetMachine::getSubtargetImpl(const Function &F) const { Attribute CPUAttr = F.getFnAttribute("target-cpu"); Attribute FSAttr = F.getFnAttribute("target-features"); StringRef CPU = !CPUAttr.hasAttribute(Attribute::None) ? CPUAttr.getValueAsString() : (StringRef)TargetCPU; StringRef FS = !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString() : (StringRef)TargetFS; SmallString<512> Key; Key.reserve(CPU.size() + FS.size()); Key += CPU; Key += FS; // FIXME: This is related to the code below to reset the target options, // we need to know whether or not the soft float flag is set on the // function before we can generate a subtarget. We also need to use // it as a key for the subtarget since that can be the only difference // between two functions. bool SoftFloat = F.getFnAttribute("use-soft-float").getValueAsString() == "true"; // If the soft float attribute is set on the function turn on the soft float // subtarget feature. if (SoftFloat) Key += FS.empty() ? "+soft-float" : ",+soft-float"; FS = Key.substr(CPU.size()); auto &I = SubtargetMap[Key]; if (!I) { // This needs to be done before we create a new subtarget since any // creation will depend on the TM and the code generation flags on the // function that reside in TargetOptions. resetTargetOptions(F); I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this, Options.StackAlignmentOverride); } return I.get(); } //===----------------------------------------------------------------------===// // Command line options for x86 //===----------------------------------------------------------------------===// static cl::opt<bool> UseVZeroUpper("x86-use-vzeroupper", cl::Hidden, cl::desc("Minimize AVX to SSE transition penalty"), cl::init(true)); //===----------------------------------------------------------------------===// // X86 TTI query. //===----------------------------------------------------------------------===// TargetIRAnalysis X86TargetMachine::getTargetIRAnalysis() { return TargetIRAnalysis([this](const Function &F) { return TargetTransformInfo(X86TTIImpl(this, F)); }); } //===----------------------------------------------------------------------===// // Pass Pipeline Configuration //===----------------------------------------------------------------------===// namespace { /// X86 Code Generator Pass Configuration Options. class X86PassConfig : public TargetPassConfig { public: X86PassConfig(X86TargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} X86TargetMachine &getX86TargetMachine() const { return getTM<X86TargetMachine>(); } void addIRPasses() override; bool addInstSelector() override; bool addILPOpts() override; bool addPreISel() override; void addPreRegAlloc() override; void addPostRegAlloc() override; void addPreEmitPass() override; void addPreSched2() override; }; } // namespace TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) { return new X86PassConfig(this, PM); } void X86PassConfig::addIRPasses() { addPass(createAtomicExpandPass(&getX86TargetMachine())); TargetPassConfig::addIRPasses(); } bool X86PassConfig::addInstSelector() { // Install an instruction selector. addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel())); // For ELF, cleanup any local-dynamic TLS accesses. if (TM->getTargetTriple().isOSBinFormatELF() && getOptLevel() != CodeGenOpt::None) addPass(createCleanupLocalDynamicTLSPass()); addPass(createX86GlobalBaseRegPass()); return false; } bool X86PassConfig::addILPOpts() { addPass(&EarlyIfConverterID); if (EnableMachineCombinerPass) addPass(&MachineCombinerID); return true; } bool X86PassConfig::addPreISel() { // Only add this pass for 32-bit x86 Windows. const Triple &TT = TM->getTargetTriple(); if (TT.isOSWindows() && TT.getArch() == Triple::x86) addPass(createX86WinEHStatePass()); return true; } void X86PassConfig::addPreRegAlloc() { if (getOptLevel() != CodeGenOpt::None) { addPass(createX86FixupSetCC()); addPass(createX86OptimizeLEAs()); addPass(createX86CallFrameOptimization()); } addPass(createX86WinAllocaExpander()); } void X86PassConfig::addPostRegAlloc() { addPass(createX86FloatingPointStackifierPass()); } void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); } void X86PassConfig::addPreEmitPass() { if (getOptLevel() != CodeGenOpt::None) addPass(createExecutionDependencyFixPass(&X86::VR128XRegClass)); if (UseVZeroUpper) addPass(createX86IssueVZeroUpperPass()); if (getOptLevel() != CodeGenOpt::None) { addPass(createX86FixupBWInsts()); addPass(createX86PadShortFunctions()); addPass(createX86FixupLEAs()); } } <commit_msg>Remove a use of subtarget initialization in the X86 backend so we can get rid of the default subtarget.<commit_after>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the X86 specific subclass of TargetMachine. // //===----------------------------------------------------------------------===// #include "X86TargetMachine.h" #include "X86.h" #include "X86TargetObjectFile.h" #include "X86TargetTransformInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/IR/Function.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner", cl::desc("Enable the machine combiner pass"), cl::init(true), cl::Hidden); namespace llvm { void initializeWinEHStatePassPass(PassRegistry &); } extern "C" void LLVMInitializeX86Target() { // Register the target. RegisterTargetMachine<X86TargetMachine> X(TheX86_32Target); RegisterTargetMachine<X86TargetMachine> Y(TheX86_64Target); PassRegistry &PR = *PassRegistry::getPassRegistry(); initializeWinEHStatePassPass(PR); initializeFixupBWInstPassPass(PR); } static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { if (TT.isOSBinFormatMachO()) { if (TT.getArch() == Triple::x86_64) return make_unique<X86_64MachoTargetObjectFile>(); return make_unique<TargetLoweringObjectFileMachO>(); } if (TT.isOSLinux() || TT.isOSNaCl()) return make_unique<X86LinuxNaClTargetObjectFile>(); if (TT.isOSBinFormatELF()) return make_unique<X86ELFTargetObjectFile>(); if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment()) return make_unique<X86WindowsTargetObjectFile>(); if (TT.isOSBinFormatCOFF()) return make_unique<TargetLoweringObjectFileCOFF>(); llvm_unreachable("unknown subtarget type"); } static std::string computeDataLayout(const Triple &TT) { // X86 is little endian std::string Ret = "e"; Ret += DataLayout::getManglingComponent(TT); // X86 and x32 have 32 bit pointers. if ((TT.isArch64Bit() && (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) || !TT.isArch64Bit()) Ret += "-p:32:32"; // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32. if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl()) Ret += "-i64:64"; else if (TT.isOSIAMCU()) Ret += "-i64:32-f64:32"; else Ret += "-f64:32:64"; // Some ABIs align long double to 128 bits, others to 32. if (TT.isOSNaCl() || TT.isOSIAMCU()) ; // No f80 else if (TT.isArch64Bit() || TT.isOSDarwin()) Ret += "-f80:128"; else Ret += "-f80:32"; if (TT.isOSIAMCU()) Ret += "-f128:32"; // The registers can hold 8, 16, 32 or, in x86-64, 64 bits. if (TT.isArch64Bit()) Ret += "-n8:16:32:64"; else Ret += "-n8:16:32"; // The stack is aligned to 32 bits on some ABIs and 128 bits on others. if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU()) Ret += "-a:0:32-S32"; else Ret += "-S128"; return Ret; } static Reloc::Model getEffectiveRelocModel(const Triple &TT, Optional<Reloc::Model> RM) { bool is64Bit = TT.getArch() == Triple::x86_64; if (!RM.hasValue()) { // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode. // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we // use static relocation model by default. if (TT.isOSDarwin()) { if (is64Bit) return Reloc::PIC_; return Reloc::DynamicNoPIC; } if (TT.isOSWindows() && is64Bit) return Reloc::PIC_; return Reloc::Static; } // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC // is defined as a model for code which may be used in static or dynamic // executables but not necessarily a shared library. On X86-32 we just // compile in -static mode, in x86-64 we use PIC. if (*RM == Reloc::DynamicNoPIC) { if (is64Bit) return Reloc::PIC_; if (!TT.isOSDarwin()) return Reloc::Static; } // If we are on Darwin, disallow static relocation model in X86-64 mode, since // the Mach-O file format doesn't support it. if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit) return Reloc::PIC_; return *RM; } /// Create an X86 target. /// X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional<Reloc::Model> RM, CodeModel::Model CM, CodeGenOpt::Level OL) : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM, OL), TLOF(createTLOF(getTargetTriple())), Subtarget(TT, CPU, FS, *this, Options.StackAlignmentOverride) { // Windows stack unwinder gets confused when execution flow "falls through" // after a call to 'noreturn' function. // To prevent that, we emit a trap for 'unreachable' IR instructions. // (which on X86, happens to be the 'ud2' instruction) // On PS4, the "return address" of a 'noreturn' call must still be within // the calling function, and TrapUnreachable is an easy way to get that. // The check here for 64-bit windows is a bit icky, but as we're unlikely // to ever want to mix 32 and 64-bit windows code in a single module // this should be fine. if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4()) this->Options.TrapUnreachable = true; // By default (and when -ffast-math is on), enable estimate codegen for // everything except scalar division. By default, use 1 refinement step for // all operations. Defaults may be overridden by using command-line options. // Scalar division estimates are disabled because they break too much // real-world code. These defaults match GCC behavior. this->Options.Reciprocals.setDefaults("sqrtf", true, 1); this->Options.Reciprocals.setDefaults("divf", false, 1); this->Options.Reciprocals.setDefaults("vec-sqrtf", true, 1); this->Options.Reciprocals.setDefaults("vec-divf", true, 1); initAsmInfo(); } X86TargetMachine::~X86TargetMachine() {} const X86Subtarget * X86TargetMachine::getSubtargetImpl(const Function &F) const { Attribute CPUAttr = F.getFnAttribute("target-cpu"); Attribute FSAttr = F.getFnAttribute("target-features"); StringRef CPU = !CPUAttr.hasAttribute(Attribute::None) ? CPUAttr.getValueAsString() : (StringRef)TargetCPU; StringRef FS = !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString() : (StringRef)TargetFS; SmallString<512> Key; Key.reserve(CPU.size() + FS.size()); Key += CPU; Key += FS; // FIXME: This is related to the code below to reset the target options, // we need to know whether or not the soft float flag is set on the // function before we can generate a subtarget. We also need to use // it as a key for the subtarget since that can be the only difference // between two functions. bool SoftFloat = F.getFnAttribute("use-soft-float").getValueAsString() == "true"; // If the soft float attribute is set on the function turn on the soft float // subtarget feature. if (SoftFloat) Key += FS.empty() ? "+soft-float" : ",+soft-float"; FS = Key.substr(CPU.size()); auto &I = SubtargetMap[Key]; if (!I) { // This needs to be done before we create a new subtarget since any // creation will depend on the TM and the code generation flags on the // function that reside in TargetOptions. resetTargetOptions(F); I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this, Options.StackAlignmentOverride); } return I.get(); } //===----------------------------------------------------------------------===// // Command line options for x86 //===----------------------------------------------------------------------===// static cl::opt<bool> UseVZeroUpper("x86-use-vzeroupper", cl::Hidden, cl::desc("Minimize AVX to SSE transition penalty"), cl::init(true)); //===----------------------------------------------------------------------===// // X86 TTI query. //===----------------------------------------------------------------------===// TargetIRAnalysis X86TargetMachine::getTargetIRAnalysis() { return TargetIRAnalysis([this](const Function &F) { return TargetTransformInfo(X86TTIImpl(this, F)); }); } //===----------------------------------------------------------------------===// // Pass Pipeline Configuration //===----------------------------------------------------------------------===// namespace { /// X86 Code Generator Pass Configuration Options. class X86PassConfig : public TargetPassConfig { public: X86PassConfig(X86TargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} X86TargetMachine &getX86TargetMachine() const { return getTM<X86TargetMachine>(); } void addIRPasses() override; bool addInstSelector() override; bool addILPOpts() override; bool addPreISel() override; void addPreRegAlloc() override; void addPostRegAlloc() override; void addPreEmitPass() override; void addPreSched2() override; }; } // namespace TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) { return new X86PassConfig(this, PM); } void X86PassConfig::addIRPasses() { addPass(createAtomicExpandPass(&getX86TargetMachine())); TargetPassConfig::addIRPasses(); } bool X86PassConfig::addInstSelector() { // Install an instruction selector. addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel())); // For ELF, cleanup any local-dynamic TLS accesses. if (TM->getTargetTriple().isOSBinFormatELF() && getOptLevel() != CodeGenOpt::None) addPass(createCleanupLocalDynamicTLSPass()); addPass(createX86GlobalBaseRegPass()); return false; } bool X86PassConfig::addILPOpts() { addPass(&EarlyIfConverterID); if (EnableMachineCombinerPass) addPass(&MachineCombinerID); return true; } bool X86PassConfig::addPreISel() { // Only add this pass for 32-bit x86 Windows. const Triple &TT = TM->getTargetTriple(); if (TT.isOSWindows() && TT.getArch() == Triple::x86) addPass(createX86WinEHStatePass()); return true; } void X86PassConfig::addPreRegAlloc() { if (getOptLevel() != CodeGenOpt::None) { addPass(createX86FixupSetCC()); addPass(createX86OptimizeLEAs()); addPass(createX86CallFrameOptimization()); } addPass(createX86WinAllocaExpander()); } void X86PassConfig::addPostRegAlloc() { addPass(createX86FloatingPointStackifierPass()); } void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); } void X86PassConfig::addPreEmitPass() { if (getOptLevel() != CodeGenOpt::None) addPass(createExecutionDependencyFixPass(&X86::VR128XRegClass)); if (UseVZeroUpper) addPass(createX86IssueVZeroUpperPass()); if (getOptLevel() != CodeGenOpt::None) { addPass(createX86FixupBWInsts()); addPass(createX86PadShortFunctions()); addPass(createX86FixupLEAs()); } } <|endoftext|>
<commit_before>//===- StripSymbols.cpp - Strip symbols and debug info from a module ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The StripSymbols transformation implements code stripping. Specifically, it // can delete: // // * names for virtual registers // * symbols for internal globals and functions // * debug information // // Note that this transformation makes code much less readable, so it should // only be used in situations where the 'strip' utility would be used, such as // reducing code size or making it harder to reverse engineer code. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Analysis/DebugInfo.h" #include "llvm/ValueSymbolTable.h" #include "llvm/TypeSymbolTable.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; namespace { class StripSymbols : public ModulePass { bool OnlyDebugInfo; public: static char ID; // Pass identification, replacement for typeid explicit StripSymbols(bool ODI = false) : ModulePass(&ID), OnlyDebugInfo(ODI) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; class StripNonDebugSymbols : public ModulePass { public: static char ID; // Pass identification, replacement for typeid explicit StripNonDebugSymbols() : ModulePass(&ID) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; class StripDebugDeclare : public ModulePass { public: static char ID; // Pass identification, replacement for typeid explicit StripDebugDeclare() : ModulePass(&ID) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; } char StripSymbols::ID = 0; static RegisterPass<StripSymbols> X("strip", "Strip all symbols from a module"); ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) { return new StripSymbols(OnlyDebugInfo); } char StripNonDebugSymbols::ID = 0; static RegisterPass<StripNonDebugSymbols> Y("strip-nondebug", "Strip all symbols, except dbg symbols, from a module"); ModulePass *llvm::createStripNonDebugSymbolsPass() { return new StripNonDebugSymbols(); } char StripDebugDeclare::ID = 0; static RegisterPass<StripDebugDeclare> Z("strip-debug-declare", "Strip all llvm.dbg.declare intrinsics"); ModulePass *llvm::createStripDebugDeclarePass() { return new StripDebugDeclare(); } /// OnlyUsedBy - Return true if V is only used by Usr. static bool OnlyUsedBy(Value *V, Value *Usr) { for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) { User *U = *I; if (U != Usr) return false; } return true; } static void RemoveDeadConstant(Constant *C) { assert(C->use_empty() && "Constant is not dead!"); SmallPtrSet<Constant*, 4> Operands; for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) if (isa<DerivedType>(C->getOperand(i)->getType()) && OnlyUsedBy(C->getOperand(i), C)) Operands.insert(cast<Constant>(C->getOperand(i))); if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { if (!GV->hasLocalLinkage()) return; // Don't delete non static globals. GV->eraseFromParent(); } else if (!isa<Function>(C)) if (isa<CompositeType>(C->getType())) C->destroyConstant(); // If the constant referenced anything, see if we can delete it as well. for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(), OE = Operands.end(); OI != OE; ++OI) RemoveDeadConstant(*OI); } // Strip the symbol table of its names. // static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) { for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) { Value *V = VI->getValue(); ++VI; if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) { if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg")) // Set name to "", removing from symbol table! V->setName(""); } } } // Strip the symbol table of its names. static void StripTypeSymtab(TypeSymbolTable &ST, bool PreserveDbgInfo) { for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) { if (PreserveDbgInfo && StringRef(TI->first).startswith("llvm.dbg")) ++TI; else ST.remove(TI++); } } /// Find values that are marked as llvm.used. static void findUsedValues(GlobalVariable *LLVMUsed, SmallPtrSet<const GlobalValue*, 8> &UsedValues) { if (LLVMUsed == 0) return; UsedValues.insert(LLVMUsed); ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer()); if (Inits == 0) return; for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) if (GlobalValue *GV = dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts())) UsedValues.insert(GV); } /// StripSymbolNames - Strip symbol names. static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) { SmallPtrSet<const GlobalValue*, 8> llvmUsedValues; findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues); findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues); for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0) if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg")) I->setName(""); // Internal symbols can't participate in linkage } for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0) if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg")) I->setName(""); // Internal symbols can't participate in linkage StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo); } // Remove all names from types. StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo); return true; } // StripDebugInfo - Strip debug info in the module if it exists. // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and // llvm.dbg.region.end calls, and any globals they point to if now dead. static bool StripDebugInfo(Module &M) { bool Changed = false; // Remove all of the calls to the debugger intrinsics, and remove them from // the module. if (Function *Declare = M.getFunction("llvm.dbg.declare")) { while (!Declare->use_empty()) { CallInst *CI = cast<CallInst>(Declare->use_back()); CI->eraseFromParent(); } Declare->eraseFromParent(); Changed = true; } NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv"); if (NMD) { Changed = true; NMD->eraseFromParent(); } unsigned MDDbgKind = M.getMDKindID("dbg"); for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI) for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) BI->setMetadata(MDDbgKind, 0); return true; } bool StripSymbols::runOnModule(Module &M) { bool Changed = false; Changed |= StripDebugInfo(M); if (!OnlyDebugInfo) Changed |= StripSymbolNames(M, false); return Changed; } bool StripNonDebugSymbols::runOnModule(Module &M) { return StripSymbolNames(M, true); } bool StripDebugDeclare::runOnModule(Module &M) { Function *Declare = M.getFunction("llvm.dbg.declare"); std::vector<Constant*> DeadConstants; if (Declare) { while (!Declare->use_empty()) { CallInst *CI = cast<CallInst>(Declare->use_back()); Value *Arg1 = CI->getOperand(1); Value *Arg2 = CI->getOperand(2); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg1->use_empty()) { if (Constant *C = dyn_cast<Constant>(Arg1)) DeadConstants.push_back(C); else RecursivelyDeleteTriviallyDeadInstructions(Arg1); } if (Arg2->use_empty()) if (Constant *C = dyn_cast<Constant>(Arg2)) DeadConstants.push_back(C); } Declare->eraseFromParent(); } while (!DeadConstants.empty()) { Constant *C = DeadConstants.back(); DeadConstants.pop_back(); if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { if (GV->hasLocalLinkage()) RemoveDeadConstant(GV); } else RemoveDeadConstant(C); } return true; } <commit_msg>Strip new llvm.dbg.value intrinsic.<commit_after>//===- StripSymbols.cpp - Strip symbols and debug info from a module ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The StripSymbols transformation implements code stripping. Specifically, it // can delete: // // * names for virtual registers // * symbols for internal globals and functions // * debug information // // Note that this transformation makes code much less readable, so it should // only be used in situations where the 'strip' utility would be used, such as // reducing code size or making it harder to reverse engineer code. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Analysis/DebugInfo.h" #include "llvm/ValueSymbolTable.h" #include "llvm/TypeSymbolTable.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; namespace { class StripSymbols : public ModulePass { bool OnlyDebugInfo; public: static char ID; // Pass identification, replacement for typeid explicit StripSymbols(bool ODI = false) : ModulePass(&ID), OnlyDebugInfo(ODI) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; class StripNonDebugSymbols : public ModulePass { public: static char ID; // Pass identification, replacement for typeid explicit StripNonDebugSymbols() : ModulePass(&ID) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; class StripDebugDeclare : public ModulePass { public: static char ID; // Pass identification, replacement for typeid explicit StripDebugDeclare() : ModulePass(&ID) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; } char StripSymbols::ID = 0; static RegisterPass<StripSymbols> X("strip", "Strip all symbols from a module"); ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) { return new StripSymbols(OnlyDebugInfo); } char StripNonDebugSymbols::ID = 0; static RegisterPass<StripNonDebugSymbols> Y("strip-nondebug", "Strip all symbols, except dbg symbols, from a module"); ModulePass *llvm::createStripNonDebugSymbolsPass() { return new StripNonDebugSymbols(); } char StripDebugDeclare::ID = 0; static RegisterPass<StripDebugDeclare> Z("strip-debug-declare", "Strip all llvm.dbg.declare intrinsics"); ModulePass *llvm::createStripDebugDeclarePass() { return new StripDebugDeclare(); } /// OnlyUsedBy - Return true if V is only used by Usr. static bool OnlyUsedBy(Value *V, Value *Usr) { for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) { User *U = *I; if (U != Usr) return false; } return true; } static void RemoveDeadConstant(Constant *C) { assert(C->use_empty() && "Constant is not dead!"); SmallPtrSet<Constant*, 4> Operands; for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) if (isa<DerivedType>(C->getOperand(i)->getType()) && OnlyUsedBy(C->getOperand(i), C)) Operands.insert(cast<Constant>(C->getOperand(i))); if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { if (!GV->hasLocalLinkage()) return; // Don't delete non static globals. GV->eraseFromParent(); } else if (!isa<Function>(C)) if (isa<CompositeType>(C->getType())) C->destroyConstant(); // If the constant referenced anything, see if we can delete it as well. for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(), OE = Operands.end(); OI != OE; ++OI) RemoveDeadConstant(*OI); } // Strip the symbol table of its names. // static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) { for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) { Value *V = VI->getValue(); ++VI; if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) { if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg")) // Set name to "", removing from symbol table! V->setName(""); } } } // Strip the symbol table of its names. static void StripTypeSymtab(TypeSymbolTable &ST, bool PreserveDbgInfo) { for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) { if (PreserveDbgInfo && StringRef(TI->first).startswith("llvm.dbg")) ++TI; else ST.remove(TI++); } } /// Find values that are marked as llvm.used. static void findUsedValues(GlobalVariable *LLVMUsed, SmallPtrSet<const GlobalValue*, 8> &UsedValues) { if (LLVMUsed == 0) return; UsedValues.insert(LLVMUsed); ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer()); if (Inits == 0) return; for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) if (GlobalValue *GV = dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts())) UsedValues.insert(GV); } /// StripSymbolNames - Strip symbol names. static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) { SmallPtrSet<const GlobalValue*, 8> llvmUsedValues; findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues); findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues); for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0) if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg")) I->setName(""); // Internal symbols can't participate in linkage } for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0) if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg")) I->setName(""); // Internal symbols can't participate in linkage StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo); } // Remove all names from types. StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo); return true; } // StripDebugInfo - Strip debug info in the module if it exists. // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and // llvm.dbg.region.end calls, and any globals they point to if now dead. static bool StripDebugInfo(Module &M) { bool Changed = false; // Remove all of the calls to the debugger intrinsics, and remove them from // the module. if (Function *Declare = M.getFunction("llvm.dbg.declare")) { while (!Declare->use_empty()) { CallInst *CI = cast<CallInst>(Declare->use_back()); CI->eraseFromParent(); } Declare->eraseFromParent(); Changed = true; } if (Function *DbgVal = M.getFunction("llvm.dbg.value")) { while (!DbgVal->use_empty()) { CallInst *CI = cast<CallInst>(DbgVal->use_back()); CI->eraseFromParent(); } DbgVal->eraseFromParent(); Changed = true; } NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv"); if (NMD) { Changed = true; NMD->eraseFromParent(); } unsigned MDDbgKind = M.getMDKindID("dbg"); for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI) for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) BI->setMetadata(MDDbgKind, 0); return true; } bool StripSymbols::runOnModule(Module &M) { bool Changed = false; Changed |= StripDebugInfo(M); if (!OnlyDebugInfo) Changed |= StripSymbolNames(M, false); return Changed; } bool StripNonDebugSymbols::runOnModule(Module &M) { return StripSymbolNames(M, true); } bool StripDebugDeclare::runOnModule(Module &M) { Function *Declare = M.getFunction("llvm.dbg.declare"); std::vector<Constant*> DeadConstants; if (Declare) { while (!Declare->use_empty()) { CallInst *CI = cast<CallInst>(Declare->use_back()); Value *Arg1 = CI->getOperand(1); Value *Arg2 = CI->getOperand(2); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg1->use_empty()) { if (Constant *C = dyn_cast<Constant>(Arg1)) DeadConstants.push_back(C); else RecursivelyDeleteTriviallyDeadInstructions(Arg1); } if (Arg2->use_empty()) if (Constant *C = dyn_cast<Constant>(Arg2)) DeadConstants.push_back(C); } Declare->eraseFromParent(); } while (!DeadConstants.empty()) { Constant *C = DeadConstants.back(); DeadConstants.pop_back(); if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { if (GV->hasLocalLinkage()) RemoveDeadConstant(GV); } else RemoveDeadConstant(C); } return true; } <|endoftext|>
<commit_before>//===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SSAUpdater class. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/SSAUpdater.h" #include "llvm/Instructions.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ValueHandle.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; typedef DenseMap<BasicBlock*, TrackingVH<Value> > AvailableValsTy; typedef std::vector<std::pair<BasicBlock*, TrackingVH<Value> > > IncomingPredInfoTy; static AvailableValsTy &getAvailableVals(void *AV) { return *static_cast<AvailableValsTy*>(AV); } static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) { return *static_cast<IncomingPredInfoTy*>(IPI); } SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI) : AV(0), PrototypeValue(0), IPI(0), InsertedPHIs(NewPHI) {} SSAUpdater::~SSAUpdater() { delete &getAvailableVals(AV); delete &getIncomingPredInfo(IPI); } /// Initialize - Reset this object to get ready for a new set of SSA /// updates. ProtoValue is the value used to name PHI nodes. void SSAUpdater::Initialize(Value *ProtoValue) { if (AV == 0) AV = new AvailableValsTy(); else getAvailableVals(AV).clear(); if (IPI == 0) IPI = new IncomingPredInfoTy(); else getIncomingPredInfo(IPI).clear(); PrototypeValue = ProtoValue; } /// HasValueForBlock - Return true if the SSAUpdater already has a value for /// the specified block. bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const { return getAvailableVals(AV).count(BB); } /// AddAvailableValue - Indicate that a rewritten value is available in the /// specified block with the specified value. void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) { assert(PrototypeValue != 0 && "Need to initialize SSAUpdater"); assert(PrototypeValue->getType() == V->getType() && "All rewritten values must have the same type"); getAvailableVals(AV)[BB] = V; } /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is /// live at the end of the specified block. Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) { assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State"); Value *Res = GetValueAtEndOfBlockInternal(BB); assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State"); return Res; } /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that /// is live in the middle of the specified block. /// /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one /// important case: if there is a definition of the rewritten value after the /// 'use' in BB. Consider code like this: /// /// X1 = ... /// SomeBB: /// use(X) /// X2 = ... /// br Cond, SomeBB, OutBB /// /// In this case, there are two values (X1 and X2) added to the AvailableVals /// set by the client of the rewriter, and those values are both live out of /// their respective blocks. However, the use of X happens in the *middle* of /// a block. Because of this, we need to insert a new PHI node in SomeBB to /// merge the appropriate values, and this value isn't live out of the block. /// Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) { // If there is no definition of the renamed variable in this block, just use // GetValueAtEndOfBlock to do our work. if (!getAvailableVals(AV).count(BB)) return GetValueAtEndOfBlock(BB); // Otherwise, we have the hard case. Get the live-in values for each // predecessor. SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues; Value *SingularValue = 0; // We can get our predecessor info by walking the pred_iterator list, but it // is relatively slow. If we already have PHI nodes in this block, walk one // of them to get the predecessor list instead. if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) { for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) { BasicBlock *PredBB = SomePhi->getIncomingBlock(i); Value *PredVal = GetValueAtEndOfBlock(PredBB); PredValues.push_back(std::make_pair(PredBB, PredVal)); // Compute SingularValue. if (i == 0) SingularValue = PredVal; else if (PredVal != SingularValue) SingularValue = 0; } } else { bool isFirstPred = true; for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { BasicBlock *PredBB = *PI; Value *PredVal = GetValueAtEndOfBlock(PredBB); PredValues.push_back(std::make_pair(PredBB, PredVal)); // Compute SingularValue. if (isFirstPred) { SingularValue = PredVal; isFirstPred = false; } else if (PredVal != SingularValue) SingularValue = 0; } } // If there are no predecessors, just return undef. if (PredValues.empty()) return UndefValue::get(PrototypeValue->getType()); // Otherwise, if all the merged values are the same, just use it. if (SingularValue != 0) return SingularValue; // Otherwise, we do need a PHI: check to see if we already have one available // in this block that produces the right value. if (isa<PHINode>(BB->begin())) { DenseMap<BasicBlock*, Value*> ValueMapping(PredValues.begin(), PredValues.end()); PHINode *SomePHI; for (BasicBlock::iterator It = BB->begin(); (SomePHI = dyn_cast<PHINode>(It)); ++It) { // Scan this phi to see if it is what we need. bool Equal = true; for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) if (ValueMapping[SomePHI->getIncomingBlock(i)] != SomePHI->getIncomingValue(i)) { Equal = false; break; } if (Equal) return SomePHI; } } // Ok, we have no way out, insert a new one now. PHINode *InsertedPHI = PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(), &BB->front()); InsertedPHI->reserveOperandSpace(PredValues.size()); // Fill in all the predecessors of the PHI. for (unsigned i = 0, e = PredValues.size(); i != e; ++i) InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first); // See if the PHI node can be merged to a single value. This can happen in // loop cases when we get a PHI of itself and one other value. if (Value *ConstVal = InsertedPHI->hasConstantValue()) { InsertedPHI->eraseFromParent(); return ConstVal; } // If the client wants to know about all new instructions, tell it. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI); DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n"); return InsertedPHI; } /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes, /// which use their value in the corresponding predecessor. void SSAUpdater::RewriteUse(Use &U) { Instruction *User = cast<Instruction>(U.getUser()); Value *V; if (PHINode *UserPN = dyn_cast<PHINode>(User)) V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U)); else V = GetValueInMiddleOfBlock(User->getParent()); U.set(V); } /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry /// for the specified BB and if so, return it. If not, construct SSA form by /// walking predecessors inserting PHI nodes as needed until we get to a block /// where the value is available. /// Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) { AvailableValsTy &AvailableVals = getAvailableVals(AV); // Query AvailableVals by doing an insertion of null. std::pair<AvailableValsTy::iterator, bool> InsertRes = AvailableVals.insert(std::make_pair(BB, WeakVH())); // Handle the case when the insertion fails because we have already seen BB. if (!InsertRes.second) { // If the insertion failed, there are two cases. The first case is that the // value is already available for the specified block. If we get this, just // return the value. if (InsertRes.first->second != 0) return InsertRes.first->second; // Otherwise, if the value we find is null, then this is the value is not // known but it is being computed elsewhere in our recursion. This means // that we have a cycle. Handle this by inserting a PHI node and returning // it. When we get back to the first instance of the recursion we will fill // in the PHI node. return InsertRes.first->second = PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(), &BB->front()); } // Okay, the value isn't in the map and we just inserted a null in the entry // to indicate that we're processing the block. Since we have no idea what // value is in this block, we have to recurse through our predecessors. // // While we're walking our predecessors, we keep track of them in a vector, // then insert a PHI node in the end if we actually need one. We could use a // smallvector here, but that would take a lot of stack space for every level // of the recursion, just use IncomingPredInfo as an explicit stack. IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI); unsigned FirstPredInfoEntry = IncomingPredInfo.size(); // As we're walking the predecessors, keep track of whether they are all // producing the same value. If so, this value will capture it, if not, it // will get reset to null. We distinguish the no-predecessor case explicitly // below. TrackingVH<Value> SingularValue; // We can get our predecessor info by walking the pred_iterator list, but it // is relatively slow. If we already have PHI nodes in this block, walk one // of them to get the predecessor list instead. if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) { for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) { BasicBlock *PredBB = SomePhi->getIncomingBlock(i); Value *PredVal = GetValueAtEndOfBlockInternal(PredBB); IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal)); // Compute SingularValue. if (i == 0) SingularValue = PredVal; else if (PredVal != SingularValue) SingularValue = 0; } } else { bool isFirstPred = true; for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { BasicBlock *PredBB = *PI; Value *PredVal = GetValueAtEndOfBlockInternal(PredBB); IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal)); // Compute SingularValue. if (isFirstPred) { SingularValue = PredVal; isFirstPred = false; } else if (PredVal != SingularValue) SingularValue = 0; } } // If there are no predecessors, then we must have found an unreachable block // just return 'undef'. Since there are no predecessors, InsertRes must not // be invalidated. if (IncomingPredInfo.size() == FirstPredInfoEntry) return InsertRes.first->second = UndefValue::get(PrototypeValue->getType()); /// Look up BB's entry in AvailableVals. 'InsertRes' may be invalidated. If /// this block is involved in a loop, a no-entry PHI node will have been /// inserted as InsertedVal. Otherwise, we'll still have the null we inserted /// above. TrackingVH<Value> &InsertedVal = AvailableVals[BB]; // If all the predecessor values are the same then we don't need to insert a // PHI. This is the simple and common case. if (SingularValue) { // If a PHI node got inserted, replace it with the singlar value and delete // it. if (InsertedVal) { PHINode *OldVal = cast<PHINode>(InsertedVal); // Be careful about dead loops. These RAUW's also update InsertedVal. if (InsertedVal != SingularValue) OldVal->replaceAllUsesWith(SingularValue); else OldVal->replaceAllUsesWith(UndefValue::get(InsertedVal->getType())); OldVal->eraseFromParent(); } else { InsertedVal = SingularValue; } // Either path through the 'if' should have set insertedVal -> SingularVal. assert((InsertedVal == SingularValue || isa<UndefValue>(InsertedVal)) && "RAUW didn't change InsertedVal to be SingularVal"); // Drop the entries we added in IncomingPredInfo to restore the stack. IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry, IncomingPredInfo.end()); return SingularValue; } // Otherwise, we do need a PHI: insert one now if we don't already have one. if (InsertedVal == 0) InsertedVal = PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(), &BB->front()); PHINode *InsertedPHI = cast<PHINode>(InsertedVal); InsertedPHI->reserveOperandSpace(IncomingPredInfo.size()-FirstPredInfoEntry); // Fill in all the predecessors of the PHI. for (IncomingPredInfoTy::iterator I = IncomingPredInfo.begin()+FirstPredInfoEntry, E = IncomingPredInfo.end(); I != E; ++I) InsertedPHI->addIncoming(I->second, I->first); // Drop the entries we added in IncomingPredInfo to restore the stack. IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry, IncomingPredInfo.end()); // See if the PHI node can be merged to a single value. This can happen in // loop cases when we get a PHI of itself and one other value. if (Value *ConstVal = InsertedPHI->hasConstantValue()) { InsertedPHI->replaceAllUsesWith(ConstVal); InsertedPHI->eraseFromParent(); InsertedVal = ConstVal; } else { DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n"); // If the client wants to know about all new instructions, tell it. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI); } return InsertedVal; } <commit_msg>improve indentation avoid a pointless conversion from weakvh to trackingvh, no functionality change.<commit_after>//===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SSAUpdater class. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/SSAUpdater.h" #include "llvm/Instructions.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ValueHandle.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; typedef DenseMap<BasicBlock*, TrackingVH<Value> > AvailableValsTy; typedef std::vector<std::pair<BasicBlock*, TrackingVH<Value> > > IncomingPredInfoTy; static AvailableValsTy &getAvailableVals(void *AV) { return *static_cast<AvailableValsTy*>(AV); } static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) { return *static_cast<IncomingPredInfoTy*>(IPI); } SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI) : AV(0), PrototypeValue(0), IPI(0), InsertedPHIs(NewPHI) {} SSAUpdater::~SSAUpdater() { delete &getAvailableVals(AV); delete &getIncomingPredInfo(IPI); } /// Initialize - Reset this object to get ready for a new set of SSA /// updates. ProtoValue is the value used to name PHI nodes. void SSAUpdater::Initialize(Value *ProtoValue) { if (AV == 0) AV = new AvailableValsTy(); else getAvailableVals(AV).clear(); if (IPI == 0) IPI = new IncomingPredInfoTy(); else getIncomingPredInfo(IPI).clear(); PrototypeValue = ProtoValue; } /// HasValueForBlock - Return true if the SSAUpdater already has a value for /// the specified block. bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const { return getAvailableVals(AV).count(BB); } /// AddAvailableValue - Indicate that a rewritten value is available in the /// specified block with the specified value. void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) { assert(PrototypeValue != 0 && "Need to initialize SSAUpdater"); assert(PrototypeValue->getType() == V->getType() && "All rewritten values must have the same type"); getAvailableVals(AV)[BB] = V; } /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is /// live at the end of the specified block. Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) { assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State"); Value *Res = GetValueAtEndOfBlockInternal(BB); assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State"); return Res; } /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that /// is live in the middle of the specified block. /// /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one /// important case: if there is a definition of the rewritten value after the /// 'use' in BB. Consider code like this: /// /// X1 = ... /// SomeBB: /// use(X) /// X2 = ... /// br Cond, SomeBB, OutBB /// /// In this case, there are two values (X1 and X2) added to the AvailableVals /// set by the client of the rewriter, and those values are both live out of /// their respective blocks. However, the use of X happens in the *middle* of /// a block. Because of this, we need to insert a new PHI node in SomeBB to /// merge the appropriate values, and this value isn't live out of the block. /// Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) { // If there is no definition of the renamed variable in this block, just use // GetValueAtEndOfBlock to do our work. if (!getAvailableVals(AV).count(BB)) return GetValueAtEndOfBlock(BB); // Otherwise, we have the hard case. Get the live-in values for each // predecessor. SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues; Value *SingularValue = 0; // We can get our predecessor info by walking the pred_iterator list, but it // is relatively slow. If we already have PHI nodes in this block, walk one // of them to get the predecessor list instead. if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) { for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) { BasicBlock *PredBB = SomePhi->getIncomingBlock(i); Value *PredVal = GetValueAtEndOfBlock(PredBB); PredValues.push_back(std::make_pair(PredBB, PredVal)); // Compute SingularValue. if (i == 0) SingularValue = PredVal; else if (PredVal != SingularValue) SingularValue = 0; } } else { bool isFirstPred = true; for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { BasicBlock *PredBB = *PI; Value *PredVal = GetValueAtEndOfBlock(PredBB); PredValues.push_back(std::make_pair(PredBB, PredVal)); // Compute SingularValue. if (isFirstPred) { SingularValue = PredVal; isFirstPred = false; } else if (PredVal != SingularValue) SingularValue = 0; } } // If there are no predecessors, just return undef. if (PredValues.empty()) return UndefValue::get(PrototypeValue->getType()); // Otherwise, if all the merged values are the same, just use it. if (SingularValue != 0) return SingularValue; // Otherwise, we do need a PHI: check to see if we already have one available // in this block that produces the right value. if (isa<PHINode>(BB->begin())) { DenseMap<BasicBlock*, Value*> ValueMapping(PredValues.begin(), PredValues.end()); PHINode *SomePHI; for (BasicBlock::iterator It = BB->begin(); (SomePHI = dyn_cast<PHINode>(It)); ++It) { // Scan this phi to see if it is what we need. bool Equal = true; for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) if (ValueMapping[SomePHI->getIncomingBlock(i)] != SomePHI->getIncomingValue(i)) { Equal = false; break; } if (Equal) return SomePHI; } } // Ok, we have no way out, insert a new one now. PHINode *InsertedPHI = PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(), &BB->front()); InsertedPHI->reserveOperandSpace(PredValues.size()); // Fill in all the predecessors of the PHI. for (unsigned i = 0, e = PredValues.size(); i != e; ++i) InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first); // See if the PHI node can be merged to a single value. This can happen in // loop cases when we get a PHI of itself and one other value. if (Value *ConstVal = InsertedPHI->hasConstantValue()) { InsertedPHI->eraseFromParent(); return ConstVal; } // If the client wants to know about all new instructions, tell it. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI); DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n"); return InsertedPHI; } /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes, /// which use their value in the corresponding predecessor. void SSAUpdater::RewriteUse(Use &U) { Instruction *User = cast<Instruction>(U.getUser()); Value *V; if (PHINode *UserPN = dyn_cast<PHINode>(User)) V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U)); else V = GetValueInMiddleOfBlock(User->getParent()); U.set(V); } /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry /// for the specified BB and if so, return it. If not, construct SSA form by /// walking predecessors inserting PHI nodes as needed until we get to a block /// where the value is available. /// Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) { AvailableValsTy &AvailableVals = getAvailableVals(AV); // Query AvailableVals by doing an insertion of null. std::pair<AvailableValsTy::iterator, bool> InsertRes = AvailableVals.insert(std::make_pair(BB, TrackingVH<Value>())); // Handle the case when the insertion fails because we have already seen BB. if (!InsertRes.second) { // If the insertion failed, there are two cases. The first case is that the // value is already available for the specified block. If we get this, just // return the value. if (InsertRes.first->second != 0) return InsertRes.first->second; // Otherwise, if the value we find is null, then this is the value is not // known but it is being computed elsewhere in our recursion. This means // that we have a cycle. Handle this by inserting a PHI node and returning // it. When we get back to the first instance of the recursion we will fill // in the PHI node. return InsertRes.first->second = PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(), &BB->front()); } // Okay, the value isn't in the map and we just inserted a null in the entry // to indicate that we're processing the block. Since we have no idea what // value is in this block, we have to recurse through our predecessors. // // While we're walking our predecessors, we keep track of them in a vector, // then insert a PHI node in the end if we actually need one. We could use a // smallvector here, but that would take a lot of stack space for every level // of the recursion, just use IncomingPredInfo as an explicit stack. IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI); unsigned FirstPredInfoEntry = IncomingPredInfo.size(); // As we're walking the predecessors, keep track of whether they are all // producing the same value. If so, this value will capture it, if not, it // will get reset to null. We distinguish the no-predecessor case explicitly // below. TrackingVH<Value> SingularValue; // We can get our predecessor info by walking the pred_iterator list, but it // is relatively slow. If we already have PHI nodes in this block, walk one // of them to get the predecessor list instead. if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) { for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) { BasicBlock *PredBB = SomePhi->getIncomingBlock(i); Value *PredVal = GetValueAtEndOfBlockInternal(PredBB); IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal)); // Compute SingularValue. if (i == 0) SingularValue = PredVal; else if (PredVal != SingularValue) SingularValue = 0; } } else { bool isFirstPred = true; for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { BasicBlock *PredBB = *PI; Value *PredVal = GetValueAtEndOfBlockInternal(PredBB); IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal)); // Compute SingularValue. if (isFirstPred) { SingularValue = PredVal; isFirstPred = false; } else if (PredVal != SingularValue) SingularValue = 0; } } // If there are no predecessors, then we must have found an unreachable block // just return 'undef'. Since there are no predecessors, InsertRes must not // be invalidated. if (IncomingPredInfo.size() == FirstPredInfoEntry) return InsertRes.first->second = UndefValue::get(PrototypeValue->getType()); /// Look up BB's entry in AvailableVals. 'InsertRes' may be invalidated. If /// this block is involved in a loop, a no-entry PHI node will have been /// inserted as InsertedVal. Otherwise, we'll still have the null we inserted /// above. TrackingVH<Value> &InsertedVal = AvailableVals[BB]; // If all the predecessor values are the same then we don't need to insert a // PHI. This is the simple and common case. if (SingularValue) { // If a PHI node got inserted, replace it with the singlar value and delete // it. if (InsertedVal) { PHINode *OldVal = cast<PHINode>(InsertedVal); // Be careful about dead loops. These RAUW's also update InsertedVal. if (InsertedVal != SingularValue) OldVal->replaceAllUsesWith(SingularValue); else OldVal->replaceAllUsesWith(UndefValue::get(InsertedVal->getType())); OldVal->eraseFromParent(); } else { InsertedVal = SingularValue; } // Either path through the 'if' should have set insertedVal -> SingularVal. assert((InsertedVal == SingularValue || isa<UndefValue>(InsertedVal)) && "RAUW didn't change InsertedVal to be SingularVal"); // Drop the entries we added in IncomingPredInfo to restore the stack. IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry, IncomingPredInfo.end()); return SingularValue; } // Otherwise, we do need a PHI: insert one now if we don't already have one. if (InsertedVal == 0) InsertedVal = PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(), &BB->front()); PHINode *InsertedPHI = cast<PHINode>(InsertedVal); InsertedPHI->reserveOperandSpace(IncomingPredInfo.size()-FirstPredInfoEntry); // Fill in all the predecessors of the PHI. for (IncomingPredInfoTy::iterator I = IncomingPredInfo.begin()+FirstPredInfoEntry, E = IncomingPredInfo.end(); I != E; ++I) InsertedPHI->addIncoming(I->second, I->first); // Drop the entries we added in IncomingPredInfo to restore the stack. IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry, IncomingPredInfo.end()); // See if the PHI node can be merged to a single value. This can happen in // loop cases when we get a PHI of itself and one other value. if (Value *ConstVal = InsertedPHI->hasConstantValue()) { InsertedPHI->replaceAllUsesWith(ConstVal); InsertedPHI->eraseFromParent(); InsertedVal = ConstVal; } else { DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n"); // If the client wants to know about all new instructions, tell it. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI); } return InsertedVal; } <|endoftext|>
<commit_before>#include "AppDelegate.h" #include "scenes/SceneMenu.h" #include "scenes/SceneFinish.h" #include "scenes/SceneGame.h" #include "SoundManager/SoundManager.h" USING_NS_CC; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } //if you want a different context,just modify the value of glContextAttrs //it will takes effect on all platforms void AppDelegate::initGLContextAttrs() { //set OpenGL context attributions,now can only set six attributions: //red,green,blue,alpha,depth,stencil GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { glview = GLViewImpl::create("Wonky Monkey"); director->setOpenGLView(glview); } // turn on display FPS // director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); Size screenSize = glview->getFrameSize(); //screenSize.height = 540; //CCLOG("glview->getFrameSize(): %f, %f\n", screenSize.width, screenSize.height); std::vector<std::string> searchPaths; if (screenSize.height > 1300) { searchPaths.push_back("ipadhd"); director->setContentScaleFactor(1.0); } else if (screenSize.height > 480) { searchPaths.push_back("hd"); director->setContentScaleFactor(0.5); } else { searchPaths.push_back("sd"); director->setContentScaleFactor(0.25); } FileUtils::getInstance()->setSearchPaths(searchPaths); director->getOpenGLView()->setDesignResolutionSize(2732, 1536, ResolutionPolicy::NO_BORDER); auto scene = SceneGame::createWithPhysics(); director->runWithScene(scene); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); cocos2d::experimental::AudioEngine::pauseAll(); // if you use SimpleAudioEngine, it must be pause // SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); cocos2d::experimental::AudioEngine::resume(sound_best_loop); cocos2d::experimental::AudioEngine::resume(sound_noise_loop); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); } <commit_msg>rand(time(0));<commit_after>#include "AppDelegate.h" #include "scenes/SceneMenu.h" #include "scenes/SceneFinish.h" #include "scenes/SceneGame.h" #include "SoundManager/SoundManager.h" USING_NS_CC; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } //if you want a different context,just modify the value of glContextAttrs //it will takes effect on all platforms void AppDelegate::initGLContextAttrs() { //set OpenGL context attributions,now can only set six attributions: //red,green,blue,alpha,depth,stencil GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { glview = GLViewImpl::create("Wonky Monkey"); director->setOpenGLView(glview); } // turn on display FPS // director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); Size screenSize = glview->getFrameSize(); //screenSize.height = 540; //CCLOG("glview->getFrameSize(): %f, %f\n", screenSize.width, screenSize.height); std::vector<std::string> searchPaths; if (screenSize.height > 1300) { searchPaths.push_back("ipadhd"); director->setContentScaleFactor(1.0); } else if (screenSize.height > 480) { searchPaths.push_back("hd"); director->setContentScaleFactor(0.5); } else { searchPaths.push_back("sd"); director->setContentScaleFactor(0.25); } FileUtils::getInstance()->setSearchPaths(searchPaths); director->getOpenGLView()->setDesignResolutionSize(2732, 1536, ResolutionPolicy::NO_BORDER); auto scene = SceneGame::createWithPhysics(); director->runWithScene(scene); srand(time(0)); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); cocos2d::experimental::AudioEngine::pauseAll(); // if you use SimpleAudioEngine, it must be pause // SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); cocos2d::experimental::AudioEngine::resume(sound_best_loop); cocos2d::experimental::AudioEngine::resume(sound_noise_loop); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); } <|endoftext|>
<commit_before>/* pluginloader.cpp - Kopete Plugin Loader Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org> Portions of this code based in Noatun plugin code: Copyright (c) 2000-2002 The Noatun Developers Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "pluginloader.h" #include <qapplication.h> #include <qdir.h> #include <qfile.h> #include <qregexp.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include <knotifyclient.h> #include <kparts/componentfactory.h> #include <ksimpleconfig.h> #include <kstaticdeleter.h> #include <kstandarddirs.h> #include <kurl.h> #include "kopeteplugin.h" class KopeteLibraryInfo; // Put the static deleter in its anonymous namespace namespace { KStaticDeleter<LibraryLoader> sd; } bool operator ==(const KopeteLibraryInfo &a, const KopeteLibraryInfo &b) { // Feels like cheating, doesn't it? return a.specfile == b.specfile; } LibraryLoader* LibraryLoader::s_pluginLoader = 0L; LibraryLoader* LibraryLoader::pluginLoader() { if( !s_pluginLoader ) sd.setObject( s_pluginLoader, new LibraryLoader() ); return s_pluginLoader; } LibraryLoader::LibraryLoader() : QObject( qApp ) { } LibraryLoader::~LibraryLoader() { QDictIterator<KopetePlugin> i( m_loadedPlugins ); while( i.current() ) { // Remove causes the iterator to auto-increment, so // only increment explicitly when not removing if( getInfo( i.currentKey() ).type != QString::fromLatin1( "Kopete/Protocol" ) ) delete i.current(); else ++i; } i.toFirst(); while( i.current() ) delete i.current(); kdDebug( 14010 ) << "LibraryLoader::~LibraryLoader(): all plugins removed" << endl; } QPtrList<KopetePlugin> LibraryLoader::plugins() const { QPtrList<KopetePlugin> list; QDictIterator<KopetePlugin> i( m_loadedPlugins ); for( ; i.current(); ++i ) list.append( i.current() ); return list; } QValueList<KopeteLibraryInfo> LibraryLoader::loaded() const { QValueList<KopeteLibraryInfo> items; QDictIterator<KopetePlugin> i( m_loadedPlugins ); for( ; i.current(); ++i ) { if( m_loadedPlugins[ i.currentKey() ] ) items.append( getInfo( i.currentKey() ) ); } return items; } bool LibraryLoader::loadAll() { KConfig *config=KGlobal::config(); config->setGroup(""); QStringList modules = config->readListEntry("Plugins"); // Session management... /* for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i) { KopeteLibraryInfo info=getInfo(*i); if (!info.type.contains("sm")) continue; loadPlugin( *i ); } */ for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i) { KopeteLibraryInfo info = getInfo( *i ); loadPlugin( *i ); } return true; } KopeteLibraryInfo LibraryLoader::getInfo(const QString &spec) const { QMap<QString, KopeteLibraryInfo>::iterator cached = m_cachedInfo.find(spec); if (cached != m_cachedInfo.end() ) return *cached; KopeteLibraryInfo info; QString specPath = ( spec[ 0 ] == '/' ) ? spec : KGlobal::dirs()->findResource( "services", spec ); if( !QFile::exists( specPath ) ) return info; KSimpleConfig file( specPath ); if( spec.find( '/' ) >= 0 ) info.specfile = KURL( spec ).fileName(); else info.specfile = spec; file.setGroup( QString::fromLatin1( "Desktop Entry" ) ); info.filename = file.readEntry( "X-KDE-Library" ); info.author = file.readEntry( "X-Kopete-Author" ); info.site = file.readEntry( "X-Kopete-Site" ); info.email = file.readEntry( "X-Kopete-Email" ); info.type = file.readEntry( "ServiceTypes" ); info.name = file.readEntry( "Name" ); info.comment = file.readEntry( "Comment" ); info.license = file.readEntry( "X-Kopete-License" ); info.icon = file.readEntry( "Icon" ); info.pluginId = file.readEntry( "X-Kopete-Plugin-Id" ); info.messagingProtocol = file.readEntry( "X-Kopete-Messaging-Protocol" ); if ( info.type != QString::fromLatin1( "Kopete/Plugin" ) && info.type != QString::fromLatin1( "Kopete/Protocol" ) ) return KopeteLibraryInfo(); m_cachedInfo[ spec ] = info; return info; } bool LibraryLoader::isLoaded( const QString &spec ) const { KopetePlugin *p = m_loadedPlugins[ spec ]; return p; } void LibraryLoader::setModules(const QStringList &mods) { KConfig *config=KGlobal::config(); config->setGroup(""); config->writeEntry("Plugins", mods); KGlobal::config()->sync(); } QValueList<KopeteLibraryInfo> LibraryLoader::available() const { QValueList<KopeteLibraryInfo> items; QStringList files = KGlobal::dirs()->findAllResources( "services", QString::fromLatin1( "*.desktop" ), false, true ); for( QStringList::Iterator i=files.begin(); i!=files.end(); ++i ) { KopeteLibraryInfo info = getInfo( *i ); if ( info.type == QString::fromLatin1( "Kopete/Plugin" ) || info.type == QString::fromLatin1( "Kopete/Protocol" ) ) items.append( info ); } return items; } bool LibraryLoader::loadPlugin( const QString &spec ) { kdDebug( 14010 ) << k_funcinfo << spec << endl; QString pluginId = spec; pluginId.remove( QRegExp( QString::fromLatin1( ".desktop$" ) ) ); KopetePlugin *plugin = KParts::ComponentFactory::createInstanceFromQuery<KopetePlugin>( QString::fromLatin1( "Kopete/Plugin" ), QString::fromLatin1( "[X-Kopete-Plugin-Id]=='%1'" ).arg( pluginId ), this ); //KopetePlugin *plugin = m_loadedPlugins[ spec ]; if( plugin ) { /*KopeteLibraryInfo info = getInfo( spec ); if( info.specfile != spec ) return false;*/ m_loadedPlugins.insert( spec, plugin ); connect( plugin, SIGNAL( destroyed( QObject * ) ), SLOT( slotPluginDestroyed( QObject * ) ) ); // Automatically load the i18n catalogue for the plugin //KGlobal::locale()->insertCatalogue( info.filename ); m_addressBookFields.insert( plugin, plugin->addressBookFields() ); kdDebug( 14010 ) << k_funcinfo << "Successfully loaded plugin '" << pluginId << "'"<< endl; emit pluginLoaded( plugin ); return true; } else { kdDebug( 14010 ) << k_funcinfo << "Unable to load plugin '" << pluginId << "'!" << endl; return false; } } bool LibraryLoader::remove( const QString &spec ) { KopetePlugin *plugin = m_loadedPlugins[ spec ]; if( !plugin ) return false; delete plugin; return true; } void LibraryLoader::slotPluginDestroyed( QObject *o ) { m_addressBookFields.remove( static_cast<KopetePlugin *>( o ) ); QDictIterator<KopetePlugin> it( m_loadedPlugins ); for( ; it.current() ; ++it ) { if( it.current() == o ) { m_loadedPlugins.remove( it.currentKey() ); break; } } // FIXME: Most likely most data structures here leak and are bound // to cause crashes. Find and identify those. } QStringList LibraryLoader::addressBookFields( KopetePlugin *p ) const { if( m_addressBookFields.contains( p ) ) return m_addressBookFields[ p ]; else return QStringList(); } KopetePlugin * LibraryLoader::searchByName(const QString &name) { for( QDictIterator<KopetePlugin> i( m_loadedPlugins ); i.current(); ++i ) { if (getInfo(i.currentKey()).name==name) return (*i); } return 0L; } KopetePlugin* LibraryLoader::searchByID( const QString &Id ) { QValueList<KopeteLibraryInfo> l = loaded(); for ( QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i ) { KopetePlugin *tmp_plug = m_loadedPlugins[ ( *i ).specfile ]; if( tmp_plug->pluginId() == Id ) return tmp_plug; } return NULL; } QString LibraryLoader::pluginName( const KopetePlugin *plugin ) const { for( QDictIterator<KopetePlugin> i( m_loadedPlugins ); i.current(); ++i ) { if( i.current() == plugin ) return getInfo( i.currentKey() ).name; } return QString::fromLatin1( "ERROR: plugin unknown" ); } QString LibraryLoader::pluginIcon( const KopetePlugin *plugin ) const { for( QDictIterator<KopetePlugin> i( m_loadedPlugins ); i.current(); ++i ) { if( i.current() == plugin ) return getInfo( i.currentKey() ).icon; } return QString::fromLatin1( "ERROR: plugin unknown" ); } #include "pluginloader.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>REMOVE THIS ASAP: Workaround for broken kdelibs from CVS HEAD<commit_after>/* pluginloader.cpp - Kopete Plugin Loader Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org> Portions of this code based in Noatun plugin code: Copyright (c) 2000-2002 The Noatun Developers Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "pluginloader.h" #include <qapplication.h> #include <qdir.h> #include <qfile.h> #include <qregexp.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include <knotifyclient.h> #include <kparts/componentfactory.h> #include <ksimpleconfig.h> #include <kstaticdeleter.h> #include <kstandarddirs.h> #include <kurl.h> #include "kopeteplugin.h" class KopeteLibraryInfo; // Put the static deleter in its anonymous namespace namespace { KStaticDeleter<LibraryLoader> sd; } bool operator ==(const KopeteLibraryInfo &a, const KopeteLibraryInfo &b) { // Feels like cheating, doesn't it? return a.specfile == b.specfile; } LibraryLoader* LibraryLoader::s_pluginLoader = 0L; LibraryLoader* LibraryLoader::pluginLoader() { if( !s_pluginLoader ) sd.setObject( s_pluginLoader, new LibraryLoader() ); return s_pluginLoader; } LibraryLoader::LibraryLoader() : QObject( qApp ) { } LibraryLoader::~LibraryLoader() { QDictIterator<KopetePlugin> i( m_loadedPlugins ); while( i.current() ) { // Remove causes the iterator to auto-increment, so // only increment explicitly when not removing if( getInfo( i.currentKey() ).type != QString::fromLatin1( "Kopete/Protocol" ) ) delete i.current(); else ++i; } i.toFirst(); while( i.current() ) delete i.current(); kdDebug( 14010 ) << "LibraryLoader::~LibraryLoader(): all plugins removed" << endl; } QPtrList<KopetePlugin> LibraryLoader::plugins() const { QPtrList<KopetePlugin> list; QDictIterator<KopetePlugin> i( m_loadedPlugins ); for( ; i.current(); ++i ) list.append( i.current() ); return list; } QValueList<KopeteLibraryInfo> LibraryLoader::loaded() const { QValueList<KopeteLibraryInfo> items; QDictIterator<KopetePlugin> i( m_loadedPlugins ); for( ; i.current(); ++i ) { if( m_loadedPlugins[ i.currentKey() ] ) items.append( getInfo( i.currentKey() ) ); } return items; } bool LibraryLoader::loadAll() { KConfig *config=KGlobal::config(); config->setGroup(""); QStringList modules = config->readListEntry("Plugins"); // Session management... /* for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i) { KopeteLibraryInfo info=getInfo(*i); if (!info.type.contains("sm")) continue; loadPlugin( *i ); } */ for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i) { KopeteLibraryInfo info = getInfo( *i ); loadPlugin( *i ); } return true; } KopeteLibraryInfo LibraryLoader::getInfo(const QString &spec) const { QMap<QString, KopeteLibraryInfo>::iterator cached = m_cachedInfo.find(spec); if (cached != m_cachedInfo.end() ) return *cached; KopeteLibraryInfo info; QString specPath = ( spec[ 0 ] == '/' ) ? spec : KGlobal::dirs()->findResource( "services", spec ); if( !QFile::exists( specPath ) ) return info; KSimpleConfig file( specPath ); if( spec.find( '/' ) >= 0 ) info.specfile = KURL( spec ).fileName(); else info.specfile = spec; file.setGroup( QString::fromLatin1( "Desktop Entry" ) ); info.filename = file.readEntry( "X-KDE-Library" ); info.author = file.readEntry( "X-Kopete-Author" ); info.site = file.readEntry( "X-Kopete-Site" ); info.email = file.readEntry( "X-Kopete-Email" ); info.type = file.readEntry( "ServiceTypes" ); info.name = file.readEntry( "Name" ); info.comment = file.readEntry( "Comment" ); info.license = file.readEntry( "X-Kopete-License" ); info.icon = file.readEntry( "Icon" ); info.pluginId = file.readEntry( "X-Kopete-Plugin-Id" ); info.messagingProtocol = file.readEntry( "X-Kopete-Messaging-Protocol" ); if ( info.type != QString::fromLatin1( "Kopete/Plugin" ) && info.type != QString::fromLatin1( "Kopete/Protocol" ) ) return KopeteLibraryInfo(); m_cachedInfo[ spec ] = info; return info; } bool LibraryLoader::isLoaded( const QString &spec ) const { KopetePlugin *p = m_loadedPlugins[ spec ]; return p; } void LibraryLoader::setModules(const QStringList &mods) { KConfig *config=KGlobal::config(); config->setGroup(""); config->writeEntry("Plugins", mods); KGlobal::config()->sync(); } QValueList<KopeteLibraryInfo> LibraryLoader::available() const { QValueList<KopeteLibraryInfo> items; QStringList files = KGlobal::dirs()->findAllResources( "services", QString::fromLatin1( "*.desktop" ), false, true ); for( QStringList::Iterator i=files.begin(); i!=files.end(); ++i ) { KopeteLibraryInfo info = getInfo( *i ); if ( info.type == QString::fromLatin1( "Kopete/Plugin" ) || info.type == QString::fromLatin1( "Kopete/Protocol" ) ) items.append( info ); } return items; } bool LibraryLoader::loadPlugin( const QString &spec ) { kdDebug( 14010 ) << k_funcinfo << spec << endl; QString pluginId = spec; pluginId.remove( QRegExp( QString::fromLatin1( ".desktop$" ) ) ); KopetePlugin *plugin; plugin = KParts::ComponentFactory::createInstanceFromQuery<KopetePlugin>( QString::fromLatin1("Kopete/Plugin"), QString::fromLatin1("[X-Kopete-Plugin-Id]=='%1'").arg(pluginId), this); // BEGIN =========================================================================== // TODO: REMOVE THIS ASAP, WORKAROUND FOR BROKEN KDELIBS AROUND APRIL 2003! if( !plugin ) // maybe it's a protocol? { plugin = KParts::ComponentFactory::createInstanceFromQuery<KopetePlugin>( QString::fromLatin1("Kopete/Protocol"), QString::fromLatin1("[X-Kopete-Plugin-Id]=='%1'").arg(pluginId), this); } // END ============================================================================= //KopetePlugin *plugin = m_loadedPlugins[ spec ]; if( plugin ) { /*KopeteLibraryInfo info = getInfo( spec ); if( info.specfile != spec ) return false;*/ m_loadedPlugins.insert( spec, plugin ); connect( plugin, SIGNAL( destroyed( QObject * ) ), SLOT( slotPluginDestroyed( QObject * ) ) ); // Automatically load the i18n catalogue for the plugin //KGlobal::locale()->insertCatalogue( info.filename ); m_addressBookFields.insert( plugin, plugin->addressBookFields() ); kdDebug( 14010 ) << k_funcinfo << "Successfully loaded plugin '" << pluginId << "'"<< endl; emit pluginLoaded( plugin ); return true; } else { kdDebug( 14010 ) << k_funcinfo << "Unable to load plugin '" << pluginId << "'!" << endl; return false; } } bool LibraryLoader::remove( const QString &spec ) { KopetePlugin *plugin = m_loadedPlugins[ spec ]; if( !plugin ) return false; delete plugin; return true; } void LibraryLoader::slotPluginDestroyed( QObject *o ) { m_addressBookFields.remove( static_cast<KopetePlugin *>( o ) ); QDictIterator<KopetePlugin> it( m_loadedPlugins ); for( ; it.current() ; ++it ) { if( it.current() == o ) { m_loadedPlugins.remove( it.currentKey() ); break; } } // FIXME: Most likely most data structures here leak and are bound // to cause crashes. Find and identify those. } QStringList LibraryLoader::addressBookFields( KopetePlugin *p ) const { if( m_addressBookFields.contains( p ) ) return m_addressBookFields[ p ]; else return QStringList(); } KopetePlugin * LibraryLoader::searchByName(const QString &name) { for( QDictIterator<KopetePlugin> i( m_loadedPlugins ); i.current(); ++i ) { if (getInfo(i.currentKey()).name==name) return (*i); } return 0L; } KopetePlugin* LibraryLoader::searchByID( const QString &Id ) { QValueList<KopeteLibraryInfo> l = loaded(); for ( QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i ) { KopetePlugin *tmp_plug = m_loadedPlugins[ ( *i ).specfile ]; if( tmp_plug->pluginId() == Id ) return tmp_plug; } return NULL; } QString LibraryLoader::pluginName( const KopetePlugin *plugin ) const { for( QDictIterator<KopetePlugin> i( m_loadedPlugins ); i.current(); ++i ) { if( i.current() == plugin ) return getInfo( i.currentKey() ).name; } return QString::fromLatin1( "ERROR: plugin unknown" ); } QString LibraryLoader::pluginIcon( const KopetePlugin *plugin ) const { for( QDictIterator<KopetePlugin> i( m_loadedPlugins ); i.current(); ++i ) { if( i.current() == plugin ) return getInfo( i.currentKey() ).icon; } return QString::fromLatin1( "ERROR: plugin unknown" ); } #include "pluginloader.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/directory.h" bool Directory::Open(const char* path, intptr_t* dir) { UNIMPLEMENTED(); return false; } bool Directory::Close(intptr_t dir) { UNIMPLEMENTED(); return false; } void Directory::List(intptr_t dir, bool recursive, Dart_Port dir_handler, Dart_Port file_handler, Dart_Port done_handler, Dart_Port dir_error_handler) { UNIMPLEMENTED(); } <commit_msg>Fix Windows build after directory library changes.<commit_after>// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/directory.h" bool Directory::Open(const char* path, intptr_t* dir) { UNIMPLEMENTED(); return false; } bool Directory::Close(intptr_t dir) { UNIMPLEMENTED(); return false; } void Directory::List(const char* path, intptr_t dir, bool recursive, Dart_Port dir_handler, Dart_Port file_handler, Dart_Port done_handler, Dart_Port dir_error_handler) { UNIMPLEMENTED(); } <|endoftext|>
<commit_before>#include <matrix.hpp> #include <catch.hpp> SCENARIO("matrix init without parametrs", "[init wp]") { Matrix matrix; REQUIRE(matrix.rows() == 4); REQUIRE(matrix.columns() == 4); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.mas[i][j] == 0); } } } SCENARIO("matrix init with parametrs", "[init withp]") { Matrix matrix(6,6); REQUIRE(matrix.rows() == 6); REQUIRE(matrix.columns() == 6); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.mas[i][j] == 0); } } } SCENARIO("matrix init copy", "[init copy]") { Matrix matrix(6,6); Matrix matrix1(matrix); REQUIRE(matrix1.rows() == matrix.rows()); REQUIRE(matrix1.columns() == matrix.columns()); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.mas[i][j] == matrix1.mas[i][j]); } } } SCENARIO("matrix fill", "[fill]") { Matrix matrix(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); REQUIRE(matrix.mas[0][0] == 1); REQUIRE(matrix.mas[0][1] == 2); REQUIRE(matrix.mas[1][0] == 3); REQUIRE(matrix.mas[1][1] == 4); } <commit_msg>Update init.cpp<commit_after>#include <matrix.hpp> #include <catch.hpp> SCENARIO("matrix init without parametrs", "[init wp]") { Matrix matrix; REQUIRE(matrix.rows() == 4); REQUIRE(matrix.columns() == 4); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix[i][j] == 0); } } } SCENARIO("matrix init with parametrs", "[init withp]") { Matrix matrix(6,6); REQUIRE(matrix.rows() == 6); REQUIRE(matrix.columns() == 6); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix[i][j] == 0); } } } SCENARIO("matrix init copy", "[init copy]") { Matrix matrix(6,6); Matrix matrix1(matrix); REQUIRE(matrix1.rows() == matrix.rows()); REQUIRE(matrix1.columns() == matrix.columns()); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix[i][j] == matrix1[i][j]); } } } SCENARIO("matrix fill", "[fill]") { Matrix matrix(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); REQUIRE(matrix[0][0] == 1); REQUIRE(matrix[0][1] == 2); REQUIRE(matrix[1][0] == 3); REQUIRE(matrix[1][1] == 4); } SCENARIO("matrix sum", "[sum]") { Matrix matrix(2,2); Matrix matrix1(2,2); <|endoftext|>
<commit_before>#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "coconfig.h" #if defined(_MSC_VER) #define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #include <Windows.h> #else #include <signal.h> #endif typedef int32_t (*test_func_t)(); extern int32_t test_simple (); extern int32_t test_factoral (); extern int32_t test_multiple (); extern int32_t test_allocator(); extern int32_t test_fpregs (); extern int32_t test_unchained(); extern int32_t test_yieldmain(); extern int32_t test_nesting (); extern int32_t test_params (); struct test_t { test_func_t func_; const char * name_; }; static test_t tests[] = { { test_simple, "test_simple" }, { test_factoral, "test_factoral" }, { test_multiple, "test_multiple" }, { test_allocator, "test_allocator" }, { test_fpregs, "test_fpregs" }, { test_unchained, "test_unchained" }, { test_yieldmain, "test_yieldmain" }, { test_nesting, "test_nesting" }, { test_params, "test_params" }, { nullptr, nullptr } }; static const char * test_name = ""; #if defined(_MSC_VER) static LONG CALLBACK segv_handler(PEXCEPTION_POINTERS info) { if (info->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) { printf("! fail '%s'\n", test_name); } else { printf("! crash '%s'\n", test_name); #if defined(_M_X64) printf(" pc @ 0x%016llx\n", info->ContextRecord->Rip); printf(" sp @ 0x%016llx\n", info->ContextRecord->Rsp); #else printf(" pc @ 0x%08lx\n", info->ContextRecord->Eip); printf(" sp @ 0x%08lx\n", info->ContextRecord->Esp); #endif } getchar(); exit(1); } static void setup() { // AddVectoredExceptionHandler(1, segv_handler); } #else static void segv_handler(int signal) { printf("! crash '%s'\n", test_name); exit(1); } static void sigtrap_handler(int signal) printf("! fail '%s'\n", test_name); exit(1); } static void setup() { signal(SIGSEGV, segv_handler); signal(SIGABRT, segv_handler); signal(SIGILL, segv_handler); signal(SIGINT, segv_handler); signal(SIGTRAP, sigtrap_handler); } #endif int main() { setup(); int32_t fails = 0; for (int32_t i = 0; tests[i].name_; i++) { test_t & test = tests[i]; test_name = test.name_; // run this specific test int32_t res = test.func_(); if (res >= 0) { printf(". pass '%s'\n", test.name_); } else { printf("! fail '%s' (%d)\n", test.name_, res); ++fails; } } getchar(); return fails; } <commit_msg>fix typo<commit_after>#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "coconfig.h" #if defined(_MSC_VER) #define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #include <Windows.h> #else #include <signal.h> #endif typedef int32_t (*test_func_t)(); extern int32_t test_simple (); extern int32_t test_factoral (); extern int32_t test_multiple (); extern int32_t test_allocator(); extern int32_t test_fpregs (); extern int32_t test_unchained(); extern int32_t test_yieldmain(); extern int32_t test_nesting (); extern int32_t test_params (); struct test_t { test_func_t func_; const char * name_; }; static test_t tests[] = { { test_simple, "test_simple" }, { test_factoral, "test_factoral" }, { test_multiple, "test_multiple" }, { test_allocator, "test_allocator" }, { test_fpregs, "test_fpregs" }, { test_unchained, "test_unchained" }, { test_yieldmain, "test_yieldmain" }, { test_nesting, "test_nesting" }, { test_params, "test_params" }, { nullptr, nullptr } }; static const char * test_name = ""; #if defined(_MSC_VER) static LONG CALLBACK segv_handler(PEXCEPTION_POINTERS info) { if (info->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) { printf("! fail '%s'\n", test_name); } else { printf("! crash '%s'\n", test_name); #if defined(_M_X64) printf(" pc @ 0x%016llx\n", info->ContextRecord->Rip); printf(" sp @ 0x%016llx\n", info->ContextRecord->Rsp); #else printf(" pc @ 0x%08lx\n", info->ContextRecord->Eip); printf(" sp @ 0x%08lx\n", info->ContextRecord->Esp); #endif } getchar(); exit(1); } static void setup() { // AddVectoredExceptionHandler(1, segv_handler); } #else static void segv_handler(int signal) { printf("! crash '%s'\n", test_name); exit(1); } static void sigtrap_handler(int signal) { printf("! fail '%s'\n", test_name); exit(1); } static void setup() { signal(SIGSEGV, segv_handler); signal(SIGABRT, segv_handler); signal(SIGILL, segv_handler); signal(SIGINT, segv_handler); signal(SIGTRAP, sigtrap_handler); } #endif int main() { setup(); int32_t fails = 0; for (int32_t i = 0; tests[i].name_; i++) { test_t & test = tests[i]; test_name = test.name_; // run this specific test int32_t res = test.func_(); if (res >= 0) { printf(". pass '%s'\n", test.name_); } else { printf("! fail '%s' (%d)\n", test.name_, res); ++fails; } } getchar(); return fails; } <|endoftext|>
<commit_before>#include "lest.hpp" #include "../twombly.hpp" #include <iostream> using namespace tw; #define RED 2 #define GREEN 1 #define BLUE 0 #define ALPHA 3 int opencv_error_handler(int status, const char* func_name, const char* err_msg, const char* file_name, int line, void*) { return 0; } const lest::test drawing_test[] = { CASE ( "Mat3b drawing" ) { Mat3b im(100, 100); auto d = draw(im); d.clear(255, 0, 0); EXPECT(im.at<Vec3b>(10, 10)[RED] == 255); EXPECT(im.at<Vec3b>(10, 10)[GREEN] == 0); EXPECT(im.at<Vec3b>(10, 10)[BLUE] == 0); }, CASE ( "Mat4b drawing" ) { Mat4b im(100, 100); auto d = draw(im); d.clear(255, 0, 0); EXPECT(im.at<Vec4b>(10, 10)[RED] == 255); EXPECT(im.at<Vec4b>(10, 10)[GREEN] == 0); EXPECT(im.at<Vec4b>(10, 10)[BLUE] == 0); EXPECT(im.at<Vec4b>(10, 10)[ALPHA] == 255); }, CASE ( "Mat3w drawing" ) { Mat3w im(100, 100); auto d = draw(im); d.clear(255, 0, 0); EXPECT(im.at<Vec3w>(10, 10)[RED] == 65535); EXPECT(im.at<Vec3w>(10, 10)[GREEN] == 0); EXPECT(im.at<Vec3w>(10, 10)[BLUE] == 0); }, CASE ( "Mat4w drawing" ) { Mat4w im(100, 100); auto d = draw(im); d.clear(255, 0, 0); EXPECT(im.at<Vec4w>(10, 10)[RED] == 65535); EXPECT(im.at<Vec4w>(10, 10)[GREEN] == 0); EXPECT(im.at<Vec4w>(10, 10)[BLUE] == 0); EXPECT(im.at<Vec4w>(10, 10)[ALPHA] == 65535); }, CASE ( "Path" ) { Mat3b im(500, 500); auto d = draw(im); d.preserve(true); d.new_path(); d.set_color(255, 255, 255); d.move_to(10, 10); d.line_to(490, 490); d.stroke(); int pathid = d.active_path(); EXPECT (d.total_vertices() == 2); double x, y; d.vertex(1, &x, &y); EXPECT(x == 490); EXPECT(y == 490); d.modify_vertex(1, 248, 249); d.vertex(1, &x, &y); EXPECT(x == 248); EXPECT(y == 249); d.new_path(); EXPECT (d.active_path() != pathid); EXPECT (d.active_path() > pathid); d.new_path(); d.line_width(2); d.ellipse(250, 250, 100, 100); d.stroke(); d.active_path(pathid); d.stroke(); d.preserve(false); #ifndef NO_SHOW try{ namedWindow("Path test"); imshow("Path test", im); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif }, CASE ( "Curve" ) { Mat3b im2(500, 500); im2.setTo(Scalar(255, 255, 255)); auto d = draw(im2); d.set_color(255, 0, 0); d.move_to(100, 100); d.curve_to(400, 400, 100, 320); d.stroke(); #ifndef NO_SHOW try { namedWindow("Curve test"); imshow("Curve test", im2); waitKey(0); } catch (std::exception &exc){ } #endif d.new_path(); d.clear(255, 255, 255); d.set_color(0, 255, 0); d.move_to(100, 100); d.curve_to(400, 400, 150, 320); d.stroke(); #ifndef NO_SHOW try{ imshow("Curve test", im2); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif }, CASE ( "Gradient" ) { Mat3w im2(500, 500); im2.setTo(Scalar(255, 255, 255)); auto d = draw(im2); d.set_color(255, 0, 0); d.move_to(100, 100); d.curve_to(400, 400, 100, 320); d.stroke(); d.new_path(); d.ellipse(250, 250, 250, 250); Gradient<Color16> g; g.add_stop(Color16(255<<8, 0, 0, 127<<8)); g.add_stop(Color16(0, 255<<8, 0, 127<<8)); g.add_stop(Color16(0, 0, 255<<8, 127<<8)); d.fill_gradient(g, 0, 300, gradient_type_y); EXPECT((im2.at<Scalar>(250, 250)[0] > 0)); #ifndef NO_SHOW try{ imshow("Gradient test", im2); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif }, CASE( "cairo-arc-infinite-loop"){ Mat3b im2(8, 8); auto d = draw(im2); d.clear(255, 255, 255); d.move_to(0, 0); d.arc_to(0, 0, 1, 1024 / DBL_EPSILON * M_PI, 0); d.arc_to(0, 0, 1, 0, 1024 / DBL_EPSILON * M_PI); d.set_color(255, 0, 0); d.stroke(); #ifndef NO_SHOW try{ imshow("infinte loop", im2); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif } }; int main(int argc, char **argv){ cv::redirectError(opencv_error_handler); lest::run(drawing_test, argc, argv); } <commit_msg>add more tests<commit_after>#include "lest.hpp" #include "../twombly.hpp" #include <iostream> using namespace tw; #define RED 2 #define GREEN 1 #define BLUE 0 #define ALPHA 3 int opencv_error_handler(int status, const char* func_name, const char* err_msg, const char* file_name, int line, void*) { return 0; } const lest::test drawing_test[] = { CASE ( "Mat3b drawing" ) { Mat3b im(100, 100); auto d = draw(im); d.clear(255, 0, 0); EXPECT(im.at<Vec3b>(10, 10)[RED] == 255); EXPECT(im.at<Vec3b>(10, 10)[GREEN] == 0); EXPECT(im.at<Vec3b>(10, 10)[BLUE] == 0); }, CASE ( "Mat4b drawing" ) { Mat4b im(100, 100); auto d = draw(im); d.clear(255, 0, 0); EXPECT(im.at<Vec4b>(10, 10)[RED] == 255); EXPECT(im.at<Vec4b>(10, 10)[GREEN] == 0); EXPECT(im.at<Vec4b>(10, 10)[BLUE] == 0); EXPECT(im.at<Vec4b>(10, 10)[ALPHA] == 255); }, CASE ( "Mat3w drawing" ) { Mat3w im(100, 100); auto d = draw(im); d.clear(255, 0, 0); EXPECT(im.at<Vec3w>(10, 10)[RED] == 65535); EXPECT(im.at<Vec3w>(10, 10)[GREEN] == 0); EXPECT(im.at<Vec3w>(10, 10)[BLUE] == 0); }, CASE ( "Mat4w drawing" ) { Mat4w im(100, 100); auto d = draw(im); d.clear(255, 0, 0); EXPECT(im.at<Vec4w>(10, 10)[RED] == 65535); EXPECT(im.at<Vec4w>(10, 10)[GREEN] == 0); EXPECT(im.at<Vec4w>(10, 10)[BLUE] == 0); EXPECT(im.at<Vec4w>(10, 10)[ALPHA] == 65535); }, CASE ( "Path" ) { Mat3b im(500, 500); auto d = draw(im); d.preserve(true); d.new_path(); d.set_color(255, 255, 255); d.move_to(10, 10); d.line_to(490, 490); d.stroke(); int pathid = d.active_path(); EXPECT (d.total_vertices() == 2); double x, y; d.vertex(1, &x, &y); EXPECT(x == 490); EXPECT(y == 490); d.modify_vertex(1, 248, 249); d.vertex(1, &x, &y); EXPECT(x == 248); EXPECT(y == 249); d.new_path(); EXPECT (d.active_path() != pathid); EXPECT (d.active_path() > pathid); d.new_path(); d.line_width(2); d.ellipse(250, 250, 100, 100); d.stroke(); d.active_path(pathid); d.stroke(); d.preserve(false); #ifndef NO_SHOW try{ namedWindow("Path test"); imshow("Path test", im); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif }, CASE ( "Curve" ) { Mat3b im2(500, 500); im2.setTo(Scalar(255, 255, 255)); auto d = draw(im2); d.set_color(255, 0, 0); d.move_to(100, 100); d.curve_to(400, 400, 100, 320); d.stroke(); #ifndef NO_SHOW try { namedWindow("Curve test"); imshow("Curve test", im2); waitKey(0); } catch (std::exception &exc){ } #endif d.new_path(); d.clear(255, 255, 255); d.set_color(0, 255, 0); d.move_to(100, 100); d.curve_to(400, 400, 150, 320); d.stroke(); #ifndef NO_SHOW try{ imshow("Curve test", im2); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif }, CASE ( "Gradient" ) { Mat3w im2(500, 500); im2.setTo(Scalar(255, 255, 255)); auto d = draw(im2); d.set_color(255, 0, 0); d.move_to(100, 100); d.curve_to(400, 400, 100, 320); d.stroke(); d.new_path(); d.ellipse(250, 250, 250, 250); Gradient<Color16> g; g.add_stop(Color16(255<<8, 0, 0, 127<<8)); g.add_stop(Color16(0, 255<<8, 0, 127<<8)); g.add_stop(Color16(0, 0, 255<<8, 127<<8)); d.fill_gradient(g, 0, 300, gradient_type_y); EXPECT((im2.at<Scalar>(250, 250)[0] > 0)); #ifndef NO_SHOW try{ imshow("Gradient test", im2); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif }, CASE("linear gradient many stops"){ Mat3b im2(800, 800); auto d = draw(im2); Gradient<Color> g; for(int i = 0; i < 255; i++){ g.add_stop(Color(i, 255-i, 255 * rand(), 255 * rand())); } d.rect(0, 0, 800, 800); d.fill_gradient(g, 0, 800, gradient_type_x); #ifndef NO_SHOW try{ imshow("Gradient test many stops", im2); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif }, CASE( "cairo-arc-infinite-loop"){ Mat3b im2(8, 8); auto d = draw(im2); d.clear(255, 255, 255); d.move_to(0, 0); d.arc_to(0, 0, 1, 1024 / DBL_EPSILON * M_PI, 0); d.arc_to(0, 0, 1, 0, 1024 / DBL_EPSILON * M_PI); d.set_color(255, 0, 0); d.stroke(); }, CASE( "mask"){ Mat4b im2(8, 8); auto d = draw(im2); d.antialias(false); d.alpha_mask_init(); d.rect(0, 0, 8, 8); d.set_color(255, 0, 0, 255); d.alpha_mask_get(5, 5) = 0; d.fill(); imwrite("test1.jpg", im2); EXPECT((int)(im2.at<Vec4b>(5, 5)[2]) < 255); EXPECT(((int)im2.at<Vec4b>(4, 4)[2]) == 255); }, CASE("Matrix rotation, scaling, translation, "){ int PAT_WIDTH = 120, PAT_HEIGHT = 120, PAD = 2; Mat4b im2(((PAT_WIDTH*2) + 8), ((PAT_WIDTH*2) + 8)); auto d = draw(im2); d.clear(0, 0, 0); d.translate(-PAT_WIDTH/2.0, -PAT_WIDTH/2.0); d.rotate(1.57079633); d.translate(PAT_WIDTH/2.0 + PAD, PAT_WIDTH/2.0-PAD); d.mtx.invert(); d.scale(2, 2); d.set_color(255, 0, 255, 127); d.rect(PAT_WIDTH/6.0, PAT_HEIGHT/6.0, PAT_WIDTH/6.0 + PAT_WIDTH/4.0, PAT_WIDTH/6.0 + PAT_HEIGHT/4.0); d.fill(); d.set_color (0, 255, 255, 127); d.rect(PAT_WIDTH/2.0, PAT_HEIGHT/2.0, PAT_WIDTH/2.0 + PAT_WIDTH/4.0, PAT_WIDTH/2.0 + PAT_HEIGHT/4.0); d.fill(); d.line_width(1); d.move_to(PAT_WIDTH/6.0, 0); d.line_to(0, 0); d.line_to(0, PAT_HEIGHT/6.0); d.set_color(255, 0, 0); d.stroke(); d.move_to(PAT_WIDTH/6.0, PAT_HEIGHT); d.line_to(0, PAT_HEIGHT); d.line_to(0, 5 * PAT_HEIGHT/6.0); d.set_color(0, 0, 255, 255); d.stroke(); d.move_to (5*PAT_WIDTH/6.0, 0); d.line_to (PAT_WIDTH, 0); d.line_to (PAT_WIDTH, PAT_HEIGHT/6.0); d.set_color (0, 0, 255, 255); d.stroke (); d.move_to (5*PAT_WIDTH/6.0, PAT_HEIGHT); d.line_to (PAT_WIDTH, PAT_HEIGHT); d.line_to (PAT_WIDTH, 5*PAT_HEIGHT/6.0); d.set_color (255, 255, 0, 255); d.stroke (); d.set_color (127, 127, 127); d.line_width (PAT_WIDTH/10.0); d.move_to (0, PAT_HEIGHT/4.0); d.line_to (PAT_WIDTH, PAT_HEIGHT/4.0); d.stroke (); d.move_to (PAT_WIDTH/4.0, 0); d.line_to (PAT_WIDTH/4.0, PAT_WIDTH); d.stroke (); #ifndef NO_SHOW try{ imshow("Test Matrix", im2); waitKey(0); destroyAllWindows(); } catch(std::exception &exc){ } #endif } }; int main(int argc, char **argv){ cv::redirectError(opencv_error_handler); lest::run(drawing_test, argc, argv); } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2013 Razor team * Authors: * Petr Vanek <petr@yarpen.cz> * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <QtDBus> #include "rzmountproviders.h" UDisks2Provider::UDisks2Provider(QObject *parent): RzMountProvider(parent) { QDBusConnection system = QDBusConnection::systemBus(); if (!system.isConnected()) { qDebug() << "UDisks2Provider::UDisks2Provider - not connected - " << mIsValid; return; } bool ret; ret = system.connect("org.freedesktop.UDisks2", "/org/freedesktop/UDisks2", "org.freedesktop.UDisks2", "InterfacesAdded", this, SLOT(dbusDeviceAdded(QDBusObjectPath,QVariantMap))); if (!ret) { qDebug() << "UDisks2Provider::UDisks2Provider InterfacesAdded connect failed"; return; } ret = system.connect("org.freedesktop.UDisks2", "/org/freedesktop/UDisks2", "org.freedesktop.UDisks2", "InterfacesRemoved", this, SLOT(dbusDeviceRemoved(QDBusObjectPath,QStringList))); if (!ret) { qDebug() << "UDisks2Provider::UDisks2Provider InterfacesRemoved connect failed"; return; } mIsValid = true; qDebug() << "UDisks2Provider::UDisks2Provider final validity" << mIsValid; } void UDisks2Provider::update() { qDebug() << "UDisks2Provider::update() called"; QList<QDBusObjectPath> paths; QDBusMessage call = QDBusMessage::createMethodCall("org.freedesktop.UDisks2", "/org/freedesktop/UDisks2/block_devices", "org.freedesktop.DBus.Introspectable", "Introspect"); QDBusPendingReply<QString> reply = QDBusConnection::systemBus().call(call); if (!reply.isValid()) { qWarning("UDisks2Manager: error: %s", qPrintable(reply.error().name())); return; } QXmlStreamReader xml(reply.value()); while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::StartElement && xml.name().toString() == "node" ) { QString name = xml.attributes().value("name").toString(); if(!name.isEmpty()) paths << QDBusObjectPath("/org/freedesktop/UDisks2/block_devices/" + name); } } foreach (QDBusObjectPath i, paths) { // qDebug() << "UDisks2Provider::update() path:" << i.path(); if (mDevicesByPath.contains(i.path())) dbusDeviceChanged(i); else dbusDeviceAdded(i, QVariantMap()); } // qDebug() << mDevicesByPath; } UDisks2MountDevice *UDisks2Provider::getDevice(const QDBusObjectPath &path) const { if (mDevicesByPath.contains(path.path())) return mDevicesByPath[path.path()]; else return 0; } void UDisks2Provider::addDevice(UDisks2MountDevice *device) { mDevicesByPath.insert(device->path().path(), device); mDevices.append(device); } void UDisks2Provider::delDevice(UDisks2MountDevice *device) { mDevices.removeAll(device); mDevicesByPath.remove(device->path().path()); device->deleteLater(); } void UDisks2Provider::dbusDeviceAdded(const QDBusObjectPath &path, const QVariantMap &) { if(path.path().startsWith("/org/freedesktop/UDisks2/jobs")) return; UDisks2MountDevice *device = new UDisks2MountDevice(path); addDevice(device); emit deviceAdded(device); } void UDisks2Provider::dbusDeviceRemoved(const QDBusObjectPath &path, const QStringList &) { if(path.path().startsWith("/org/freedesktop/UDisks2/jobs")) return; UDisks2MountDevice *device = getDevice(path); if (device) { emit deviceRemoved(device); delDevice(device); } } void UDisks2Provider::dbusDeviceChanged(const QDBusObjectPath &path) { #if 0 if(path.path().startsWith("/org/freedesktop/UDisks2/jobs")) return; UDisks2MountDevice *device = getDevice(path); if (!device) return; if (device->update()) emit deviceChanged(device); #endif } UDisks2MountDevice::UDisks2MountDevice(const QDBusObjectPath &path): RazorMountDevice(), mPath(path) { // qDebug() << "UDisks2MountDevice::UDisks2MountDevice path" << mPath.path(); mBlockIface = new QDBusInterface("org.freedesktop.UDisks2", mPath.path(), "org.freedesktop.UDisks2.Block", QDBusConnection::systemBus(), this); Q_ASSERT(mBlockIface); QDBusObjectPath drive_object = mBlockIface->property("Drive").value<QDBusObjectPath>(); // qDebug() << "UDisks2MountDevice::UDisks2MountDevice drive_object" << drive_object.path(); QDBusConnection::systemBus().connect("org.freedesktop.UDisks2", mPath.path(), "org.freedesktop.DBus.Properties","PropertiesChanged", this, SIGNAL(update())); mDriveIface = new QDBusInterface("org.freedesktop.UDisks2", drive_object.path(), "org.freedesktop.UDisks2.Drive", QDBusConnection::systemBus(), this); Q_ASSERT(mDriveIface); update(); } void UDisks2MountDevice::update() { bool res = false; res = setDevFile(mBlockIface->property("Device").toByteArray().data()) || res; res = setMediaType(calcMediaType()) || res; res = setLabel(calcLabel()) || res; res = setIsExternal(calcIsExternal()) || res; res = setIconName(calcIconName()) || res; QStringList mounts = mountPoints(); res = setIsMounted(mounts.count() != 0) || res; res = setIsEjectable(mDriveIface->property("Ejectable").toBool()); res = setSize(mBlockIface->property("Size").toULongLong()) || res; res = setVendor(mDriveIface->property("Vendor").toString()) || res; res = setModel(mDriveIface->property("Model").toString()) || res; res = setFileSystem(mBlockIface->property("IdType").toString()) || res; if (!mounts.empty()) res = setMountPath(mounts.first()) || res; if (res) emit changed(); } QStringList UDisks2MountDevice::mountPoints() const { QStringList points; QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.UDisks2", mPath.path(), "org.freedesktop.DBus.Properties", "Get"); QList<QVariant> args; args << "org.freedesktop.UDisks2.Filesystem" << "MountPoints"; message.setArguments(args); QDBusMessage reply = QDBusConnection::systemBus().call(message); QList<QByteArray> l; foreach (QVariant arg, reply.arguments()) arg.value<QDBusVariant>().variant().value<QDBusArgument>() >> l; foreach (QByteArray p, l) points.append(p); // qDebug() << "UDisks2MountDevice::mountPoints()" << points; return points; } RazorMountDevice::MediaType UDisks2MountDevice::calcMediaType() { if (mDriveIface->property("Optical").toBool()) return RazorMountDevice::MediaTypeOptical; const QString media = mDriveIface->property("Media").toString(); const QStringList mediaCompat = mDriveIface->property("MediaCompatibility").toStringList(); const QString idUsage = mBlockIface->property("IdUsage").toString(); // TODO/FIXME: how to get it from udisks2?! // if (mDbus->property("DeviceIsDrive").toBool()) // { // TODO/FIXME: just guessing... if (mediaCompat.contains("floppy")) return RazorMountDevice::MediaTypeFdd; if (idUsage == "filesystem") return RazorMountDevice::MediaTypeDrive; return RazorMountDevice::MediaTypeUnknown; // } // if (mDbus->property("DeviceIsPartition").toBool()) // { // if (idUsage == "filesystem") // return RazorMountDevice::MediaTypePartition; // return RazorMountDevice::MediaTypeUnknown; // } return RazorMountDevice::MediaTypeUnknown; } QString UDisks2MountDevice::calcLabel() { const QString idLabel = mBlockIface->property("IdLabel").toString(); if (mMediaType == MediaTypeFdd) return tr("Floppy drive"); if (mMediaType == MediaTypeOptical) return idLabel; const QString driveVendor = mDriveIface->property("Vendor").toString(); const QString driveModel = mDriveIface->property("Model").toString(); const qulonglong size = mBlockIface->property("Size").toULongLong(); QString label; if (!idLabel.isEmpty()) { label = idLabel; } else { if (!driveVendor.isEmpty()) label = driveVendor; if (!driveModel.isEmpty()) label += QString(" - %1").arg(driveModel); } if (label.isEmpty()) label = mDevFile; if (mSize) label += QString(" [%3]").arg(sizeToString(size)); return label; } bool UDisks2MountDevice::calcIsExternal() { // TODO/FIXME: I'm really unsure here... return mDriveIface->property("Removable").toBool(); } QString UDisks2MountDevice::calcIconName() { const QString media = mDriveIface->property( "Media" ).toString(); switch (mMediaType) { // .............................................. case MediaTypeDrive: case MediaTypePartition: { // handle drives const QString conn = mDriveIface->property( "ConnectionBus" ).toString(); if (conn == "usb") return "drive-removable-media-usb"; return "drive-removable-media"; } // .............................................. case MediaTypeFdd: { return "media-floppy"; } // .............................................. // case MediaTypeFlash: // { // if ( media == "flash_ms" ) // Flash & Co. // return "media-flash-memory-stick"; // if ( media == "flash_sd" || // media == "flash_sdhc" || // media == "flash_mmc" ) // return "media-flash-sd-mmc"; // if ( media == "flash_sm" ) // return "media-flash-smart-media"; // return "media-flash"; // } case MediaTypeOptical: { bool isWritable = mDriveIface->property( "OpticalBlank" ).toBool() // TODO/FIXME: how in udisks2? //|| // mDbus->property("OpticalDiscIsAppendable").toBool(); ; if (isWritable) return "media-optical-recordable"; if (media.startsWith("optical_dvd") || media.startsWith( "optical_hddvd")) // DVD return "media-optical-dvd"; if (media.startsWith("optical_bd")) // BluRay return "media-optical-blu-ray"; return "media-optical"; } case MediaTypeUnknown: { return "drive-harddisk"; } } return "drive-harddisk"; } void UDisks2MountDevice::dbusError(const QDBusError &err, const QDBusMessage &msg) { qWarning() << "UdisksInfo::mDbus_error" << err.message(); emit error(err.message()); } bool UDisks2MountDevice::mount() { #if 0 if (mIsMounted) return true; QList<QVariant> args; args << QVariant(QString()) << QVariant(QStringList()); bool ret; ret = mDbus->callWithCallback("FilesystemMount", args, this, //SLOT(dbusSuccess(QDBusMessage)), SIGNAL(mounted()), SLOT(dbusError(QDBusError, QDBusMessage))); QStringList paths = mDbus->property("DeviceMountPaths").toStringList(); if (!paths.empty()) mMountPath = paths.at(0); else mMountPath = ""; return ret; #endif } bool UDisks2MountDevice::unmount() { #if 0 if (!mIsMounted) return true; QList<QVariant> args; args << QVariant(QStringList()); bool ret; ret = mDbus->callWithCallback("FilesystemUnmount", args, this, // SLOT(dbusSuccess(QDBusMessage)), SIGNAL(unmounted()), SLOT(dbusError(QDBusError, QDBusMessage))); return ret; #endif } bool UDisks2MountDevice::eject() { #if 0 if (!mIsMounted) return false; QList<QVariant> args; args << QVariant(QStringList()); return mDbus->callWithCallback("DriveEject", args, this, SLOT(dbusSuccess(QDBusMessage)), SLOT(dbusError(QDBusError, QDBusMessage))); #endif } <commit_msg>Preventing compiler from complaining<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2013 Razor team * Authors: * Petr Vanek <petr@yarpen.cz> * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <QtDBus> #include "rzmountproviders.h" UDisks2Provider::UDisks2Provider(QObject *parent): RzMountProvider(parent) { QDBusConnection system = QDBusConnection::systemBus(); if (!system.isConnected()) { qDebug() << "UDisks2Provider::UDisks2Provider - not connected - " << mIsValid; return; } bool ret; ret = system.connect("org.freedesktop.UDisks2", "/org/freedesktop/UDisks2", "org.freedesktop.UDisks2", "InterfacesAdded", this, SLOT(dbusDeviceAdded(QDBusObjectPath,QVariantMap))); if (!ret) { qDebug() << "UDisks2Provider::UDisks2Provider InterfacesAdded connect failed"; return; } ret = system.connect("org.freedesktop.UDisks2", "/org/freedesktop/UDisks2", "org.freedesktop.UDisks2", "InterfacesRemoved", this, SLOT(dbusDeviceRemoved(QDBusObjectPath,QStringList))); if (!ret) { qDebug() << "UDisks2Provider::UDisks2Provider InterfacesRemoved connect failed"; return; } mIsValid = true; qDebug() << "UDisks2Provider::UDisks2Provider final validity" << mIsValid; } void UDisks2Provider::update() { qDebug() << "UDisks2Provider::update() called"; QList<QDBusObjectPath> paths; QDBusMessage call = QDBusMessage::createMethodCall("org.freedesktop.UDisks2", "/org/freedesktop/UDisks2/block_devices", "org.freedesktop.DBus.Introspectable", "Introspect"); QDBusPendingReply<QString> reply = QDBusConnection::systemBus().call(call); if (!reply.isValid()) { qWarning("UDisks2Manager: error: %s", qPrintable(reply.error().name())); return; } QXmlStreamReader xml(reply.value()); while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::StartElement && xml.name().toString() == "node" ) { QString name = xml.attributes().value("name").toString(); if(!name.isEmpty()) paths << QDBusObjectPath("/org/freedesktop/UDisks2/block_devices/" + name); } } foreach (QDBusObjectPath i, paths) { // qDebug() << "UDisks2Provider::update() path:" << i.path(); if (mDevicesByPath.contains(i.path())) dbusDeviceChanged(i); else dbusDeviceAdded(i, QVariantMap()); } // qDebug() << mDevicesByPath; } UDisks2MountDevice *UDisks2Provider::getDevice(const QDBusObjectPath &path) const { if (mDevicesByPath.contains(path.path())) return mDevicesByPath[path.path()]; else return 0; } void UDisks2Provider::addDevice(UDisks2MountDevice *device) { mDevicesByPath.insert(device->path().path(), device); mDevices.append(device); } void UDisks2Provider::delDevice(UDisks2MountDevice *device) { mDevices.removeAll(device); mDevicesByPath.remove(device->path().path()); device->deleteLater(); } void UDisks2Provider::dbusDeviceAdded(const QDBusObjectPath &path, const QVariantMap &) { if(path.path().startsWith("/org/freedesktop/UDisks2/jobs")) return; UDisks2MountDevice *device = new UDisks2MountDevice(path); addDevice(device); emit deviceAdded(device); } void UDisks2Provider::dbusDeviceRemoved(const QDBusObjectPath &path, const QStringList &) { if(path.path().startsWith("/org/freedesktop/UDisks2/jobs")) return; UDisks2MountDevice *device = getDevice(path); if (device) { emit deviceRemoved(device); delDevice(device); } } void UDisks2Provider::dbusDeviceChanged(const QDBusObjectPath &path) { #if 0 if(path.path().startsWith("/org/freedesktop/UDisks2/jobs")) return; UDisks2MountDevice *device = getDevice(path); if (!device) return; if (device->update()) emit deviceChanged(device); #endif } UDisks2MountDevice::UDisks2MountDevice(const QDBusObjectPath &path): RazorMountDevice(), mPath(path) { // qDebug() << "UDisks2MountDevice::UDisks2MountDevice path" << mPath.path(); mBlockIface = new QDBusInterface("org.freedesktop.UDisks2", mPath.path(), "org.freedesktop.UDisks2.Block", QDBusConnection::systemBus(), this); Q_ASSERT(mBlockIface); QDBusObjectPath drive_object = mBlockIface->property("Drive").value<QDBusObjectPath>(); // qDebug() << "UDisks2MountDevice::UDisks2MountDevice drive_object" << drive_object.path(); QDBusConnection::systemBus().connect("org.freedesktop.UDisks2", mPath.path(), "org.freedesktop.DBus.Properties","PropertiesChanged", this, SIGNAL(update())); mDriveIface = new QDBusInterface("org.freedesktop.UDisks2", drive_object.path(), "org.freedesktop.UDisks2.Drive", QDBusConnection::systemBus(), this); Q_ASSERT(mDriveIface); update(); } void UDisks2MountDevice::update() { bool res = false; res = setDevFile(mBlockIface->property("Device").toByteArray().data()) || res; res = setMediaType(calcMediaType()) || res; res = setLabel(calcLabel()) || res; res = setIsExternal(calcIsExternal()) || res; res = setIconName(calcIconName()) || res; QStringList mounts = mountPoints(); res = setIsMounted(mounts.count() != 0) || res; res = setIsEjectable(mDriveIface->property("Ejectable").toBool()); res = setSize(mBlockIface->property("Size").toULongLong()) || res; res = setVendor(mDriveIface->property("Vendor").toString()) || res; res = setModel(mDriveIface->property("Model").toString()) || res; res = setFileSystem(mBlockIface->property("IdType").toString()) || res; if (!mounts.empty()) res = setMountPath(mounts.first()) || res; if (res) emit changed(); } QStringList UDisks2MountDevice::mountPoints() const { QStringList points; QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.UDisks2", mPath.path(), "org.freedesktop.DBus.Properties", "Get"); QList<QVariant> args; args << "org.freedesktop.UDisks2.Filesystem" << "MountPoints"; message.setArguments(args); QDBusMessage reply = QDBusConnection::systemBus().call(message); QList<QByteArray> l; foreach (QVariant arg, reply.arguments()) arg.value<QDBusVariant>().variant().value<QDBusArgument>() >> l; foreach (QByteArray p, l) points.append(p); // qDebug() << "UDisks2MountDevice::mountPoints()" << points; return points; } RazorMountDevice::MediaType UDisks2MountDevice::calcMediaType() { if (mDriveIface->property("Optical").toBool()) return RazorMountDevice::MediaTypeOptical; const QString media = mDriveIface->property("Media").toString(); const QStringList mediaCompat = mDriveIface->property("MediaCompatibility").toStringList(); const QString idUsage = mBlockIface->property("IdUsage").toString(); // TODO/FIXME: how to get it from udisks2?! // if (mDbus->property("DeviceIsDrive").toBool()) // { // TODO/FIXME: just guessing... if (mediaCompat.contains("floppy")) return RazorMountDevice::MediaTypeFdd; if (idUsage == "filesystem") return RazorMountDevice::MediaTypeDrive; return RazorMountDevice::MediaTypeUnknown; // } // if (mDbus->property("DeviceIsPartition").toBool()) // { // if (idUsage == "filesystem") // return RazorMountDevice::MediaTypePartition; // return RazorMountDevice::MediaTypeUnknown; // } return RazorMountDevice::MediaTypeUnknown; } QString UDisks2MountDevice::calcLabel() { const QString idLabel = mBlockIface->property("IdLabel").toString(); if (mMediaType == MediaTypeFdd) return tr("Floppy drive"); if (mMediaType == MediaTypeOptical) return idLabel; const QString driveVendor = mDriveIface->property("Vendor").toString(); const QString driveModel = mDriveIface->property("Model").toString(); const qulonglong size = mBlockIface->property("Size").toULongLong(); QString label; if (!idLabel.isEmpty()) { label = idLabel; } else { if (!driveVendor.isEmpty()) label = driveVendor; if (!driveModel.isEmpty()) label += QString(" - %1").arg(driveModel); } if (label.isEmpty()) label = mDevFile; if (mSize) label += QString(" [%3]").arg(sizeToString(size)); return label; } bool UDisks2MountDevice::calcIsExternal() { // TODO/FIXME: I'm really unsure here... return mDriveIface->property("Removable").toBool(); } QString UDisks2MountDevice::calcIconName() { const QString media = mDriveIface->property( "Media" ).toString(); switch (mMediaType) { // .............................................. case MediaTypeDrive: case MediaTypePartition: { // handle drives const QString conn = mDriveIface->property( "ConnectionBus" ).toString(); if (conn == "usb") return "drive-removable-media-usb"; return "drive-removable-media"; } // .............................................. case MediaTypeFdd: { return "media-floppy"; } // .............................................. // case MediaTypeFlash: // { // if ( media == "flash_ms" ) // Flash & Co. // return "media-flash-memory-stick"; // if ( media == "flash_sd" || // media == "flash_sdhc" || // media == "flash_mmc" ) // return "media-flash-sd-mmc"; // if ( media == "flash_sm" ) // return "media-flash-smart-media"; // return "media-flash"; // } case MediaTypeOptical: { bool isWritable = mDriveIface->property( "OpticalBlank" ).toBool() // TODO/FIXME: how in udisks2? //|| // mDbus->property("OpticalDiscIsAppendable").toBool(); ; if (isWritable) return "media-optical-recordable"; if (media.startsWith("optical_dvd") || media.startsWith( "optical_hddvd")) // DVD return "media-optical-dvd"; if (media.startsWith("optical_bd")) // BluRay return "media-optical-blu-ray"; return "media-optical"; } case MediaTypeUnknown: { return "drive-harddisk"; } } return "drive-harddisk"; } void UDisks2MountDevice::dbusError(const QDBusError &err, const QDBusMessage &msg) { qWarning() << "UdisksInfo::mDbus_error" << err.message(); emit error(err.message()); } bool UDisks2MountDevice::mount() { #if 0 if (mIsMounted) return true; QList<QVariant> args; args << QVariant(QString()) << QVariant(QStringList()); bool ret; ret = mDbus->callWithCallback("FilesystemMount", args, this, //SLOT(dbusSuccess(QDBusMessage)), SIGNAL(mounted()), SLOT(dbusError(QDBusError, QDBusMessage))); QStringList paths = mDbus->property("DeviceMountPaths").toStringList(); if (!paths.empty()) mMountPath = paths.at(0); else mMountPath = ""; return ret; #else return false; #endif } bool UDisks2MountDevice::unmount() { #if 0 if (!mIsMounted) return true; QList<QVariant> args; args << QVariant(QStringList()); bool ret; ret = mDbus->callWithCallback("FilesystemUnmount", args, this, // SLOT(dbusSuccess(QDBusMessage)), SIGNAL(unmounted()), SLOT(dbusError(QDBusError, QDBusMessage))); return ret; #else return false; #endif } bool UDisks2MountDevice::eject() { #if 0 if (!mIsMounted) return false; QList<QVariant> args; args << QVariant(QStringList()); return mDbus->callWithCallback("DriveEject", args, this, SLOT(dbusSuccess(QDBusMessage)), SLOT(dbusError(QDBusError, QDBusMessage))); #else return false; #endif } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: process_impl.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-06-17 13:27:08 $ * * 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 _STRINGS_H #include <strings.h> #endif #ifndef _STDLIB_H #include <stdlib.h> #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _OSL_UUNXAPI_HXX_ #include "uunxapi.hxx" #endif #ifndef _OSL_FILE_PATH_HELPER_HXX_ #include "file_path_helper.hxx" #endif #include <string.h> //------------------------------------ // forward //------------------------------------ extern "C" sal_Char *getCmdLine(); extern "C" char* osl_impl_getExecutableName(char * buffer, size_t n); //------------------------------------ // private stuff //------------------------------------ namespace /* private */ { const rtl::OUString UNICHAR_SLASH = rtl::OUString::createFromAscii("/"); //------------------------------------------------------- // if the command line arg 0 contains a '/' somewhere it // has been probably invoked relatively to the current // working dir //------------------------------------------------------- inline bool is_relative_to_cwd(const rtl::OUString& path) { return (path.indexOf(UNICHAR_SLASH) > -1); } //--------------------------------------------------------- // make a relative path absolute using the current working // directory // no return value because osl_getExecutableFile either // returns osl_Process_E_None or osl_Process_E_Unknown //--------------------------------------------------------- void make_absolute_to_cwd(const rtl::OUString& relative_path, rtl::OUString& absolute_path) { rtl::OUString cwd_url; if (osl_Process_E_None == osl_getProcessWorkingDir(&cwd_url.pData)) { rtl::OUString cwd; #if OSL_DEBUG_LEVEL > 0 osl::FileBase::RC rc = #endif osl::FileBase::getSystemPathFromFileURL(cwd_url, cwd); OSL_ASSERT(osl::FileBase::E_None == rc); osl::systemPathMakeAbsolutePath(cwd, relative_path, absolute_path); } } //--------------------------------------------------------- // search for the file using the PATH environment variable // no return value because osl_getExecutableFile either // returns osl_Process_E_None or osl_Process_E_Unknown //--------------------------------------------------------- void find_in_PATH(const rtl::OUString& file_path, rtl::OUString& path_found) { rtl::OUString PATH = rtl::OUString::createFromAscii("PATH"); rtl::OUString env_path; if (osl_getEnvironment(PATH.pData, &env_path.pData) == osl_Process_E_None) osl::searchPath(file_path, env_path, path_found); } } // namespace /private */ /*************************************** osl_getExecutableFile **************************************/ oslProcessError SAL_CALL osl_getExecutableFile(rtl_uString** ppustrFile) { sal_Char* p_cmdline = getCmdLine(); oslProcessError osl_error = osl_Process_E_Unknown; if (p_cmdline != 0) { rtl::OUString cmdline(p_cmdline, (sal_Int32)(strlen(p_cmdline)), osl_getThreadTextEncoding()); free(p_cmdline); rtl::OUString abs_path; if (osl::systemPathIsRelativePath(cmdline)) { if (is_relative_to_cwd(cmdline)) make_absolute_to_cwd(cmdline, abs_path); else find_in_PATH(cmdline, abs_path); } else { abs_path = cmdline; } rtl::OUString path_resolved; if ((abs_path.getLength() > 0) && osl::realpath(abs_path, path_resolved)) { rtl::OUString furl; #if OSL_DEBUG_LEVEL > 0 osl::FileBase::RC rc = #endif osl::FileBase::getFileURLFromSystemPath(path_resolved.pData, furl); OSL_ASSERT(osl::FileBase::E_None == rc); rtl_uString_assign(ppustrFile, furl.pData); osl_error = osl_Process_E_None; } } return osl_error; } /*************************************** Necessary for signal.c **************************************/ char* osl_impl_getExecutableName(char * buffer, size_t n) { sal_Char* p_cmdline = getCmdLine(); char* pChrRet = NULL; if (p_cmdline != 0) { rtl::OUString cmdline(p_cmdline, (sal_Int32)(strlen(p_cmdline)), osl_getThreadTextEncoding()); free(p_cmdline); rtl::OUString exename_u; osl::systemPathGetFileNameOrLastDirectoryPart(cmdline, exename_u); rtl::OString exename_a = rtl::OUStringToOString(exename_u, osl_getThreadTextEncoding()); if (exename_a.getLength() < static_cast<int>(n)) { strcpy(buffer, exename_a.getStr()); pChrRet = buffer; } } return pChrRet; } <commit_msg>INTEGRATION: CWS tune04 (1.4.54); FILE MERGED 2004/06/10 12:20:17 cmc 1.4.54.1: #i29636# persistant UNICHAR_SLASH OUString obj can be a simple sal_Unicode<commit_after>/************************************************************************* * * $RCSfile: process_impl.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hjs $ $Date: 2004-06-25 17:14:34 $ * * 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 _STRINGS_H #include <strings.h> #endif #ifndef _STDLIB_H #include <stdlib.h> #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _OSL_UUNXAPI_HXX_ #include "uunxapi.hxx" #endif #ifndef _OSL_FILE_PATH_HELPER_HXX_ #include "file_path_helper.hxx" #endif #include <string.h> //------------------------------------ // forward //------------------------------------ extern "C" sal_Char *getCmdLine(); extern "C" char* osl_impl_getExecutableName(char * buffer, size_t n); //------------------------------------ // private stuff //------------------------------------ namespace /* private */ { const sal_Unicode UNICHAR_SLASH = ((sal_Unicode)'/'); //------------------------------------------------------- // if the command line arg 0 contains a '/' somewhere it // has been probably invoked relatively to the current // working dir //------------------------------------------------------- inline bool is_relative_to_cwd(const rtl::OUString& path) { return (path.indexOf(UNICHAR_SLASH) > -1); } //--------------------------------------------------------- // make a relative path absolute using the current working // directory // no return value because osl_getExecutableFile either // returns osl_Process_E_None or osl_Process_E_Unknown //--------------------------------------------------------- void make_absolute_to_cwd(const rtl::OUString& relative_path, rtl::OUString& absolute_path) { rtl::OUString cwd_url; if (osl_Process_E_None == osl_getProcessWorkingDir(&cwd_url.pData)) { rtl::OUString cwd; #if OSL_DEBUG_LEVEL > 0 osl::FileBase::RC rc = #endif osl::FileBase::getSystemPathFromFileURL(cwd_url, cwd); OSL_ASSERT(osl::FileBase::E_None == rc); osl::systemPathMakeAbsolutePath(cwd, relative_path, absolute_path); } } //--------------------------------------------------------- // search for the file using the PATH environment variable // no return value because osl_getExecutableFile either // returns osl_Process_E_None or osl_Process_E_Unknown //--------------------------------------------------------- void find_in_PATH(const rtl::OUString& file_path, rtl::OUString& path_found) { rtl::OUString PATH = rtl::OUString::createFromAscii("PATH"); rtl::OUString env_path; if (osl_getEnvironment(PATH.pData, &env_path.pData) == osl_Process_E_None) osl::searchPath(file_path, env_path, path_found); } } // namespace /private */ /*************************************** osl_getExecutableFile **************************************/ oslProcessError SAL_CALL osl_getExecutableFile(rtl_uString** ppustrFile) { sal_Char* p_cmdline = getCmdLine(); oslProcessError osl_error = osl_Process_E_Unknown; if (p_cmdline != 0) { rtl::OUString cmdline(p_cmdline, (sal_Int32)(strlen(p_cmdline)), osl_getThreadTextEncoding()); free(p_cmdline); rtl::OUString abs_path; if (osl::systemPathIsRelativePath(cmdline)) { if (is_relative_to_cwd(cmdline)) make_absolute_to_cwd(cmdline, abs_path); else find_in_PATH(cmdline, abs_path); } else { abs_path = cmdline; } rtl::OUString path_resolved; if ((abs_path.getLength() > 0) && osl::realpath(abs_path, path_resolved)) { rtl::OUString furl; #if OSL_DEBUG_LEVEL > 0 osl::FileBase::RC rc = #endif osl::FileBase::getFileURLFromSystemPath(path_resolved.pData, furl); OSL_ASSERT(osl::FileBase::E_None == rc); rtl_uString_assign(ppustrFile, furl.pData); osl_error = osl_Process_E_None; } } return osl_error; } /*************************************** Necessary for signal.c **************************************/ char* osl_impl_getExecutableName(char * buffer, size_t n) { sal_Char* p_cmdline = getCmdLine(); char* pChrRet = NULL; if (p_cmdline != 0) { rtl::OUString cmdline(p_cmdline, (sal_Int32)(strlen(p_cmdline)), osl_getThreadTextEncoding()); free(p_cmdline); rtl::OUString exename_u; osl::systemPathGetFileNameOrLastDirectoryPart(cmdline, exename_u); rtl::OString exename_a = rtl::OUStringToOString(exename_u, osl_getThreadTextEncoding()); if (exename_a.getLength() < static_cast<int>(n)) { strcpy(buffer, exename_a.getStr()); pChrRet = buffer; } } return pChrRet; } <|endoftext|>
<commit_before>#include "test.h" #include "../Source/Database.h" #include "../Source/Libs/SteamVdfParse.hpp" #include <QList> #include <QDir> #include <QFile> inline bool operator==(Game g1, Game g2) { return g1.id == g2.id && g1.gameName == g2.gameName && g1.gameDirectory == g2.gameDirectory && g1.executablePath == g2.executablePath && g1.arguments == g2.arguments ? true : false; } TEST_CASE ("Database", "[db]") { QFile file("ascensionTest.db"); if (file.exists()) { std::cout << "Removing" << std::endl; file.remove(); } Database db("ascensionTest.db"); Game testGame = {1, QString("Test Game"), QString("."), QString("test.exe"), QString("args")}; Game hl3 = {2, QString("Half-Life 3"), QString("."), QString("hl2.exe"), QString("")}; QList<Game> list; list << testGame << hl3; REQUIRE (db.init() == true); REQUIRE (db.addGame(QString("Test Game"), QString("."), QString("test.exe"), QString("args")) == true); REQUIRE (db.addGame(QString("Half-Life 3"), QString("."), QString("hl2.exe"), QString("")) == true); REQUIRE (db.getGameCount() == 2); REQUIRE (db.getGameById(1) == testGame); REQUIRE (db.getGames() == list); REQUIRE (db.removeGameById(1) == true); REQUIRE (db.removeGameById(1) == false); REQUIRE (db.removeGameByName("Half-Life 3") == true); REQUIRE (db.removeGameByName("Test Game") == false); REQUIRE (db.reset() == true); file.remove(); } TEST_CASE ("VDF Parser", "[vdf]") { std::unordered_map<int, SteamVdfParse::Game> map = SteamVdfParse::parseVdf("appinfo.vdf"); std::ifstream game("game", std::ios::binary); REQUIRE (SteamVdfParse::read32_le(game) == uint32_t(208050)); REQUIRE (SteamVdfParse::read64_le(game) == uint64_t(8589935831)); game.seekg(0, std::ios::beg); SteamVdfParse::Game gameTest = SteamVdfParse::parseGame(game); REQUIRE (gameTest.appID == 208050); REQUIRE (gameTest.size == 1239); REQUIRE (gameTest.infoState == 2); REQUIRE (gameTest.lastUpdated == 1436802448); REQUIRE (gameTest.accessToken == 0); REQUIRE (gameTest.changeNumber == 1127960); int codes[20] = {42, 74, 191, 28, 29, 82, 192, 217, 80, 82, 248, 202, 208, 235, 83, 1, 97, 130, 131, 196}; bool shaFlag = true; for (auto i=0;i<20;i++) { if (!int(gameTest.sha[i]) == codes[i]) { shaFlag = false; break; } } REQUIRE (shaFlag == true); } <commit_msg>Incorrect case<commit_after>#include "test.h" #include "../Source/Database.h" #include "../Source/Libs/SteamVdfParse.hpp" #include <QList> #include <QDir> #include <QFile> inline bool operator==(Game g1, Game g2) { return g1.id == g2.id && g1.gameName == g2.gameName && g1.gameDirectory == g2.gameDirectory && g1.executablePath == g2.executablePath && g1.arguments == g2.arguments ? true : false; } TEST_CASE ("Database", "[db]") { QFile file("ascensionTest.db"); if (file.exists()) { std::cout << "Removing" << std::endl; file.remove(); } Database db("ascensionTest.db"); Game testGame = {1, QString("Test Game"), QString("."), QString("test.exe"), QString("args")}; Game hl3 = {2, QString("Half-Life 3"), QString("."), QString("hl2.exe"), QString("")}; QList<Game> list; list << testGame << hl3; REQUIRE (db.init() == true); REQUIRE (db.addGame(QString("Test Game"), QString("."), QString("test.exe"), QString("args")) == true); REQUIRE (db.addGame(QString("Half-Life 3"), QString("."), QString("hl2.exe"), QString("")) == true); REQUIRE (db.getGameCount() == 2); REQUIRE (db.getGameById(1) == testGame); REQUIRE (db.getGames() == list); REQUIRE (db.removeGameById(1) == true); REQUIRE (db.removeGameById(1) == false); REQUIRE (db.removeGameByName("Half-Life 3") == true); REQUIRE (db.removeGameByName("Test Game") == true); REQUIRE (db.reset() == true); file.remove(); } TEST_CASE ("VDF Parser", "[vdf]") { std::unordered_map<int, SteamVdfParse::Game> map = SteamVdfParse::parseVdf("appinfo.vdf"); std::ifstream game("game", std::ios::binary); REQUIRE (SteamVdfParse::read32_le(game) == uint32_t(208050)); REQUIRE (SteamVdfParse::read64_le(game) == uint64_t(8589935831)); game.seekg(0, std::ios::beg); SteamVdfParse::Game gameTest = SteamVdfParse::parseGame(game); REQUIRE (gameTest.appID == 208050); REQUIRE (gameTest.size == 1239); REQUIRE (gameTest.infoState == 2); REQUIRE (gameTest.lastUpdated == 1436802448); REQUIRE (gameTest.accessToken == 0); REQUIRE (gameTest.changeNumber == 1127960); int codes[20] = {42, 74, 191, 28, 29, 82, 192, 217, 80, 82, 248, 202, 208, 235, 83, 1, 97, 130, 131, 196}; bool shaFlag = true; for (auto i=0;i<20;i++) { if (!int(gameTest.sha[i]) == codes[i]) { shaFlag = false; break; } } REQUIRE (shaFlag == true); } <|endoftext|>
<commit_before>#include "drape/overlay_tree.hpp" #include "drape/constants.hpp" #include "std/algorithm.hpp" #include "std/bind.hpp" namespace dp { int const kFrameUpdatePeriod = 10; int const kAverageHandlesCount[dp::OverlayRanksCount] = { 300, 200, 50 }; int const kInvalidFrame = -1; namespace { class HandleComparator { public: HandleComparator(bool enableMask, bool followingMode) : m_followingMode(followingMode) , m_enableMask(enableMask) {} bool operator()(ref_ptr<OverlayHandle> const & l, ref_ptr<OverlayHandle> const & r) const { return IsGreater(l, r); } bool IsGreater(ref_ptr<OverlayHandle> const & l, ref_ptr<OverlayHandle> const & r) const { uint64_t const mask = m_enableMask ? l->GetPriorityMask() & r->GetPriorityMask() : dp::kPriorityMaskAll; uint64_t const priorityLeft = (m_followingMode ? l->GetPriorityInFollowingMode() : l->GetPriority()) & mask; uint64_t const priorityRight = (m_followingMode ? r->GetPriorityInFollowingMode() : r->GetPriority()) & mask; if (priorityLeft > priorityRight) return true; if (priorityLeft == priorityRight) { auto const & hashLeft = l->GetFeatureID(); auto const & hashRight = r->GetFeatureID(); if (hashLeft < hashRight) return true; if (hashLeft == hashRight) return l.get() < r.get(); } return false; } private: bool m_followingMode; bool m_enableMask; }; } // namespace OverlayTree::OverlayTree() : m_frameCounter(kInvalidFrame) , m_followingMode(false) , m_isDisplacementEnabled(true) , m_displacementMode(displacement::kDefaultMode) { for (size_t i = 0; i < m_handles.size(); i++) m_handles[i].reserve(kAverageHandlesCount[i]); } bool OverlayTree::Frame() { if (IsNeedUpdate()) return true; m_frameCounter++; if (m_frameCounter >= kFrameUpdatePeriod) m_frameCounter = kInvalidFrame; return IsNeedUpdate(); } bool OverlayTree::IsNeedUpdate() const { return m_frameCounter == kInvalidFrame; } void OverlayTree::StartOverlayPlacing(ScreenBase const & screen) { ASSERT(IsNeedUpdate(), ()); Clear(); m_handlesCache.clear(); m_traits.m_modelView = screen; #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.clear(); #endif } void OverlayTree::Remove(ref_ptr<OverlayHandle> handle) { if (m_frameCounter == kInvalidFrame) return; if (m_handlesCache.find(handle) != m_handlesCache.end()) m_frameCounter = kInvalidFrame; } void OverlayTree::Add(ref_ptr<OverlayHandle> handle) { ASSERT(IsNeedUpdate(), ()); ScreenBase const & modelView = GetModelView(); handle->SetIsVisible(false); handle->SetCachingEnable(true); // Skip overlays from another displacement mode. if ((handle->GetDisplacementMode() & m_displacementMode) == 0) return; // Skip duplicates. if (m_handlesCache.find(handle) != m_handlesCache.end()) return; // Skip not-ready handles. if (!handle->Update(modelView)) return; // Clip handles which are out of screen. double const kScreenRectScale = 1.2; m2::RectD const pixelRect = handle->GetExtendedPixelRect(modelView); if (modelView.isPerspective()) { m2::RectD screenRect = modelView.PixelRectIn3d(); screenRect.Scale(kScreenRectScale); if (!screenRect.IsIntersect(pixelRect) || modelView.IsReverseProjection3d(pixelRect.Center())) { handle->SetIsVisible(false); return; } } else { m2::RectD screenRect = modelView.PixelRect(); screenRect.Scale(kScreenRectScale); if (!screenRect.IsIntersect(pixelRect)) { handle->SetIsVisible(false); return; } } int const rank = handle->GetOverlayRank(); ASSERT_LESS(rank, m_handles.size(), ()); m_handles[rank].emplace_back(handle); } void OverlayTree::InsertHandle(ref_ptr<OverlayHandle> handle, ref_ptr<OverlayHandle> const & parentOverlay) { ASSERT(IsNeedUpdate(), ()); #ifdef DEBUG_OVERLAYS_OUTPUT string str = handle->GetOverlayDebugInfo(); if (!str.empty()) LOG(LINFO, (str)); #endif ScreenBase const & modelView = GetModelView(); m2::RectD const pixelRect = handle->GetExtendedPixelRect(modelView); if (!m_isDisplacementEnabled) { m_handlesCache.insert(handle); TBase::Add(handle, pixelRect); return; } TOverlayContainer rivals; HandleComparator comparator(true /* enableMask */, m_followingMode); // Find elements that already on OverlayTree and it's pixel rect // intersect with handle pixel rect ("Intersected elements"). ForEachInRect(pixelRect, [&] (ref_ptr<OverlayHandle> const & h) { bool const isParent = (h == parentOverlay); if (!isParent && handle->IsIntersect(modelView, h)) rivals.push_back(h); }); // If handle is bound to its parent, parent's handle will be used. ref_ptr<OverlayHandle> handleToCompare = handle; bool const boundToParent = (parentOverlay != nullptr && handle->IsBound()); if (boundToParent) handleToCompare = parentOverlay; // In this loop we decide which element must be visible. // If input element "handle" more priority than all "Intersected elements" // than we remove all "Intersected elements" and insert input element "handle". // But if some of already inserted elements more priority than we don't insert "handle". for (auto const & rivalHandle : rivals) { bool rejectByDepth = false; if (modelView.isPerspective()) { bool const pathTextComparation = handle->HasDynamicAttributes() || rivalHandle->HasDynamicAttributes(); rejectByDepth = !pathTextComparation && handleToCompare->GetPivot(modelView, true).y > rivalHandle->GetPivot(modelView, true).y; } if (rejectByDepth || comparator.IsGreater(rivalHandle, handleToCompare)) { // Handle is displaced and bound to its parent, parent will be displaced too. if (boundToParent) { DeleteHandle(parentOverlay); #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("Displace (0):", handle->GetOverlayDebugInfo(), "->", parentOverlay->GetOverlayDebugInfo())); #endif #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.emplace_back(DisplacementData(handle->GetExtendedPixelRect(modelView).Center(), parentOverlay->GetExtendedPixelRect(modelView).Center(), dp::Color(0, 255, 0, 255))); #endif } #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("Displace (1):", rivalHandle->GetOverlayDebugInfo(), "->", handle->GetOverlayDebugInfo())); #endif #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.emplace_back(DisplacementData(rivalHandle->GetExtendedPixelRect(modelView).Center(), handle->GetExtendedPixelRect(modelView).Center(), dp::Color(0, 0, 255, 255))); #endif return; } } // Current overlay displaces other overlay, delete them. for (auto const & rivalHandle : rivals) { if (rivalHandle->IsBound()) { // Delete rival handle and all handles bound to it. for (auto it = m_handlesCache.begin(); it != m_handlesCache.end();) { if ((*it)->GetFeatureID() == rivalHandle->GetFeatureID()) { Erase(*it); #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("Displace (2):", handle->GetOverlayDebugInfo(), "->", (*it)->GetOverlayDebugInfo())); #endif #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.emplace_back(DisplacementData(handle->GetExtendedPixelRect(modelView).Center(), (*it)->GetExtendedPixelRect(modelView).Center(), dp::Color(0, 0, 255, 255))); #endif it = m_handlesCache.erase(it); } else { ++it; } } } else { DeleteHandle(rivalHandle); #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("Displace (3):", handle->GetOverlayDebugInfo(), "->", rivalHandle->GetOverlayDebugInfo())); #endif #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.emplace_back(DisplacementData(handle->GetExtendedPixelRect(modelView).Center(), rivalHandle->GetExtendedPixelRect(modelView).Center(), dp::Color(0, 0, 255, 255))); #endif } } m_handlesCache.insert(handle); TBase::Add(handle, pixelRect); } void OverlayTree::EndOverlayPlacing() { ASSERT(IsNeedUpdate(), ()); #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("- BEGIN OVERLAYS PLACING")); #endif HandleComparator comparator(false /* enableMask */, m_followingMode); for (int rank = 0; rank < dp::OverlayRanksCount; rank++) { sort(m_handles[rank].begin(), m_handles[rank].end(), comparator); for (auto const & handle : m_handles[rank]) { ref_ptr<OverlayHandle> parentOverlay; if (!CheckHandle(handle, rank, parentOverlay)) continue; InsertHandle(handle, parentOverlay); } m_handles[rank].clear(); } for (auto const & handle : m_handlesCache) { handle->SetIsVisible(true); handle->SetCachingEnable(false); } m_frameCounter = 0; #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("- END OVERLAYS PLACING")); #endif } bool OverlayTree::CheckHandle(ref_ptr<OverlayHandle> handle, int currentRank, ref_ptr<OverlayHandle> & parentOverlay) const { if (currentRank == dp::OverlayRank0) return true; int const seachingRank = currentRank - 1; for (auto const & h : m_handlesCache) { if (h->GetFeatureID() == handle->GetFeatureID() && h->GetOverlayRank() == seachingRank) { parentOverlay = h; return true; } } return false; } void OverlayTree::DeleteHandle(ref_ptr<OverlayHandle> const & handle) { size_t const deletedCount = m_handlesCache.erase(handle); ASSERT_NOT_EQUAL(deletedCount, 0, ()); if (deletedCount != 0) Erase(handle); } void OverlayTree::Select(m2::PointD const & glbPoint, TOverlayContainer & result) const { ScreenBase const & screen = m_traits.m_modelView; m2::PointD const pxPoint = screen.GtoP(glbPoint); double const kSearchRectHalfSize = 10.0; m2::RectD rect(pxPoint, pxPoint); rect.Inflate(kSearchRectHalfSize, kSearchRectHalfSize); for (auto const & handle : m_handlesCache) { if (rect.IsPointInside(handle->GetPivot(screen, false))) result.push_back(handle); } } void OverlayTree::Select(m2::RectD const & rect, TOverlayContainer & result) const { ScreenBase screen = m_traits.m_modelView; ForEachInRect(rect, [&](ref_ptr<OverlayHandle> const & h) { if (h->IsVisible() && h->GetFeatureID().IsValid()) { OverlayHandle::Rects shape; h->GetPixelShape(screen, screen.isPerspective(), shape); for (m2::RectF const & rShape : shape) { if (rShape.IsIntersect(m2::RectF(rect))) { result.push_back(h); break; } } } }); } void OverlayTree::SetFollowingMode(bool mode) { m_followingMode = mode; } void OverlayTree::SetDisplacementEnabled(bool enabled) { m_isDisplacementEnabled = enabled; m_frameCounter = kInvalidFrame; } void OverlayTree::SetDisplacementMode(int displacementMode) { m_displacementMode = displacementMode; m_frameCounter = kInvalidFrame; } #ifdef COLLECT_DISPLACEMENT_INFO OverlayTree::TDisplacementInfo const & OverlayTree::GetDisplacementInfo() const { return m_displacementInfo; } #endif } // namespace dp <commit_msg>Fixed false displacement in overlay tree<commit_after>#include "drape/overlay_tree.hpp" #include "drape/constants.hpp" #include "std/algorithm.hpp" #include "std/bind.hpp" namespace dp { int const kFrameUpdatePeriod = 10; int const kAverageHandlesCount[dp::OverlayRanksCount] = { 300, 200, 50 }; int const kInvalidFrame = -1; namespace { class HandleComparator { public: HandleComparator(bool enableMask, bool followingMode) : m_followingMode(followingMode) , m_enableMask(enableMask) {} bool operator()(ref_ptr<OverlayHandle> const & l, ref_ptr<OverlayHandle> const & r) const { return IsGreater(l, r); } bool IsGreater(ref_ptr<OverlayHandle> const & l, ref_ptr<OverlayHandle> const & r) const { uint64_t const mask = m_enableMask ? l->GetPriorityMask() & r->GetPriorityMask() : dp::kPriorityMaskAll; uint64_t const priorityLeft = (m_followingMode ? l->GetPriorityInFollowingMode() : l->GetPriority()) & mask; uint64_t const priorityRight = (m_followingMode ? r->GetPriorityInFollowingMode() : r->GetPriority()) & mask; if (priorityLeft > priorityRight) return true; if (priorityLeft == priorityRight) { auto const & hashLeft = l->GetFeatureID(); auto const & hashRight = r->GetFeatureID(); if (hashLeft < hashRight) return true; if (hashLeft == hashRight) return l.get() < r.get(); } return false; } private: bool m_followingMode; bool m_enableMask; }; } // namespace OverlayTree::OverlayTree() : m_frameCounter(kInvalidFrame) , m_followingMode(false) , m_isDisplacementEnabled(true) , m_displacementMode(displacement::kDefaultMode) { for (size_t i = 0; i < m_handles.size(); i++) m_handles[i].reserve(kAverageHandlesCount[i]); } bool OverlayTree::Frame() { if (IsNeedUpdate()) return true; m_frameCounter++; if (m_frameCounter >= kFrameUpdatePeriod) m_frameCounter = kInvalidFrame; return IsNeedUpdate(); } bool OverlayTree::IsNeedUpdate() const { return m_frameCounter == kInvalidFrame; } void OverlayTree::StartOverlayPlacing(ScreenBase const & screen) { ASSERT(IsNeedUpdate(), ()); Clear(); m_handlesCache.clear(); m_traits.m_modelView = screen; #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.clear(); #endif } void OverlayTree::Remove(ref_ptr<OverlayHandle> handle) { if (m_frameCounter == kInvalidFrame) return; if (m_handlesCache.find(handle) != m_handlesCache.end()) m_frameCounter = kInvalidFrame; } void OverlayTree::Add(ref_ptr<OverlayHandle> handle) { ASSERT(IsNeedUpdate(), ()); ScreenBase const & modelView = GetModelView(); handle->SetIsVisible(false); handle->SetCachingEnable(true); // Skip overlays from another displacement mode. if ((handle->GetDisplacementMode() & m_displacementMode) == 0) return; // Skip duplicates. if (m_handlesCache.find(handle) != m_handlesCache.end()) return; // Skip not-ready handles. if (!handle->Update(modelView)) return; // Clip handles which are out of screen. double const kScreenRectScale = 1.2; m2::RectD const pixelRect = handle->GetExtendedPixelRect(modelView); if (modelView.isPerspective()) { m2::RectD screenRect = modelView.PixelRectIn3d(); screenRect.Scale(kScreenRectScale); if (!screenRect.IsIntersect(pixelRect) || modelView.IsReverseProjection3d(pixelRect.Center())) { handle->SetIsVisible(false); return; } } else { m2::RectD screenRect = modelView.PixelRect(); screenRect.Scale(kScreenRectScale); if (!screenRect.IsIntersect(pixelRect)) { handle->SetIsVisible(false); return; } } int const rank = handle->GetOverlayRank(); ASSERT_LESS(rank, m_handles.size(), ()); m_handles[rank].emplace_back(handle); } void OverlayTree::InsertHandle(ref_ptr<OverlayHandle> handle, ref_ptr<OverlayHandle> const & parentOverlay) { ASSERT(IsNeedUpdate(), ()); #ifdef DEBUG_OVERLAYS_OUTPUT string str = handle->GetOverlayDebugInfo(); if (!str.empty()) LOG(LINFO, (str)); #endif ScreenBase const & modelView = GetModelView(); m2::RectD const pixelRect = handle->GetExtendedPixelRect(modelView); if (!m_isDisplacementEnabled) { m_handlesCache.insert(handle); TBase::Add(handle, pixelRect); return; } TOverlayContainer rivals; HandleComparator comparator(true /* enableMask */, m_followingMode); // Find elements that already on OverlayTree and it's pixel rect // intersect with handle pixel rect ("Intersected elements"). ForEachInRect(pixelRect, [&] (ref_ptr<OverlayHandle> const & h) { bool const isParent = (h == parentOverlay) || (h->GetFeatureID() == handle->GetFeatureID() && h->GetOverlayRank() < handle->GetOverlayRank()); if (!isParent && handle->IsIntersect(modelView, h)) rivals.push_back(h); }); // If handle is bound to its parent, parent's handle will be used. ref_ptr<OverlayHandle> handleToCompare = handle; bool const boundToParent = (parentOverlay != nullptr && handle->IsBound()); if (boundToParent) handleToCompare = parentOverlay; // In this loop we decide which element must be visible. // If input element "handle" more priority than all "Intersected elements" // than we remove all "Intersected elements" and insert input element "handle". // But if some of already inserted elements more priority than we don't insert "handle". for (auto const & rivalHandle : rivals) { bool rejectByDepth = false; if (modelView.isPerspective()) { bool const pathTextComparation = handle->HasDynamicAttributes() || rivalHandle->HasDynamicAttributes(); rejectByDepth = !pathTextComparation && handleToCompare->GetPivot(modelView, true).y > rivalHandle->GetPivot(modelView, true).y; } if (rejectByDepth || comparator.IsGreater(rivalHandle, handleToCompare)) { // Handle is displaced and bound to its parent, parent will be displaced too. if (boundToParent) { DeleteHandle(parentOverlay); #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("Displace (0):", handle->GetOverlayDebugInfo(), "->", parentOverlay->GetOverlayDebugInfo())); #endif #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.emplace_back(DisplacementData(handle->GetExtendedPixelRect(modelView).Center(), parentOverlay->GetExtendedPixelRect(modelView).Center(), dp::Color(0, 255, 0, 255))); #endif } #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("Displace (1):", rivalHandle->GetOverlayDebugInfo(), "->", handle->GetOverlayDebugInfo())); #endif #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.emplace_back(DisplacementData(rivalHandle->GetExtendedPixelRect(modelView).Center(), handle->GetExtendedPixelRect(modelView).Center(), dp::Color(0, 0, 255, 255))); #endif return; } } // Current overlay displaces other overlay, delete them. for (auto const & rivalHandle : rivals) { if (rivalHandle->IsBound()) { // Delete rival handle and all handles bound to it. for (auto it = m_handlesCache.begin(); it != m_handlesCache.end();) { if ((*it)->GetFeatureID() == rivalHandle->GetFeatureID()) { Erase(*it); #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("Displace (2):", handle->GetOverlayDebugInfo(), "->", (*it)->GetOverlayDebugInfo())); #endif #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.emplace_back(DisplacementData(handle->GetExtendedPixelRect(modelView).Center(), (*it)->GetExtendedPixelRect(modelView).Center(), dp::Color(0, 0, 255, 255))); #endif it = m_handlesCache.erase(it); } else { ++it; } } } else { DeleteHandle(rivalHandle); #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("Displace (3):", handle->GetOverlayDebugInfo(), "->", rivalHandle->GetOverlayDebugInfo())); #endif #ifdef COLLECT_DISPLACEMENT_INFO m_displacementInfo.emplace_back(DisplacementData(handle->GetExtendedPixelRect(modelView).Center(), rivalHandle->GetExtendedPixelRect(modelView).Center(), dp::Color(0, 0, 255, 255))); #endif } } m_handlesCache.insert(handle); TBase::Add(handle, pixelRect); } void OverlayTree::EndOverlayPlacing() { ASSERT(IsNeedUpdate(), ()); #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("- BEGIN OVERLAYS PLACING")); #endif HandleComparator comparator(false /* enableMask */, m_followingMode); for (int rank = 0; rank < dp::OverlayRanksCount; rank++) { sort(m_handles[rank].begin(), m_handles[rank].end(), comparator); for (auto const & handle : m_handles[rank]) { ref_ptr<OverlayHandle> parentOverlay; if (!CheckHandle(handle, rank, parentOverlay)) continue; InsertHandle(handle, parentOverlay); } } for (int rank = 0; rank < dp::OverlayRanksCount; rank++) m_handles[rank].clear(); for (auto const & handle : m_handlesCache) { handle->SetIsVisible(true); handle->SetCachingEnable(false); } m_frameCounter = 0; #ifdef DEBUG_OVERLAYS_OUTPUT LOG(LINFO, ("- END OVERLAYS PLACING")); #endif } bool OverlayTree::CheckHandle(ref_ptr<OverlayHandle> handle, int currentRank, ref_ptr<OverlayHandle> & parentOverlay) const { if (currentRank == dp::OverlayRank0) return true; int const seachingRank = currentRank - 1; for (auto const & h : m_handles[seachingRank]) { if (h->GetFeatureID() == handle->GetFeatureID() && m_handlesCache.find(h) != m_handlesCache.end()) { parentOverlay = h; return true; } } return false; } void OverlayTree::DeleteHandle(ref_ptr<OverlayHandle> const & handle) { size_t const deletedCount = m_handlesCache.erase(handle); ASSERT_NOT_EQUAL(deletedCount, 0, ()); if (deletedCount != 0) Erase(handle); } void OverlayTree::Select(m2::PointD const & glbPoint, TOverlayContainer & result) const { ScreenBase const & screen = m_traits.m_modelView; m2::PointD const pxPoint = screen.GtoP(glbPoint); double const kSearchRectHalfSize = 10.0; m2::RectD rect(pxPoint, pxPoint); rect.Inflate(kSearchRectHalfSize, kSearchRectHalfSize); for (auto const & handle : m_handlesCache) { if (rect.IsPointInside(handle->GetPivot(screen, false))) result.push_back(handle); } } void OverlayTree::Select(m2::RectD const & rect, TOverlayContainer & result) const { ScreenBase screen = m_traits.m_modelView; ForEachInRect(rect, [&](ref_ptr<OverlayHandle> const & h) { if (h->IsVisible() && h->GetFeatureID().IsValid()) { OverlayHandle::Rects shape; h->GetPixelShape(screen, screen.isPerspective(), shape); for (m2::RectF const & rShape : shape) { if (rShape.IsIntersect(m2::RectF(rect))) { result.push_back(h); break; } } } }); } void OverlayTree::SetFollowingMode(bool mode) { m_followingMode = mode; } void OverlayTree::SetDisplacementEnabled(bool enabled) { m_isDisplacementEnabled = enabled; m_frameCounter = kInvalidFrame; } void OverlayTree::SetDisplacementMode(int displacementMode) { m_displacementMode = displacementMode; m_frameCounter = kInvalidFrame; } #ifdef COLLECT_DISPLACEMENT_INFO OverlayTree::TDisplacementInfo const & OverlayTree::GetDisplacementInfo() const { return m_displacementInfo; } #endif } // namespace dp <|endoftext|>