text
string
size
int64
token_count
int64
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "itkProcessRegistrationDiffeomorphicDemons.h" #include "itkProcessRegistrationDiffeomorphicDemonsPlugin.h" #include "itkProcessRegistrationDiffeomorphicDemonsToolBox.h" #include <dtkLog/dtkLog.h> // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemonsPluginPrivate // ///////////////////////////////////////////////////////////////// class itkProcessRegistrationDiffeomorphicDemonsPluginPrivate { public: // Class variables go here. }; // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemonsPlugin // ///////////////////////////////////////////////////////////////// itkProcessRegistrationDiffeomorphicDemonsPlugin::itkProcessRegistrationDiffeomorphicDemonsPlugin(QObject *parent) : dtkPlugin(parent), d(new itkProcessRegistrationDiffeomorphicDemonsPluginPrivate) { } itkProcessRegistrationDiffeomorphicDemonsPlugin::~itkProcessRegistrationDiffeomorphicDemonsPlugin() { delete d; d = NULL; } bool itkProcessRegistrationDiffeomorphicDemonsPlugin::initialize() { if (!itkProcessRegistrationDiffeomorphicDemons::registered()) { dtkWarn() << "Unable to register itkProcessRegistrationDiffeomorphicDemons type"; } if (!itkProcessRegistrationDiffeomorphicDemonsToolBox::registered()) { dtkWarn() << "Unable to register itkProcessRegistrationDiffeomorphicDemons toolbox"; } return true; } bool itkProcessRegistrationDiffeomorphicDemonsPlugin::uninitialize() { return true; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::name() const { return "itkProcessRegistrationDiffeomorphicDemonsPlugin"; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::contact() const { return QString::fromUtf8("benoit.bleuze@inria.fr"); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::authors() const { QStringList list; list << QString::fromUtf8("Benoît Bleuzé"); return list; } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::contributors() const { QStringList list; list << "Vincent Garcia"; return list; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::description() const { return tr("Applies the diffeomorphic demons as they can be found in itk. Converts any type of image to float before applying the change, since the diffeomorphic demons only work on float images <br/> see: <a href=\"http://www.insight-journal.org/browse/publication/154\" > http://www.insight-journal.org/browse/publication/154 </a>"); } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::version() const { return ITKPROCESSREGISTRATIONDIFFEOMORPHICDEMONSPLUGIN_VERSION; } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::dependencies() const { return QStringList(); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::tags() const { return QStringList(); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::types() const { return QStringList() << "itkProcessRegistrationDiffeomorphicDemons"; } Q_EXPORT_PLUGIN2(itkProcessRegistrationDiffeomorphicDemonsPlugin, itkProcessRegistrationDiffeomorphicDemonsPlugin)
3,591
1,068
#ifndef _LEXTRIANGULATOR_HPP #define _LEXTRIANGULATOR_HPP #if USE_CUDA == 1 #include <cuda_runtime.h> #include <cublas_v2.h> #include <cublasLt.h> #endif #include "triangulator.hpp" class LexTriangulator : public Triangulator { public: LexTriangulator(double* x, const int n, const int d) : Triangulator(x, n, d){ #if USE_CUDA == 1 cublasStatus_t status; // Cublas Lt status = cublasLtCreate(&ltHandle); if (status != CUBLAS_STATUS_SUCCESS) { useCublas = false; } // Cublas Handle status = cublasCreate(&cblsHandle); cudaMalloc(reinterpret_cast<void **>(&d_x), sizeof(double)*n*d); cudaMemcpy(d_x, x, sizeof(double)*n*d, cudaMemcpyHostToDevice); #endif } ~LexTriangulator() { #if USE_CUDA == 1 cublasStatus_t status; if (scriptyH != nullptr) { cudaFreeHost(scriptyH); } status = cublasLtDestroy(ltHandle); status = cublasDestroy(cblsHandle); if (status != CUBLAS_STATUS_SUCCESS) { // TODO print error and raise exception } #else delete[] scriptyH; #endif } void computeTri() override; protected: #if USE_CUDA == 1 bool useCublas {true}; cublasLtHandle_t ltHandle; cublasHandle_t cblsHandle; double* d_x; double* d_D; #endif void extendTri(int yInd); void findNewHyp(int yInd); // Needed Memory TODO Determine if I can allocate most of this with std::vector. // The reason I couldn't is if I want to accelerate there parts with CUDA double *A; // 2*d*d int lenA; double *C; // n*n (for starters) int lenC; double *D; // n*n (for starters) int lenD; double *newHyp; // n*n (for starters) int lenHyp; double *S; // d int lenS; // May not need this since it will never change double *work; // 5*d int lenWork; // May not need this since it will never change }; #endif // _LEXTRIANGULATOR
2,174
729
#include "mainwindow.h" #include "ui_mainwindow.h" #include "textedit.h" #include "newconnectionwizard.h" #include "connectionmanager.h" #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery> #include <QSqlQueryModel> #include <QSqlRecord> #include <QSqlField> #include <QToolBar> #include <QAction> #include <QFileDialog> #include <QMessageBox> #include <QTreeWidgetItem> #include <QElapsedTimer> #include <QNetworkRequest> #include <QDateTime> #include <QList> #include <QUrl> #include <QCompleter> #include <QWizard> #include <QWizardPage> #include <QMenu> #include <QDomDocument> #include <QXmlStreamWriter> #include <QXmlStreamReader> #include <QFile> #include <QToolButton> #include <QXmlStreamReader> #include <QDir> #include <QTimer> #include <QProgressDialog> #include <QProcess> #include <QPropertyAnimation> #include <QDate> #include <QDebug> #include "defaults.h" // Driver not loaded // Access denied for user 'root'@'172.19.0.1' (using password: YES) // Unknown database 'retro_board' /** * @brief MainWindow::MainWindow * @param parent */ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QMainWindow::showMaximized(); connectionFactory = new ConnectionFactory(this); connectionInfoFactory = new ConnectionInfoFactory; connectionInfoFactory->setConnections(&connections); setWindowTitle(QString("%1").arg("Database Manager")); QIcon executeIcon(":/icons/ausfuehren_schatten.png"); ui->btnQueryExecute->setIcon(executeIcon); ui->queryResult->setSortingEnabled(true); ui->btnQuerySave->hide(); releaseNotesManager = new ReleaseNotesManager(this->ui->sideBarContainer, this->ui->sideBarLayout, parent); this->currentQueryRequests = new QMap<int, QString>; this->updateManager = new UpdateManager(this); this->ui->queryResult->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); /* QToolButton *tb = new QToolButton(); tb->setText("+"); // Add empty, not enabled tab to tabWidget ui->tabWidget->addTab(new QLabel("Add tabs by pressing \"+\""), QString()); ui->tabWidget->setTabEnabled(0, false); // Add tab button to current tab. Button will be enabled, but tab -- not ui->tabWidget->tabBar()->setTabButton(0, QTabBar::LeftSide, tb); */ ui->tabWidget->clear(); QIcon icon(":/icons/add_schatten.png"); ui->tabWidget->addTab(new QLabel(""), icon, QString("")); ui->tabWidget->setTabsClosable(true); ui->tabWidget->setMovable(false); auto tabBar = ui->tabWidget->tabBar(); tabBar->tabButton(0, QTabBar::RightSide)->hide(); newTab(); connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onChangeTab(int))); connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int))); ui->menuVerbinden->menuAction()->setVisible(false); ui->menuVerbinden->hideTearOffMenu(); loadConnectionInfos(); ui->databaseList->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->btnQueryExecute, SIGNAL(clicked(bool)), this, SLOT(onExecuteQueryClicked())); connect(ui->actionClose, SIGNAL(triggered(bool)), this, SLOT(close())); connect(ui->actionEditConnection, SIGNAL(triggered(bool)), this, SLOT(openConnectionManagerWindow())); connect(ui->actionNewConnection, SIGNAL(triggered(bool)), this, SLOT(openNewConnectionWindow())); connect(ui->menuVerbinden, SIGNAL(triggered(QAction*)), this, SLOT(onEstablishNewConnection(QAction*))); connect(&this->connections, SIGNAL(changed()), this, SLOT(createConnectionSubMenu())); connect(&this->connections, SIGNAL(changed()), this, SLOT(saveConnectionInfos())); connect(ui->btnQuerySave, SIGNAL(clicked()), this, SLOT(saveQuery())); connect(ui->btnQueryLoad, SIGNAL(clicked()), this, SLOT(loadQuery())); connect(ui->actionAboutDBManager, SIGNAL(triggered()), this, SLOT(showAboutText())); connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this->updateManager, SLOT(checkUpdateAvailable())); connect(ui->actionReleaseNotes, SIGNAL(triggered(bool)), this, SLOT(showReleaseNotes())); this->updateManager->checkUpdateAvailable(false); } void MainWindow::enableReleaseNotesButton() { QMenuBar* releaseNotesBar = new QMenuBar(ui->menuBar); QAction* releaseNotes = new QAction(QIcon(":/icons/release_notes.png"), ""); releaseNotesBar->addAction(releaseNotes); releaseNotesBar->setVisible(true); this->ui->menuBar->setCornerWidget(releaseNotesBar); connect(releaseNotes, SIGNAL(triggered()), this, SLOT(showReleaseNotes())); } void MainWindow::showReleaseNotes() { releaseNotesManager->toggle(); } void MainWindow::onChangeTab(int index) { // qDebug() << "OnChangeTab " << index; if (index == this->ui->tabWidget->count() - 1) { newTab(); } else { // this->currentTabIndex = index; this->handleChangedQueryRequest(); } } void MainWindow::closeTab(int index) { // qDebug() << "Tabs: " << this->ui->tabWidget->count(); // qDebug() << "Index: " << index; if (2 < this->ui->tabWidget->count() && index < (this->ui->tabWidget->count() - 1) ) { this->ui->tabWidget->removeTab(index); // this->currentTabIndex = this->currentTabIndex - 1; if (this->currentQueryRequests->contains(index)) { // this->currentQueryRequests->remove(this->currentTabIndex); this->currentQueryRequests->remove(ui->tabWidget->currentIndex()); } // reindex map QMap<int, QString>* newMap = new QMap<int, QString>(); QMapIterator<int, QString> mapIterator(*this->currentQueryRequests); int index = 0; while (mapIterator.hasNext()) { mapIterator.next(); (*newMap)[index] = mapIterator.value(); index++; } this->currentQueryRequests = newMap; } } void MainWindow::newTab() { int position = ui->tabWidget->count() - 1; TextEdit* textEdit = new TextEdit(dbConnection, this); if (nullptr != dbConnection && nullptr != dbConnection->getKeywords() ) { highlighter = new Highlighter(textEdit->document(), dbConnection->getKeywords()); } connect(textEdit, SIGNAL(textChanged()), this, SLOT(handleChangedQueryRequest())); ui->tabWidget->insertTab(position, textEdit, QString(tr("New tab"))); ui->tabWidget->setCurrentIndex(position); } void MainWindow::handleChangedQueryRequest() { // QString query = ui->queryRequest->toPlainText(); // TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->currentTabIndex)); TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex())); QString query = textEdit->toPlainText(); // if (!query.isEmpty() // && ((this->currentQueryRequests->contains(this->currentTabIndex) // && query != (*this->currentQueryRequests)[this->currentTabIndex]) // || false == this->currentQueryRequests->contains(this->currentTabIndex) // ) // ) { if (!query.isEmpty() && ((this->currentQueryRequests->contains(this->ui->tabWidget->currentIndex()) && query != (*this->currentQueryRequests)[this->ui->tabWidget->currentIndex()]) || false == this->currentQueryRequests->contains(this->ui->tabWidget->currentIndex()) ) ) { markAsUnsaved(true); showQuerySaveIcon(); } else { markAsUnsaved(isUnsaved()); hideQuerySaveIcon(); } } void MainWindow::showQuerySaveIcon() { ui->btnQuerySave->show(); } void MainWindow::hideQuerySaveIcon() { ui->btnQuerySave->hide(); } void MainWindow::saveQuery() { // TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->currentTabIndex)); TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex())); QString query = textEdit->toPlainText(); QString queryFileName = QFileDialog::getSaveFileName( this, tr("Save Current Query"), "", tr("Sql Files (*.sql);;All Files (*)") ); if (queryFileName.isEmpty()) { return; } else { // qDebug() << "Save in file: " << queryFileName; QFile file(queryFileName); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::information( this, tr("Unable to open file"), file.errorString() ); return; } QDataStream out(&file); out.setVersion(QDataStream::Qt_4_5); out << query; // (*this->currentQueryRequests)[this->currentTabIndex] = query; (*this->currentQueryRequests)[this->ui->tabWidget->currentIndex()] = query; this->markAsUnsaved(false); this->hideQuerySaveIcon(); } } void MainWindow::loadQuery() { QString queryFileName = QFileDialog::getOpenFileName( this, tr("Open Address Book"), "", tr("Sql Files (*.sql);;All Files (*)") ); if (queryFileName.isEmpty()) { return; } else { QFile file(queryFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::information( this, tr("Unable to open file"), file.errorString() ); return; } QString query; QDataStream in(&file); in.setVersion(QDataStream::Qt_4_5); in >> query; // (*this->currentQueryRequests)[this->currentTabIndex] = query; (*this->currentQueryRequests)[this->ui->tabWidget->currentIndex()] = query; hideQuerySaveIcon(); markAsUnsaved(false); // TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->currentTabIndex)); TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex())); textEdit->setText(query); } } void MainWindow::openNewConnectionWindow() { NewConnectionWizard wizard; if (wizard.exec()) { if (nullptr != dbConnection) { dbConnection->close(); } connectionInfo = connectionInfoFactory->create(wizard); storeConnectionInfo(connectionInfo); dbConnection = establishNewConnection(connectionInfo); saveConnectionInfos(); } } void MainWindow::openConnectionManagerWindow() { ConnectionManager manager(this, &connections); if (manager.exec()) { } } void MainWindow::createConnectionSubMenu() { ui->menuVerbinden->clear(); // QMapIterator<QString, QMap<QString, ConnectionInfo*> > typeIterator(connections); QMap<QString, QMap<QString, ConnectionInfo*>>::iterator typeIterator = connections.begin(); // while (typeIterator.hasNext()) { while(typeIterator != connections.end()) { // typeIterator.next(); QMenu* typeMenu = new QMenu(typeIterator.key()); QMapIterator<QString, ConnectionInfo*> connectionsIterator(typeIterator.value()); while(connectionsIterator.hasNext()) { connectionsIterator.next(); typeMenu->addAction(connectionsIterator.value()->getConnectionName()); } ui->menuVerbinden->addMenu(typeMenu); ++typeIterator; } if (0 < connections.size()) { ui->menuVerbinden->menuAction()->setVisible(true); } } void MainWindow::showResultTableContextMenu(const QPoint& point) { QMenu *menu=new QMenu(); // QAction copyAction(tr("copy"), this); QAction copyAction(QCoreApplication::tr("copy")); connect(&copyAction, SIGNAL(triggered()), dbConnection, SLOT(copyResultViewSelection())); menu->addAction(&copyAction); QAction deleteAction(tr("delete"), this); connect(&deleteAction, SIGNAL(triggered()), dbConnection, SLOT(deleteResultViewSelection())); menu->addAction(&deleteAction); QAction pasteAction(tr("paste"), this); connect(&pasteAction, SIGNAL(triggered()), dbConnection, SLOT(pasteToResultView())); menu->addAction(&pasteAction); QAction insertNullAction(tr("insert NULL")); connect(&insertNullAction, SIGNAL(triggered()), dbConnection, SLOT(insertNullToResultView())); menu->addAction(&insertNullAction); if (menu->exec(ui->queryResult->viewport()->mapToGlobal(point))) { // this->currentContextMenuItem = nullptr; } } void MainWindow::saveConnectionInfos() { QFile file("DBManager.xml"); file.open(QFile::ReadWrite); // delete all current content of file. file.resize(0); QXmlStreamWriter stream(&file); stream.setAutoFormatting(true); stream.writeStartDocument(); stream.writeStartElement("connections"); // QMapIterator<QString, QMap<QString, ConnectionInfo*> > typeIterator(connections); QMap<QString, QMap<QString, ConnectionInfo*>>::iterator typeIterator = connections.begin(); // while (typeIterator.hasNext()) { while(typeIterator != connections.end()) { // typeIterator.next(); QMapIterator<QString, ConnectionInfo*> connectionsIterator(typeIterator.value()); while(connectionsIterator.hasNext()) { connectionsIterator.next(); stream.writeStartElement("connection"); // stream.writeAttribute("href", "url"); if (!connectionsIterator.value()->getConnectionName().isEmpty() && !connectionsIterator.value()->isConnectionNameAutogenerated() ) { stream.writeTextElement("name", connectionsIterator.value()->getConnectionName()); } stream.writeTextElement("type", connectionsIterator.value()->getConnectionType()); if ("MYSQL" == connectionsIterator.value()->getConnectionType()) { if (!connectionsIterator.value()->getHost().isEmpty()) { stream.writeTextElement("host", connectionsIterator.value()->getHost()); } if (0 < connectionsIterator.value()->getPort()) { stream.writeTextElement("port", QString::number(connectionsIterator.value()->getPort())); } if (!connectionsIterator.value()->getUser().isEmpty()) { stream.writeTextElement("user", connectionsIterator.value()->getUser()); } if (!connectionsIterator.value()->getPassword().isEmpty()) { stream.writeTextElement("password", connectionsIterator.value()->getPassword()); } if (!connectionsIterator.value()->getDatabaseName().isEmpty()) { stream.writeTextElement("database", connectionsIterator.value()->getDatabaseName()); } } else if ("SQLITE" == connectionsIterator.value()->getConnectionType()) { stream.writeTextElement("databasePath", connectionsIterator.value()->getDatabasePath()); } stream.writeEndElement(); } ++typeIterator; } stream.writeEndElement(); stream.writeEndDocument(); file.close(); } void MainWindow::loadConnectionInfos() { QFile file("DBManager.xml"); if (!QFileInfo::exists("DBManager.xml")) { return; } file.open(QFile::ReadOnly | QFile::Text); QXmlStreamReader stream(&file); connections.clear(); while(!stream.atEnd() && !stream.hasError() ) { QXmlStreamReader::TokenType token = stream.readNext(); if (QXmlStreamReader::StartElement == token && "connection" == stream.name() ) { ConnectionInfo* connectionInfo = connectionInfoFactory->create(stream); connections.insert(connectionInfo); // connections[connectionInfo->getConnectionType()][connectionInfo->getConnectionName()] = connectionInfo; } } createConnectionSubMenu(); file.close(); emit connections.changed(); } void MainWindow::storeConnectionInfo(ConnectionInfo* connectionInfo) { connections.insert(connectionInfo); connectionsSaved = false; emit connections.changed(); } void MainWindow::onEstablishNewConnection(QAction *action) { QWidget* widget = action->parentWidget(); if (widget) { QMenu* menu = dynamic_cast<QMenu* >(widget); establishNewConnection(connections[menu->title()][action->text()]); } } Connection* MainWindow::establishNewConnection(ConnectionInfo* connectionInfo) { dbConnection = connectionFactory->create(connectionInfo); connect(dbConnection, SIGNAL(connectionError(QString)), this, SLOT(handleConnectionError(QString))); connect(ui->databaseList, SIGNAL(customContextMenuRequested(const QPoint&)), this->dbConnection, SLOT(showDatabaseContextMenu(const QPoint&))); ui->queryResult->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->queryResult, SIGNAL(customContextMenuRequested(QPoint)), this->dbConnection, SLOT(showResultTableContextMenu(QPoint))); connect(ui->btnAddNewRow, SIGNAL(clicked()), this->dbConnection, SLOT(addNewRow())); connect(ui->btnQueryResultSave, SIGNAL(clicked()), this->dbConnection, SLOT(saveQueryResultChanges())); connect(ui->btnQueryResultCancel, SIGNAL(clicked()), this->dbConnection, SLOT(cancelQueryResultChanges())); dbConnection->setDatabaseListView(ui->databaseList); dbConnection->setQueryResultView(ui->queryResult); // dbConnection->setQueryRequestView(qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex()))); dbConnection->setInformationView(ui->information); dbConnection->loadDatabaseList(); if (nullptr != dbConnection && nullptr != dbConnection->getKeywords() ) { TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex())); highlighter = new Highlighter(textEdit->document(), dbConnection->getKeywords()); textEdit->setConnection(dbConnection); } if ("SQLITE" == connectionInfo->getConnectionType()) { setWindowTitle(QString("%1 - %2").arg(connectionInfo->getDatabaseName()).arg("Database Manager")); } else { setWindowTitle(QString("%1@%2 - %3").arg(Defaults::Resolver::resolve("user", connectionInfo->getUser())).arg(connectionInfo->getHost()).arg("Database Manager")); } return dbConnection; } void MainWindow::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Return && event->modifiers() == Qt::ControlModifier) { this->onExecuteQueryClicked(); } } void MainWindow::handleConnectionError(QString errorMessage) { this->ui->information->append(errorMessage); } void MainWindow::onExecuteQueryClicked() { /* // qDebug() << "Current Tab Index von QTabWidget::currentIndex: " << ui->tabWidget->currentIndex(); TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(ui->tabWidget->currentIndex())); // qDebug() << "MainWindow::onExecuteQueryClicked textEdit: " << textEdit; QString queryString = textEdit->toPlainText(); // QString queryString = ui->queryRequest->toPlainText(); if (nullptr == dbConnection) { this->ui->information->append(tr("No Connection established!")); return; } QSqlQuery query = dbConnection->sendQuery(queryString); QStandardItemModel* queryResultModel = new QStandardItemModel; if (query.isActive()) { QSqlRecord localRecord = query.record(); // qDebug() << "Local Record: " << localRecord; for (int currentPos = 0; currentPos < localRecord.count(); ++currentPos) { QStandardItem* headerItem = new QStandardItem(localRecord.fieldName(currentPos)); queryResultModel->setHorizontalHeaderItem(currentPos, headerItem); } query.seek(-1); int currentRow = 0; while (query.next()) { QSqlRecord currentRecord = query.record(); for (int currentColumn = 0; currentColumn < currentRecord.count(); ++currentColumn) { QStandardItem* value = new QStandardItem(currentRecord.field(currentColumn).value().toString()); queryResultModel->setItem(currentRow, currentColumn, value); } ++currentRow; } } ui->queryResult->setModel(queryResultModel); ui->queryResult->resizeColumnsToContents(); statusBar()->showMessage(tr("connected!")); */ TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(ui->tabWidget->currentIndex())); QString queryString = textEdit->toPlainText(); if (nullptr == dbConnection) { this->ui->information->append(tr("No Connection established!")); return; } QSqlQuery query = dbConnection->sendQuery(queryString); QSqlQueryModel* queryResultModel = new QSqlQueryModel; queryResultModel->setQuery(query); ui->queryResult->setVisible(false); ui->queryResult->setModel(queryResultModel); // ui->queryResult->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->queryResult->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); ui->queryResult->resizeColumnsToContents(); ui->queryResult->setVisible(true); } void MainWindow::onQueryResultHeaderClicked(QStandardItem* item) { } /** Public slot to get unsaved state for global application. * @brief MainWindow::markAsUnsaved * @param unsaved */ void MainWindow::markAsUnsaved(bool unsaved) { this->setUnsaved(unsaved); } bool MainWindow::isUnsaved() const { return unsaved; } void MainWindow::setUnsaved(const bool unsaved) { this->unsaved = unsaved; } void MainWindow::showAboutText() { QMessageBox messageBox(this); messageBox.setIcon(QMessageBox::Icon::Information); messageBox.setWindowTitle(tr("DBManager - about")); messageBox.setTextFormat(Qt::RichText); messageBox.setText(tr("DBManager in version %1.<br />This Program is Freeware and OpenSource.").arg(Application::BuildNo)); messageBox.setInformativeText(tr("Future information and Projects under <a href='https://www.byte-artist.de'>www.byte-artist.de</a><br /><br />Found issues can tracked here: <a href='https://bitbucket.org/mastercad/dbmanager/issues'>DBManager Issue Tracker</a>")); messageBox.exec(); } MainWindow::~MainWindow() { delete currentQueryRequests; delete updateManager; delete ui; }
22,393
6,449
#include <maya/MPxLocatorNode.h> #include <maya/MString.h> #include <maya/MTypeId.h> #include <maya/MPlug.h> #include <maya/MVector.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MColor.h> #include <maya/M3dView.h> #include <maya/MFnEnumAttribute.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnMessageAttribute.h> #include "sunflowHelperNode.h" #if defined(OSMac_MachO_) #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif MTypeId sunflowHelperNode::id( 0x00114156 ); MObject sunflowHelperNode::aHelperType; MObject sunflowHelperNode::aHelperColor; MObject sunflowHelperNode::aHelperOpacity; MObject sunflowHelperNode::aMeshPath; MObject sunflowHelperNode::aShaderNode; void* sunflowHelperNode::creator() { return new sunflowHelperNode; } MStatus sunflowHelperNode::initialize() { MFnEnumAttribute eAttr; MFnNumericAttribute numAttr; MFnTypedAttribute tAttr; MFnMessageAttribute shaderAttr; MStatus status; aHelperType = eAttr.create( "type", "t", 0, &status ); eAttr.addField( "File Mesh", 0 ); eAttr.addField( "Infinite Plane", 1 ); CHECK_MSTATUS(eAttr.setKeyable(true)); CHECK_MSTATUS(eAttr.setStorable(true)); CHECK_MSTATUS(eAttr.setReadable(true)); CHECK_MSTATUS(eAttr.setWritable(true)); CHECK_MSTATUS(eAttr.setConnectable(false)); CHECK_MSTATUS( addAttribute( aHelperType ) ); aHelperColor = numAttr.createColor( "helperColor", "hc", &status ); CHECK_MSTATUS(numAttr.setKeyable(true)); CHECK_MSTATUS(numAttr.setStorable(true)); CHECK_MSTATUS(numAttr.setReadable(true)); CHECK_MSTATUS(numAttr.setWritable(true)); CHECK_MSTATUS( numAttr.setMin( 0.0, 0.0, 0.0 ) ); CHECK_MSTATUS( numAttr.setMax( 1.0, 1.0, 1.0 ) ); CHECK_MSTATUS( numAttr.setDefault( 0.0, 0.0, 0.5) ); CHECK_MSTATUS( addAttribute( aHelperColor ) ); aHelperOpacity = numAttr.create( "helperOpacity", "ho", MFnNumericData::kFloat, 0.0, &status ); CHECK_MSTATUS(numAttr.setKeyable(true)); CHECK_MSTATUS(numAttr.setStorable(true)); CHECK_MSTATUS(numAttr.setReadable(true)); CHECK_MSTATUS(numAttr.setWritable(true)); CHECK_MSTATUS( numAttr.setMin( 0.0 ) ); CHECK_MSTATUS( numAttr.setMax( 1.0 ) ); CHECK_MSTATUS( addAttribute( aHelperOpacity ) ); aMeshPath = tAttr.create(MString("meshPath"), MString("mp"), MFnData::kString, aMeshPath, &status ); CHECK_MSTATUS( addAttribute (aMeshPath) ); aShaderNode = shaderAttr.create( "shaderNode", "sn", &status ); CHECK_MSTATUS( addAttribute (aShaderNode) ); return MS::kSuccess; } MStatus sunflowHelperNode::compute( const MPlug& /* plug */, MDataBlock& /* data */ ) { return MS::kUnknownParameter; } void sunflowHelperNode::draw( M3dView & view, const MDagPath & /*path*/, M3dView::DisplayStyle /*displayStyle*/, M3dView::DisplayStatus displaystatus ) { // Get the type // MObject thisNode = thisMObject(); MPlug typePlug( thisNode, aHelperType ); CHECK_MSTATUS(typePlug.getValue( m_helperType )); MPlug colorPlug( thisNode, aHelperColor ); CHECK_MSTATUS(colorPlug.child(0).getValue( m_helperColor.r )); CHECK_MSTATUS(colorPlug.child(1).getValue( m_helperColor.g )); CHECK_MSTATUS(colorPlug.child(2).getValue( m_helperColor.b )); MPlug opacityPlug( thisNode, aHelperOpacity ); CHECK_MSTATUS(opacityPlug.getValue( m_helperColor.a )); view.beginGL(); // Draw the arrows // /* glPushAttrib( GL_ALL_ATTRIB_BITS ); glBegin( GL_LINES ); glColor4f( 1.0f, 0.0f, 0.0f, 1.0f ); glVertex3f( 0.00f, 0.00f, 0.00f ); glVertex3f( 0.50f, 0.00f, 0.00f ); glVertex3f( 0.50f, 0.00f, 0.00f ); glVertex3f( 0.40f, -0.05f, 0.00f ); glVertex3f( 0.40f, -0.05f, 0.00f ); glVertex3f( 0.40f, 0.00f, 0.00f ); glColor4f( 0.0f, 1.0f, 0.0f, 1.0f ); glVertex3f( 0.00f, 0.00f, 0.00f ); glVertex3f( 0.00f, 0.50f, 0.00f ); glVertex3f( 0.00f, 0.50f, 0.00f ); glVertex3f( 0.05f, 0.40f, 0.00f ); glVertex3f( 0.05f, 0.40f, 0.00f ); glVertex3f( 0.00f, 0.40f, 0.00f ); glColor4f( 0.0f, 0.0f, 1.0f, 1.0f ); glVertex3f( 0.00f, 0.00f, 0.00f ); glVertex3f( 0.00f, 0.00f, 0.50f ); glVertex3f( 0.00f, 0.00f, 0.50f ); glVertex3f( 0.00f, -0.05f, 0.40f ); glVertex3f( 0.00f, -0.05f, 0.40f ); glVertex3f( 0.00f, 0.00f, 0.40f ); glEnd(); glPopAttrib(); */ // draw the warious primitives // switch( m_helperType ) { case 0: // CUBE glPushAttrib( GL_ALL_ATTRIB_BITS ); if ( displaystatus == M3dView::kDormant ) glColor4f( m_helperColor.r, m_helperColor.g, m_helperColor.b, 1.0f ); glBegin( GL_LINES ); glVertex3f( -0.50f, 0.50f, -0.50f ); glVertex3f( 0.50f, 0.50f, -0.50f ); glVertex3f( 0.50f, 0.50f, -0.50f ); glVertex3f( 0.50f, 0.50f, 0.50f ); glVertex3f( 0.50f, 0.50f, 0.50f ); glVertex3f( -0.50f, 0.50f, 0.50f ); glVertex3f( -0.50f, 0.50f, 0.50f ); glVertex3f( -0.50f, 0.50f, -0.50f ); glVertex3f( -0.50f, -0.50f, -0.50f ); glVertex3f( 0.50f, -0.50f, -0.50f ); glVertex3f( 0.50f, -0.50f, -0.50f ); glVertex3f( 0.50f, -0.50f, 0.50f ); glVertex3f( 0.50f, -0.50f, 0.50f ); glVertex3f( -0.50f, -0.50f, 0.50f ); glVertex3f( -0.50f, -0.50f, 0.50f ); glVertex3f( -0.50f, -0.50f, -0.50f ); glVertex3f( -0.50f, 0.50f, -0.50f ); glVertex3f( -0.50f, -0.50f, -0.50f ); glVertex3f( 0.50f, 0.50f, -0.50f ); glVertex3f( 0.50f, -0.50f, -0.50f ); glVertex3f( 0.50f, 0.50f, 0.50f ); glVertex3f( 0.50f, -0.50f, 0.50f ); glVertex3f( -0.50f, 0.50f, 0.50f ); glVertex3f( -0.50f, -0.50f, 0.50f ); glEnd(); glPopAttrib(); break; case 1: // CLIPPING PLANE // Extra OpenGL stuff disabled for now - there seems to be a problem on Linux with Nvidia drivers (glPushAttrib/glPopAttrib not respected?) // glPushAttrib( GL_ALL_ATTRIB_BITS ); // // glEnable( GL_LINE_STIPPLE); // glLineStipple(1,0xff); // if ( displaystatus == M3dView::kDormant ) glColor4f( m_helperColor.r, m_helperColor.g, m_helperColor.b, 1.0f ); glBegin( GL_LINES ); glVertex3f( -1.0f, 0.0f, 1.0f ); glVertex3f( 1.0f, 0.0f, 1.0f ); glVertex3f( 1.0f, 0.0f, 1.0f ); glVertex3f( 1.0f, 0.0f, -1.0f ); glVertex3f( 1.0f, 0.0f, -1.0f ); glVertex3f( -1.0f, 0.0f, -1.0f ); glVertex3f( -1.0f, 0.0f, -1.0f ); glVertex3f( -1.0f, 0.0f, 1.0f ); glVertex3f( -1.0f, 0.0f, 1.0f ); glVertex3f( 1.0f, 0.0f, -1.0f ); glVertex3f( 1.0f, 0.0f, 1.0f ); glVertex3f( -1.0f, 0.0f, -1.0f ); glEnd(); // glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glEnable(GL_ALPHA_TEST); // glAlphaFunc(GL_ALWAYS ,0.1); // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glEnable(GL_DEPTH_TEST); // glDepthFunc(GL_LEQUAL); // glDepthMask( GL_FALSE ); // glColor4f( m_helperColor.r, m_helperColor.g, m_helperColor.b, m_helperColor.a ); // glBegin( GL_QUADS ); // glVertex3f( -1.0f , 0.0f, 1.0f ); // glVertex3f( 1.0f , 0.0f, 1.0f ); // glVertex3f( 1.0f , 0.0f, -1.0f ); // glVertex3f( -1.0f , 0.0f, -1.0f ); // glEnd(); // // glPopAttrib(); break; } view.endGL(); } bool sunflowHelperNode::isBounded() const { return true; } MBoundingBox sunflowHelperNode::boundingBox() const { MPoint corner1; MPoint corner2; switch( m_helperType ) { case 0: corner1 = MPoint( -0.5, -0.5, -0.5 ); corner2 = MPoint( 0.5, 0.5, 0.5 ); break; case 1: corner1 = MPoint( -1.0, -1.0, 0.0 ); corner2 = MPoint( 1.0, 1.0, 0.5 ); break; default: corner1 = MPoint( -0.5, -0.5, -0.5 ); corner2 = MPoint( 0.5, 0.5, 0.5 ); break; } return MBoundingBox( corner1, corner2 ); } MStatus sunflowHelperNode::connectionMade ( const MPlug & plug, const MPlug & otherPlug, bool asSrc ) { /* We should do some testing to se that the connected node is a material. For now i do it at export time. */ return MS::kUnknownParameter; }
8,665
4,206
// // Created by Maarten on 23/06/2020. // #include <esl/economics/markets/ticker.hpp>
88
45
#pragma once #ifndef SNAKE_DEFAULT_COLORS_HXX #define SNAKE_DEFAULT_COLORS_HXX #include "sdl.hxx" namespace snake::client::colors { static SDL_Color const BLACK{0, 0, 0, 0xFF}; static SDL_Color const WHITE{0xFF, 0xFF, 0xFF, 0xFF}; enum class Channel : std::uint8_t { Red = 0, Green = 8, Blue = 16, Alpha = 32, }; constexpr std::uint8_t extractColorChannel(std::uint32_t color, Channel which) { return static_cast<std::uint8_t>(color >> static_cast<std::uint32_t>(which)); } constexpr std::uint32_t calculateColorChannel(std::uint32_t value, Channel which) { return static_cast<std::uint32_t>(value) << static_cast<std::uint32_t>(which); } constexpr std::uint32_t colorToRGBA(SDL_Color const & color) { return calculateColorChannel(color.r, Channel::Red) | calculateColorChannel(color.g, Channel::Green) | calculateColorChannel(color.b, Channel::Blue) | calculateColorChannel(color.a, Channel::Alpha); } constexpr SDL_Color rgbaToColor(std::uint32_t rgba) { return { extractColorChannel(rgba, Channel::Red), extractColorChannel(rgba, Channel::Green), extractColorChannel(rgba, Channel::Blue), extractColorChannel(rgba, Channel::Alpha), }; } } #endif // SNAKE_DEFAULT_COLORS_HXX
1,320
489
#include "Person.h" #include <iostream> #include <sstream> #include <vector> #include "utility.h" #include "PersonVector.h" #include "FEM.h" #include "FEM_MPIMaster.h" #include "FEM_MPISlave.h" #include "TimeSeries.h" #include "Table.h" #include "EquationParser.h" #include "EquationNode.h" #include "Logger.h" #include "RandomBlowfishProvider.h" #include "RandomBasicProvider.h" #include "TimeSeriesManager.h" #include "TableManager.h" #include "ScenarioVector.h" #include "PersonPool.h" #include "fem_exception.h" #include "mpi.h" #include <fstream> #include <time.h> #include <stdio.h> /* defines FILENAME_MAX */ #ifdef __FEM_WIN__ #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #include <sys/types.h> #define GetCurrentDir getcwd #endif void copy_settings(std::string source, std::string dest, Settings &settings); void test_ss_calc(std::string settings_path); int main(int argc,char **argv) { std::ostringstream ss; #ifdef __FEM_UNIX__ // Reset priority asap! pid_t pid = getpid(); ss << "renice +19 -p " << pid; int sysret = system(ss.str().c_str()); if(sysret != 0) std::cerr << "Renice had nonzero return code."; ss.str(""); #endif // Initialize the MPI environment and find the rank of this processor. int myid; MPI::Init(argc,argv); myid = MPI::COMM_WORLD.Get_rank(); std::string settings_name("settings.txt"); if(argc > 1) settings_name = std::string(argv[1]); // Find out if this processor is the master bool is_master = myid == 0; // Find the current path. Should be something of the form XXXXXXX/runtime char cCurrentpath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentpath, sizeof(cCurrentpath))) { std::cerr << "Could not get the current working directory! Fatal!"; return 2; } /* cCurrentpath[sizeof(cCurrentpath) - 1] = '\0'; ss << cCurrentpath << _PATH_DELIM_ << "FEM_CPP_settings"; test_ss_calc(ss.str()); return 0; */ try{ // Create an initial pool of 50,000 person objects. This should be enough for most simulations PersonPool::initPool(50000); Settings settings; settings.set("base_dir", cCurrentpath); // Read in settings file settings.readSettings(std::string(settings.get("base_dir") + _PATH_DELIM_ + settings_name.c_str()).c_str()); // Setup Logging if(is_master) { // Log everything to the log_all.txt file Logger::setLogLevel(ALL); ss << settings.get("base_dir") << _PATH_DELIM_ << "log_all.txt"; Logger::addHandler( new SeverityFormattingLogHandler( new TimeFormattingLogHandler( new FileLogHandler(ss.str().c_str())))); ss.str(""); // Log just general and warning/error messages to the log_info.txt file ss << settings.get("base_dir") << _PATH_DELIM_ << "log_info.txt"; Logger::addHandler( new SeverityFormattingLogHandler( new TimeFormattingLogHandler( new FileLogHandler(ss.str().c_str(), INFO)))); ss.str(""); // Log just errors or warnings to log_error.txt ss << settings.get("base_dir") << _PATH_DELIM_ << "log_error.txt"; Logger::addHandler( new SeverityFormattingLogHandler( new FileLogHandler(ss.str().c_str(), WARNING))); ss.str(""); // Log info to standard out Logger::addHandler( new SeverityFormattingLogHandler( new StreamLogHandler(std::cout, INFO))); ss.str(""); } // Log to stderr if indicated in the settings if(settings.get("log_stderr") == "yes") { // Both the master and slave will be logging to stderr. Need to add a prefix so we can tell what message is from // what processor if(is_master) ss << "[Master] " ; else ss << "[Slave " << myid << "] "; Logger::addHandler( new PrefixFormattingLogHandler( new SeverityFormattingLogHandler( new StreamLogHandler(std::cerr, ERROR)), ss.str())); ss.str(""); } // Setup Randomness based on the settings file RandomProvider* rnd_provider; if(settings.get("random_provider") == "blowfish") { // Setup blowfish random environment RandomBlowfishProvider* rbp = new RandomBlowfishProvider(); ss << settings.get("base_dir") << _PATH_DELIM_ << "FEM_CPP_settings" << _PATH_DELIM_ << "random_tables" << _PATH_DELIM_ << "blowfish_keys.txt"; rbp->readKeyFile(ss.str().c_str()); rnd_provider = rbp; ss.str(""); } else if (settings.get("random_provider") == "basic") { // Random numbers just drawn using normal rand() calls. // Seed the random number engine with the current time. srand(time(NULL)); rnd_provider = new RandomBasicProvider(); } else { ss << "Unknown Random Provider [" << settings.get("random_provider") << "]!"; throw fem_exception(ss.str()); } // Read scenarios ss << settings.get("base_dir") << _PATH_DELIM_ << settings.get("scenarios_file"); ScenarioVector sv; sv.readDelimited(ss.str().c_str(), ','); ss.str(""); FEM* fem = NULL; for(unsigned int i = 0; i < sv.size(); i++) { if(fem != NULL) delete fem; // Create the correct FEM engine, depending on whether this process is the Master or Slave in the MPI setting if(is_master) fem = new FEM_MPIMaster(settings); else fem = new FEM_MPISlave(settings); if(is_master) { // Check if output directory exists. If not, create it. std::string outdir = sv[i]->OutputDir() + _PATH_DELIM_ + sv[i]->Name(); if(!dir_exists(outdir)) make_dir(outdir); // Now check if the detailed_output subdirectory exists. If not create it outdir += _PATH_DELIM_; outdir += "detailed_output"; if(!dir_exists(outdir)) make_dir(outdir); } // Run the scenario fem->runScenario(sv[i], rnd_provider); // Scenario is done and all data is written. // Copy all small input files (settings, models, variables, etc) into the // scenario directory for reproducibility if(is_master) { // Check if a directory exists in the scenario folder called "FEM_CPP_settings". If not, make it ss << sv[i]->OutputDir() << _PATH_DELIM_ << sv[i]->Name() << _PATH_DELIM_ << "FEM_CPP_settings"; std::string dest_settings_dir = ss.str(); ss.str(""); if(!dir_exists(dest_settings_dir)) make_dir(dest_settings_dir); // Copy over the settings.txt, scenarios.csv, and log files std::vector<std::string> files_to_copy; files_to_copy.push_back("settings.txt"); files_to_copy.push_back(settings.get("scenarios_file")); files_to_copy.push_back("log_all.txt"); files_to_copy.push_back("log_info.txt"); files_to_copy.push_back("log_error.txt"); for(unsigned int j = 0; j < files_to_copy.size(); j++) copy_file(dest_settings_dir + _PATH_DELIM_ + files_to_copy[j], settings.get("base_dir") + _PATH_DELIM_ + files_to_copy[j]); files_to_copy.clear(); // Copy over the scenario migration table, if any if(sv[i]->contains("migration_table")) { ss << sv[i]->get("migration_table") << ".txt"; copy_file(dest_settings_dir + _PATH_DELIM_ + ss.str(), settings.get("base_dir") + _PATH_DELIM_ + "FEM_CPP_settings" + _PATH_DELIM_ + ss.str()); ss.str(""); } // Check if a directory exists in the scenario folder called "settings/input_data". If not, make it ss << sv[i]->OutputDir() << _PATH_DELIM_ << sv[i]->Name() << _PATH_DELIM_ << "FEM_CPP_settings" << _PATH_DELIM_ << "input_data"; std::string input_data_dir = ss.str(); ss.str(""); if(!dir_exists(input_data_dir)) make_dir(input_data_dir); if(sv[i]->SimuType() == 3) { /* Copy incoming cohorts if simutype is 3*/ for(unsigned int yr = sv[i]->StartYr(); yr <= sv[i]->StopYr(); yr+= sv[i]->YrStep()) { ss << settings.get("base_dir") << _PATH_DELIM_ << "input_data" << _PATH_DELIM_ << "new51_" << yr << "_" << sv[i]->NewCohortModel() << ".dta"; std::string src_new_cohort_file = ss.str(); ss.str(""); ss << input_data_dir << _PATH_DELIM_ << "new51_" << yr << "_" << sv[i]->NewCohortModel() << ".dta"; std::string dest_new_cohort_file = ss.str(); ss.str(""); copy_file(dest_new_cohort_file, src_new_cohort_file); } } // Copy over settings ss << settings.get("base_dir") << _PATH_DELIM_ << "FEM_CPP_settings"; std::string src_settings_dir = ss.str(); ss.str(""); copy_settings(src_settings_dir,dest_settings_dir,settings); if(sv[i]->contains("settings") && sv[i]->get("settings").length() > 0) { ss << sv[i]->OutputDir() << _PATH_DELIM_ << sv[i]->Name() << _PATH_DELIM_ << "FEM_CPP_settings" << _PATH_DELIM_ << sv[i]->get("settings"); dest_settings_dir = ss.str(); ss.str(""); if(!dir_exists(dest_settings_dir)) make_dir(dest_settings_dir); ss << settings.get("base_dir") << _PATH_DELIM_ << "FEM_CPP_settings" << _PATH_DELIM_ << sv[i]->get("settings"); src_settings_dir = ss.str(); ss.str(""); copy_settings(src_settings_dir,dest_settings_dir,settings); } } } // Clean up delete fem; PersonPool::deletePool(); } catch (const fem_exception & e) { std::ostringstream oss; ss << "Unknown FEM error!" << std::endl << "\t\t" << e.what(); Logger::log(ss.str(), ERROR); MPI::Finalize(); return 1; } catch (const std::exception & e) { std::ostringstream oss; ss << "Unknown error!" << std::endl << "\t\t" << e.what(); Logger::log(ss.str(), ERROR); MPI::Finalize(); return 1; } MPI::Finalize(); return 0; } void copy_settings(std::string source, std::string dest, Settings &settings) { std::ostringstream ss; // Check if the other settings directories we need are there, and if not, make them. std::vector<std::string> req_dirs; req_dirs.push_back("models"); req_dirs.push_back("timeseries"); req_dirs.push_back("tables"); for(unsigned int j = 0; j < req_dirs.size(); j++) { ss << dest << _PATH_DELIM_<< req_dirs[j]; if(!dir_exists(ss.str())) make_dir(ss.str()); ss.str(""); } // Copy all relevant files std::vector<std::string> files_to_copy; std::vector<std::string> temp; files_to_copy.push_back(settings.get("vars_def_file")); files_to_copy.push_back(settings.get("summary_output")); /* Copy time series, if any */ ss << source << _PATH_DELIM_ << "timeseries"; std::string time_series_dir = ss.str(); ss.str(""); if(dir_exists(time_series_dir)) { getdir(time_series_dir.c_str(), temp, "*.txt"); for(unsigned int j = 0; j < temp.size(); j++) { ss << "timeseries" << _PATH_DELIM_ << temp[j]; files_to_copy.push_back(ss.str()); ss.str(""); } temp.clear(); } /* Copy tables, if any */ ss << source << _PATH_DELIM_ << "tables"; std::string tables_dir = ss.str(); ss.str(""); if(dir_exists(tables_dir)) { getdir(tables_dir.c_str(), temp, "*.txt"); for(unsigned int j = 0; j < temp.size(); j++) { ss << "tables" << _PATH_DELIM_ << temp[j]; files_to_copy.push_back(ss.str()); ss.str(""); } temp.clear(); } /* Copy models, if any */ ss << source << _PATH_DELIM_ << "models"; std::string models_dir = ss.str(); ss.str(""); if(dir_exists(models_dir)) { getdir(models_dir.c_str(), temp, "*.est"); for(unsigned int j = 0; j < temp.size(); j++) { ss << "models" << _PATH_DELIM_ << temp[j]; files_to_copy.push_back(ss.str()); ss.str(""); } temp.clear(); } for(unsigned int j = 0; j < files_to_copy.size(); j++) copy_file(dest + _PATH_DELIM_ + files_to_copy[j], source + _PATH_DELIM_ + files_to_copy[j]); } #include "SSCalculator.h" void test_ss_calc(std::string settings_path) { std::ostringstream ss; ss.str(""); TimeSeriesManager ts_manager; // Load time series ss << settings_path << _PATH_DELIM_ << "timeseries" << _PATH_DELIM_; std::string timeseries_dir = ss.str(); ss.str(""); ss << " source: " << timeseries_dir; ss.str(""); try { ts_manager.readTimeSeriesDefinitions(timeseries_dir.c_str()); } catch (const fem_exception & e) { std::cout << e.what() << std::endl; } // Test retirement benefits SSCalculator sscalc(&ts_manager); Person p; p.set(Vars::married, false); p.set(Vars::widowed, false); p.set(Vars::ry_earn, 0.0); p.set(Vars::rq, 400); while(0) { std::cout << "aime rbyr rbmonth rclyr cyr" << std::endl; double aime; unsigned int rbyr, rbmonth, rclyr, cyr; std::cin >> aime >> rbyr >> rbmonth >> rclyr >> cyr; p.set(Vars::raime, aime); p.set(Vars::rbyr, rbyr); p.set(Vars::rbmonth, rbmonth); int ben = (int) sscalc.SSBenefit(&p, cyr, rclyr); std::cout << "Benefit Amount: " << ben << std::endl << std::endl; } // Test spousal benefits Person sp; sp.set(Vars::married, false); p.set(Vars::married, false); p.set(Vars::widowed, true); p.set(Vars::raime, 0.0); p.setSpouse(&sp); sp.set(Vars::widowed, false); sp.set(Vars::ry_earn, 0.0); sp.set(Vars::rq, 400); while(0) { std::cout << "person aime rbyr rbmonth rclyr cyr" << std::endl; double aime; unsigned int rbyr, rbmonth, rclyr, cyr, dyr; std::cin >> aime >> rbyr >> rbmonth >> rclyr >> cyr; p.set(Vars::raime, aime); p.set(Vars::rbyr, rbyr); p.set(Vars::rbmonth, rbmonth); std::cout << "spouse aime rbyr rbmonth rclyr dyr ssclaim" << std::endl; int ssclaim; std::cin >> aime >> rbyr >> rbmonth >> rclyr >> dyr >> ssclaim; sp.set(Vars::raime, aime); sp.set(Vars::rbyr, rbyr); sp.set(Vars::year, dyr); sp.set(Vars::rbmonth, rbmonth); sp.set(Vars::ssclaim, ssclaim); sp.set(Vars::rssclyr, rclyr); int ben = (int) sscalc.SSBenefit(&p, cyr, rclyr); std::cout << "Benefit Amount: " << ben << std::endl << std::endl; } sscalc.test(); }
13,486
5,657
// Copyright mogemimi. Distributed under the MIT license. #include "pomdog/experimental/gui/stack_panel.hpp" #include "pomdog/experimental/gui/drawing_context.hpp" #include "pomdog/experimental/gui/pointer_point.hpp" #include "pomdog/experimental/gui/ui_event_dispatcher.hpp" #include "pomdog/experimental/gui/ui_helper.hpp" #include "pomdog/math/math.hpp" namespace pomdog::gui { StackPanel::StackPanel( const std::shared_ptr<UIEventDispatcher>& dispatcher, int widthIn, int heightIn) : Widget(dispatcher) , padding{12, 8, 10, 8} , barHeight(16) , needToUpdateLayout(true) { SetSize(widthIn, heightIn); verticalLayout = std::make_shared<VerticalLayout>(dispatcher, 140, 10); verticalLayout->SetStackedLayout(true); verticalLayout->SetLayoutSpacing(12); } void StackPanel::SetPosition(const Point2D& positionIn) { Widget::SetPosition(positionIn); POMDOG_ASSERT(verticalLayout != nullptr); verticalLayout->MarkParentTransformDirty(); } void StackPanel::SetPadding(const Thickness& paddingIn) { padding = paddingIn; needToUpdateLayout = true; } void StackPanel::MarkParentTransformDirty() { Widget::MarkParentTransformDirty(); POMDOG_ASSERT(verticalLayout); verticalLayout->MarkParentTransformDirty(); } void StackPanel::MarkContentLayoutDirty() { needToUpdateLayout = true; } bool StackPanel::GetSizeToFitContent() const noexcept { return false; } void StackPanel::OnEnter() { POMDOG_ASSERT(verticalLayout != nullptr); verticalLayout->MarkParentTransformDirty(); POMDOG_ASSERT(shared_from_this()); verticalLayout->SetParent(shared_from_this()); verticalLayout->OnEnter(); } void StackPanel::OnPointerPressed(const PointerPoint& pointerPoint) { if (pointerPoint.MouseEvent && (*pointerPoint.MouseEvent != PointerMouseEvent::LeftButtonPressed)) { return; } auto pointInView = UIHelper::ProjectToChildSpace(pointerPoint.Position, GetGlobalPosition()); const auto collisionHeight = barHeight + padding.Top; Rectangle captionBar{ 0, GetHeight() - collisionHeight, GetWidth(), collisionHeight}; if (captionBar.Contains(pointInView)) { startTouchPoint = math::ToVector2(pointInView); } } void StackPanel::OnPointerMoved(const PointerPoint& pointerPoint) { if (!startTouchPoint) { return; } auto pointInView = UIHelper::ProjectToChildSpace(pointerPoint.Position, GetGlobalPosition()); auto position = math::ToVector2(pointInView); auto tangent = position - *startTouchPoint; auto distanceSquared = math::LengthSquared(tangent); if (distanceSquared >= 1.4143f) { SetPosition(GetPosition() + math::ToPoint2D(tangent)); // NOTE: recalculate position in current coordinate system pointInView = UIHelper::ProjectToChildSpace(pointerPoint.Position, GetGlobalPosition()); position = math::ToVector2(pointInView); startTouchPoint = position; } } void StackPanel::OnPointerReleased([[maybe_unused]] const PointerPoint& pointerPoint) { if (!startTouchPoint) { return; } startTouchPoint = std::nullopt; } void StackPanel::AddChild(const std::shared_ptr<Widget>& widget) { POMDOG_ASSERT(verticalLayout); verticalLayout->AddChild(widget); needToUpdateLayout = true; } std::shared_ptr<Widget> StackPanel::GetChildAt(const Point2D& position) { POMDOG_ASSERT(verticalLayout != nullptr); auto bounds = verticalLayout->GetBounds(); if (bounds.Contains(position)) { return verticalLayout; } return nullptr; } void StackPanel::UpdateAnimation(const Duration& frameDuration) { POMDOG_ASSERT(verticalLayout != nullptr); verticalLayout->UpdateAnimation(frameDuration); } void StackPanel::UpdateLayout() { POMDOG_ASSERT(verticalLayout); verticalLayout->DoLayout(); if (!needToUpdateLayout) { return; } const auto requiredHeight = padding.Top + barHeight + verticalLayout->GetHeight() + padding.Bottom; if (requiredHeight != GetHeight()) { // NOTE: Keeping the original position const auto positionOffset = Point2D{0, GetHeight() - requiredHeight}; SetPosition(GetPosition() + positionOffset); // NOTE: Resizing this panel SetSize(GetWidth(), requiredHeight); auto parent = GetParent(); if (parent) { parent->MarkContentLayoutDirty(); } } // NOTE: Update layout for children { verticalLayout->SetPosition(Point2D{padding.Left, padding.Bottom}); switch (verticalLayout->GetHorizontalAlignment()) { case HorizontalAlignment::Stretch: { auto childWidth = GetWidth() - (padding.Left + padding.Right); verticalLayout->SetSize(childWidth, verticalLayout->GetHeight()); verticalLayout->MarkContentLayoutDirty(); break; } case HorizontalAlignment::Left: break; case HorizontalAlignment::Right: break; } } needToUpdateLayout = false; } void StackPanel::DoLayout() { UpdateLayout(); } void StackPanel::Draw(DrawingContext& drawingContext) { UpdateLayout(); POMDOG_ASSERT(!needToUpdateLayout); const auto* colorScheme = drawingContext.GetColorScheme(); POMDOG_ASSERT(colorScheme != nullptr); auto globalPos = UIHelper::ProjectToWorldSpace(GetPosition(), drawingContext.GetCurrentTransform()); auto primitiveBatch = drawingContext.GetPrimitiveBatch(); const auto w = static_cast<float>(GetWidth()); const auto h = static_cast<float>(GetHeight()); primitiveBatch->DrawRectangle( Rectangle{globalPos.X, globalPos.Y, GetWidth(), GetHeight()}, colorScheme->PanelBackgroundColor); primitiveBatch->DrawRectangle( Rectangle{globalPos.X, globalPos.Y + (GetHeight() - barHeight), GetWidth(), barHeight}, colorScheme->PanelTitleBarColor); const auto pos = math::ToVector2(globalPos); primitiveBatch->DrawLine(pos + Vector2{0.0f, 0.0f}, pos + Vector2{w, 0.0f}, colorScheme->PanelOutlineBorderColor, 1.0f); primitiveBatch->DrawLine(pos + Vector2{0.0f, 0.0f}, pos + Vector2{0.0f, h}, colorScheme->PanelOutlineBorderColor, 1.0f); primitiveBatch->DrawLine(pos + Vector2{0.0f, h}, pos + Vector2{w, h}, colorScheme->PanelOutlineBorderColor, 1.0f); primitiveBatch->DrawLine(pos + Vector2{w, 0.0f}, pos + Vector2{w, h}, colorScheme->PanelOutlineBorderColor, 1.0f); primitiveBatch->Flush(); drawingContext.PushTransform(globalPos); POMDOG_ASSERT(verticalLayout); verticalLayout->Draw(drawingContext); drawingContext.PopTransform(); } } // namespace pomdog::gui
6,742
2,045
#include "Interface/Core/OpcodeDispatcher.h" #include <FEXCore/Core/CoreState.h> #include <climits> #include <cstddef> #include <cstdint> #include <FEXCore/Core/X86Enums.h> namespace FEXCore::IR { auto OpToIndex = [](uint8_t Op) constexpr -> uint8_t { switch (Op) { // Group 1 case 0x80: return 0; case 0x81: return 1; case 0x82: return 2; case 0x83: return 3; // Group 2 case 0xC0: return 0; case 0xC1: return 1; case 0xD0: return 2; case 0xD1: return 3; case 0xD2: return 4; case 0xD3: return 5; // Group 3 case 0xF6: return 0; case 0xF7: return 1; // Group 4 case 0xFE: return 0; // Group 5 case 0xFF: return 0; // Group 11 case 0xC6: return 0; case 0xC7: return 1; } return 0; }; #define OpcodeArgs [[maybe_unused]] FEXCore::X86Tables::DecodedOp Op void OpDispatchBuilder::SyscallOp(OpcodeArgs) { constexpr size_t SyscallArgs = 7; constexpr std::array<uint64_t, SyscallArgs> GPRIndexes = { FEXCore::X86State::REG_RAX, FEXCore::X86State::REG_RDI, FEXCore::X86State::REG_RSI, FEXCore::X86State::REG_RDX, FEXCore::X86State::REG_R10, FEXCore::X86State::REG_R8, FEXCore::X86State::REG_R9, }; auto NewRIP = _Constant(Op->PC); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); auto SyscallOp = _Syscall( _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[0] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[1] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[2] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[3] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[4] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[5] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[6] * 8, GPRClass)); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), SyscallOp); } void OpDispatchBuilder::LEAOp(OpcodeArgs) { uint32_t DstSize = X86Tables::DecodeFlags::GetOpAddr(Op->Flags) == X86Tables::DecodeFlags::FLAG_OPERAND_SIZE_LAST ? 2 : X86Tables::DecodeFlags::GetOpAddr(Op->Flags) == X86Tables::DecodeFlags::FLAG_WIDENING_SIZE_LAST ? 8 : 4; uint32_t SrcSize = (Op->Flags & X86Tables::DecodeFlags::FLAG_ADDRESS_SIZE) ? 4 : 8; OrderedNode *Src = LoadSource_WithOpSize(GPRClass, Op, Op->Src[0], SrcSize, Op->Flags, -1, false); StoreResult_WithOpSize(GPRClass, Op, Op->Dest, Src, DstSize, -1); } void OpDispatchBuilder::NOPOp(OpcodeArgs) { } void OpDispatchBuilder::RETOp(OpcodeArgs) { auto Constant = _Constant(8); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewRIP = _LoadMem(GPRClass, 8, OldSP, 8); OrderedNode *NewSP; if (Op->OP == 0xC2) { auto Offset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); NewSP = _Add(_Add(OldSP, Constant), Offset); } else { NewSP = _Add(OldSP, Constant); } // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); _ExitFunction(); BlockSetRIP = true; } template<uint32_t SrcIndex> void OpDispatchBuilder::SecondaryALUOp(OpcodeArgs) { FEXCore::IR::IROps IROp; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) switch (Op->OP) { case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 0): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 0): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 0): IROp = FEXCore::IR::IROps::OP_ADD; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 1): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 1): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 1): IROp = FEXCore::IR::IROps::OP_OR; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 4): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 4): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 4): IROp = FEXCore::IR::IROps::OP_AND; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 5): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 5): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 5): IROp = FEXCore::IR::IROps::OP_SUB; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 5): case OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 5): IROp = FEXCore::IR::IROps::OP_MUL; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 6): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 6): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 6): IROp = FEXCore::IR::IROps::OP_XOR; break; default: IROp = FEXCore::IR::IROps::OP_LAST; LogMan::Msg::A("Unknown ALU Op: 0x%x", Op->OP); break; }; #undef OPD // X86 basic ALU ops just do the operation between the destination and a single source OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _Add(Dest, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; StoreResult(GPRClass, Op, ALUOp, -1); // Flags set { auto Size = GetSrcSize(Op) * 8; switch (IROp) { case FEXCore::IR::IROps::OP_ADD: GenerateFlags_ADD(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; case FEXCore::IR::IROps::OP_SUB: GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; case FEXCore::IR::IROps::OP_MUL: GenerateFlags_MUL(Op, _Bfe(Size, 0, ALUOp), _MulH(Dest, Src)); break; case FEXCore::IR::IROps::OP_AND: case FEXCore::IR::IROps::OP_XOR: case FEXCore::IR::IROps::OP_OR: { GenerateFlags_Logical(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; } default: break; } } } template<uint32_t SrcIndex> void OpDispatchBuilder::ADCOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto CF = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); auto ALUOp = _Add(_Add(Dest, Src), CF); StoreResult(GPRClass, Op, ALUOp, -1); GenerateFlags_ADC(Op, ALUOp, Dest, Src, CF); } template<uint32_t SrcIndex> void OpDispatchBuilder::SBBOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto CF = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); auto ALUOp = _Sub(_Sub(Dest, Src), CF); StoreResult(GPRClass, Op, ALUOp, -1); GenerateFlags_SBB(Op, ALUOp, Dest, Src, CF); } void OpDispatchBuilder::PUSHOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *Src; if (Op->OP == 0x68 || Op->OP == 0x6A) { // Immediate Push Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); } else { if (Op->OP == 0xFF && Size == 4) LogMan::Msg::A("Woops. Can't do 32bit for this PUSH op"); Src = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); } auto Constant = _Constant(Size); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewSP = _Sub(OldSP, Constant); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); // Store our value to the new stack location _StoreMem(GPRClass, Size, NewSP, Src, Size); } void OpDispatchBuilder::POPOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); auto Constant = _Constant(Size); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewGPR = _LoadMem(GPRClass, Size, OldSP, Size); auto NewSP = _Add(OldSP, Constant); if (Op->OP == 0x8F && Size == 4) LogMan::Msg::A("Woops. Can't do 32bit for this POP op"); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); // Store what we loaded from the stack StoreResult(GPRClass, Op, NewGPR, -1); } void OpDispatchBuilder::LEAVEOp(OpcodeArgs) { // First we move RBP in to RSP and then behave effectively like a pop uint8_t Size = GetSrcSize(Op); auto Constant = _Constant(Size); LogMan::Throw::A(Size == 8, "Can't handle a LEAVE op with size %d", Size); auto OldBP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RBP]), GPRClass); auto NewGPR = _LoadMem(GPRClass, Size, OldBP, Size); auto NewSP = _Add(OldBP, Constant); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); // Store what we loaded to RBP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RBP]), NewGPR); } void OpDispatchBuilder::CALLOp(OpcodeArgs) { BlockSetRIP = true; auto ConstantPC = _Constant(Op->PC + Op->InstSize); OrderedNode *JMPPCOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *NewRIP = _Add(JMPPCOffset, ConstantPC); auto ConstantPCReturn = _Constant(Op->PC + Op->InstSize); auto ConstantSize = _Constant(8); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewSP = _Sub(OldSP, ConstantSize); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); _StoreMem(GPRClass, 8, NewSP, ConstantPCReturn, 8); // Store the RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); _ExitFunction(); // If we get here then leave the function now } void OpDispatchBuilder::CALLAbsoluteOp(OpcodeArgs) { BlockSetRIP = true; OrderedNode *JMPPCOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto ConstantPCReturn = _Constant(Op->PC + Op->InstSize); auto ConstantSize = _Constant(8); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewSP = _Sub(OldSP, ConstantSize); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); _StoreMem(GPRClass, 8, NewSP, ConstantPCReturn, 8); // Store the RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), JMPPCOffset); _ExitFunction(); // If we get here then leave the function now } void OpDispatchBuilder::CondJUMPOp(OpcodeArgs) { BlockSetRIP = true; auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); IRPair<IROp_Header> SrcCond; IRPair<IROp_Constant> TakeBranch; IRPair<IROp_Constant> DoNotTakeBranch; TakeBranch = _Constant(1); DoNotTakeBranch = _Constant(0); switch (Op->OP) { case 0x70: case 0x80: { // JO - Jump if OF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x71: case 0x81: { // JNO - Jump if OF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x72: case 0x82: { // JC - Jump if CF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x73: case 0x83: { // JNC - Jump if CF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x74: case 0x84: { // JE - Jump if ZF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x75: case 0x85: { // JNE - Jump if ZF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x76: case 0x86: { // JNA - Jump if CF == 1 || ZC == 1 auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); auto Check = _Or(Flag1, Flag2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, TakeBranch, DoNotTakeBranch); break; } case 0x77: case 0x87: { // JA - Jump if CF == 0 && ZF == 0 auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); auto Check = _Or(Flag1, _Lshl(Flag2, _Constant(1))); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x78: case 0x88: { // JS - Jump if SF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x79: case 0x89: { // JNS - Jump if SF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x7A: case 0x8A: { // JP - Jump if PF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_PF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x7B: case 0x8B: { // JNP - Jump if PF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_PF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x7C: // SF <> OF case 0x8C: { auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag1, Flag2, TakeBranch, DoNotTakeBranch); break; } case 0x7D: // SF = OF case 0x8D: { auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag1, Flag2, TakeBranch, DoNotTakeBranch); break; } case 0x7E: // ZF = 1 || SF <> OF case 0x8E: { auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, OneConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_NEQ, Flag2, Flag3, OneConst, ZeroConst); auto Check = _Or(Select1, Select2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, TakeBranch, DoNotTakeBranch); break; } case 0x7F: // ZF = 0 && SF = OF case 0x8F: { auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, ZeroConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_EQ, Flag2, Flag3, OneConst, ZeroConst); auto Check = _And(Select1, Select2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, TakeBranch, DoNotTakeBranch); break; } default: LogMan::Msg::A("Unknown Jmp Op: 0x%x\n", Op->OP); return; } LogMan::Throw::A(Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Target = Op->PC + Op->InstSize + Op->Src[0].TypeLiteral.Literal; auto TrueBlock = JumpTargets.find(Target); auto FalseBlock = JumpTargets.find(Op->PC + Op->InstSize); // Fallback { auto CondJump = _CondJump(SrcCond); // Taking branch block if (TrueBlock != JumpTargets.end()) { SetTrueJumpTarget(CondJump, TrueBlock->second.BlockEntry); } else { // Make sure to start a new block after ending this one auto JumpTarget = CreateNewCodeBlock(); SetTrueJumpTarget(CondJump, JumpTarget); SetCurrentCodeBlock(JumpTarget); auto RIPOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto RIPTargetConst = _Constant(Op->PC + Op->InstSize); auto NewRIP = _Add(RIPOffset, RIPTargetConst); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); _ExitFunction(); } // Failure to take branch if (FalseBlock != JumpTargets.end()) { SetFalseJumpTarget(CondJump, FalseBlock->second.BlockEntry); } else { // Make sure to start a new block after ending this one auto JumpTarget = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, JumpTarget); SetCurrentCodeBlock(JumpTarget); // Leave block auto RIPTargetConst = _Constant(Op->PC + Op->InstSize); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), RIPTargetConst); _ExitFunction(); } } } void OpDispatchBuilder::JUMPOp(OpcodeArgs) { BlockSetRIP = true; // This is just an unconditional relative literal jump // XXX: Reenable if (Multiblock) { LogMan::Throw::A(Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Target = Op->PC + Op->InstSize + Op->Src[0].TypeLiteral.Literal; auto JumpBlock = JumpTargets.find(Target); if (JumpBlock != JumpTargets.end()) { _Jump(GetNewJumpBlock(Target)); } else { // If the block isn't a jump target then we need to create an exit block auto Jump = _Jump(); auto JumpTarget = CreateNewCodeBlock(); SetJumpTarget(Jump, JumpTarget); SetCurrentCodeBlock(JumpTarget); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), _Constant(Target)); _ExitFunction(); } return; } // Fallback { // This source is a literal auto RIPOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto RIPTargetConst = _Constant(Op->PC + Op->InstSize); auto NewRIP = _Add(RIPOffset, RIPTargetConst); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); _ExitFunction(); } } void OpDispatchBuilder::JUMPAbsoluteOp(OpcodeArgs) { BlockSetRIP = true; // This is just an unconditional jump // This uses ModRM to determine its location // No way to use this effectively in multiblock auto RIPOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), RIPOffset); _ExitFunction(); } void OpDispatchBuilder::SETccOp(OpcodeArgs) { enum CompareType { COMPARE_ZERO, COMPARE_NOTZERO, COMPARE_EQUALMASK, COMPARE_OTHER, }; uint32_t FLAGMask; CompareType Type = COMPARE_OTHER; OrderedNode *SrcCond; auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); switch (Op->OP) { case 0x90: FLAGMask = 1 << FEXCore::X86State::RFLAG_OF_LOC; Type = COMPARE_NOTZERO; break; case 0x91: FLAGMask = 1 << FEXCore::X86State::RFLAG_OF_LOC; Type = COMPARE_ZERO; break; case 0x92: FLAGMask = 1 << FEXCore::X86State::RFLAG_CF_LOC; Type = COMPARE_NOTZERO; break; case 0x93: FLAGMask = 1 << FEXCore::X86State::RFLAG_CF_LOC; Type = COMPARE_ZERO; break; case 0x94: FLAGMask = 1 << FEXCore::X86State::RFLAG_ZF_LOC; Type = COMPARE_NOTZERO; break; case 0x95: FLAGMask = 1 << FEXCore::X86State::RFLAG_ZF_LOC; Type = COMPARE_ZERO; break; case 0x96: FLAGMask = (1 << FEXCore::X86State::RFLAG_ZF_LOC) | (1 << FEXCore::X86State::RFLAG_CF_LOC); Type = COMPARE_NOTZERO; break; case 0x97: FLAGMask = (1 << FEXCore::X86State::RFLAG_ZF_LOC) | (1 << FEXCore::X86State::RFLAG_CF_LOC); Type = COMPARE_ZERO; break; case 0x98: FLAGMask = 1 << FEXCore::X86State::RFLAG_SF_LOC; Type = COMPARE_NOTZERO; break; case 0x99: FLAGMask = 1 << FEXCore::X86State::RFLAG_SF_LOC; Type = COMPARE_ZERO; break; case 0x9A: FLAGMask = 1 << FEXCore::X86State::RFLAG_PF_LOC; Type = COMPARE_NOTZERO; break; case 0x9B: FLAGMask = 1 << FEXCore::X86State::RFLAG_PF_LOC; Type = COMPARE_ZERO; break; case 0x9D: { // SF = OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag1, Flag2, OneConst, ZeroConst); break; } case 0x9C: { // SF <> OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag1, Flag2, OneConst, ZeroConst); break; } case 0x9E: { // ZF = 1 || SF <> OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, OneConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_NEQ, Flag2, Flag3, OneConst, ZeroConst); SrcCond = _Or(Select1, Select2); break; } case 0x9F: { // ZF = 0 && SF = OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, ZeroConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_EQ, Flag2, Flag3, OneConst, ZeroConst); SrcCond = _And(Select1, Select2); break; } default: LogMan::Msg::A("Unhandled SetCC op: 0x%x", Op->OP); break; } if (Type != COMPARE_OTHER) { auto MaskConst = _Constant(FLAGMask); auto RFLAG = GetPackedRFLAG(false); auto AndOp = _And(RFLAG, MaskConst); switch (Type) { case COMPARE_ZERO: { SrcCond = _Select(FEXCore::IR::COND_EQ, AndOp, ZeroConst, OneConst, ZeroConst); break; } case COMPARE_NOTZERO: { SrcCond = _Select(FEXCore::IR::COND_NEQ, AndOp, ZeroConst, OneConst, ZeroConst); break; } case COMPARE_EQUALMASK: { SrcCond = _Select(FEXCore::IR::COND_EQ, AndOp, MaskConst, OneConst, ZeroConst); break; } case COMPARE_OTHER: break; } } StoreResult(GPRClass, Op, SrcCond, -1); } template<uint32_t SrcIndex> void OpDispatchBuilder::TESTOp(OpcodeArgs) { // TEST is an instruction that does an AND between the sources // Result isn't stored in result, only writes to flags OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _And(Dest, Src); auto Size = GetSrcSize(Op) * 8; GenerateFlags_Logical(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } void OpDispatchBuilder::MOVSXDOp(OpcodeArgs) { // This instruction is a bit special // if SrcSize == 2 // Then lower 16 bits of destination is written without changing the upper 48 bits // else /* Size == 4 */ // if REX_WIDENING: // Sext(32, Src) // else // Zext(32, Src) // uint8_t Size = std::min(static_cast<uint8_t>(4), GetSrcSize(Op)); OrderedNode *Src = LoadSource_WithOpSize(GPRClass, Op, Op->Src[0], Size, Op->Flags, -1); if (Size == 2) { // This'll make sure to insert in to the lower 16bits without modifying upper bits StoreResult_WithOpSize(GPRClass, Op, Op->Dest, Src, Size, -1); } else if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REX_WIDENING) { // With REX.W then Sext Src = _Sext(Size * 8, Src); StoreResult(GPRClass, Op, Src, -1); } else { // Without REX.W then Zext Src = _Zext(Size * 8, Src); StoreResult(GPRClass, Op, Src, -1); } } void OpDispatchBuilder::MOVSXOp(OpcodeArgs) { // This will ZExt the loaded size // We want to Sext it uint8_t Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); Src = _Sext(Size * 8, Src); StoreResult(GPRClass, Op, Op->Dest, Src, -1); } void OpDispatchBuilder::MOVZXOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // Just make sure this is zero extended Src = _Zext(Size * 8, Src); StoreResult(GPRClass, Op, Src, -1); } template<uint32_t SrcIndex> void OpDispatchBuilder::CMPOp(OpcodeArgs) { // CMP is an instruction that does a SUB between the sources // Result isn't stored in result, only writes to flags OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op) * 8; auto ALUOp = _Sub(Dest, Src); GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } void OpDispatchBuilder::CQOOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto BfeOp = _Bfe(1, GetSrcSize(Op) * 8 - 1, Src); auto ZeroConst = _Constant(0); auto MaxConst = _Constant(~0ULL); auto SelectOp = _Select(FEXCore::IR::COND_EQ, BfeOp, ZeroConst, ZeroConst, MaxConst); StoreResult(GPRClass, Op, SelectOp, -1); } void OpDispatchBuilder::XCHGOp(OpcodeArgs) { // Load both the source and the destination if (Op->OP == 0x90 && GetSrcSize(Op) >= 4 && Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Src[0].TypeGPR.GPR == FEXCore::X86State::REG_RAX && Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Dest.TypeGPR.GPR == FEXCore::X86State::REG_RAX) { // This is one heck of a sucky special case // If we are the 0x90 XCHG opcode (Meaning source is GPR RAX) // and destination register is ALSO RAX // and in this very specific case we are 32bit or above // Then this is a no-op // This is because 0x90 without a prefix is technically `xchg eax, eax` // But this would result in a zext on 64bit, which would ruin the no-op nature of the instruction // So x86-64 spec mandates this special case that even though it is a 32bit instruction and // is supposed to zext the result, it is a true no-op return; } OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); if (DestIsLockedMem(Op)) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); auto Result = _AtomicSwap(Dest, Src, GetSrcSize(Op)); StoreResult(GPRClass, Op, Op->Src[0], Result, -1); } else { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); // Swap the contents // Order matters here since we don't want to swap context contents for one that effects the other StoreResult(GPRClass, Op, Op->Dest, Src, -1); StoreResult(GPRClass, Op, Op->Src[0], Dest, -1); } } void OpDispatchBuilder::CDQOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); uint8_t SrcSize = GetSrcSize(Op); Src = _Sext(SrcSize * 4, Src); if (SrcSize == 4) { Src = _Zext(SrcSize * 8, Src); SrcSize *= 2; } StoreResult_WithOpSize(GPRClass, Op, Op->Dest, Src, SrcSize * 8, -1); } void OpDispatchBuilder::SAHFOp(OpcodeArgs) { OrderedNode *Src = _LoadContext(1, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]) + 1, GPRClass); // Clear bits that aren't supposed to be set Src = _And(Src, _Constant(~0b101000)); // Set the bit that is always set here Src = _Or(Src, _Constant(0b10)); // Store the lower 8 bits in to RFLAGS SetPackedRFLAG(true, Src); } void OpDispatchBuilder::LAHFOp(OpcodeArgs) { // Load the lower 8 bits of the Rflags register auto RFLAG = GetPackedRFLAG(true); // Store the lower 8 bits of the rflags register in to AH _StoreContext(GPRClass, 1, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]) + 1, RFLAG); } void OpDispatchBuilder::FLAGControlOp(OpcodeArgs) { enum OpType { OP_CLEAR, OP_SET, OP_COMPLEMENT, }; OpType Type; uint64_t Flag; switch (Op->OP) { case 0xF5: // CMC Flag= FEXCore::X86State::RFLAG_CF_LOC; Type = OP_COMPLEMENT; break; case 0xF8: // CLC Flag= FEXCore::X86State::RFLAG_CF_LOC; Type = OP_CLEAR; break; case 0xF9: // STC Flag= FEXCore::X86State::RFLAG_CF_LOC; Type = OP_SET; break; case 0xFC: // CLD Flag= FEXCore::X86State::RFLAG_DF_LOC; Type = OP_CLEAR; break; case 0xFD: // STD Flag= FEXCore::X86State::RFLAG_DF_LOC; Type = OP_SET; break; } OrderedNode *Result{}; switch (Type) { case OP_CLEAR: { Result = _Constant(0); break; } case OP_SET: { Result = _Constant(1); break; } case OP_COMPLEMENT: { auto RFLAG = GetRFLAG(Flag); Result = _Xor(RFLAG, _Constant(1)); break; } } SetRFLAG(Result, Flag); } void OpDispatchBuilder::MOVSegOp(OpcodeArgs) { // In x86-64 mode the accesses to the segment registers end up being constant zero moves // Aside from FS/GS LogMan::Msg::A("Wanting reg: %d\n", Op->Src[0].TypeGPR.GPR); // StoreResult(Op, Src); } void OpDispatchBuilder::MOVOffsetOp(OpcodeArgs) { OrderedNode *Src; switch (Op->OP) { case 0xA0: case 0xA1: // Source is memory(literal) // Dest is GPR Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1, true, true); break; case 0xA2: case 0xA3: // Source is GPR // Dest is memory(literal) Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); break; } StoreResult(GPRClass, Op, Op->Dest, Src, -1); } void OpDispatchBuilder::CMOVOp(OpcodeArgs) { enum CompareType { COMPARE_ZERO, COMPARE_NOTZERO, COMPARE_EQUALMASK, COMPARE_OTHER, }; uint32_t FLAGMask; CompareType Type = COMPARE_OTHER; OrderedNode *SrcCond; auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); switch (Op->OP) { case 0x40: FLAGMask = 1 << FEXCore::X86State::RFLAG_OF_LOC; Type = COMPARE_NOTZERO; break; case 0x41: FLAGMask = 1 << FEXCore::X86State::RFLAG_OF_LOC; Type = COMPARE_ZERO; break; case 0x42: FLAGMask = 1 << FEXCore::X86State::RFLAG_CF_LOC; Type = COMPARE_NOTZERO; break; case 0x43: FLAGMask = 1 << FEXCore::X86State::RFLAG_CF_LOC; Type = COMPARE_ZERO; break; case 0x44: FLAGMask = 1 << FEXCore::X86State::RFLAG_ZF_LOC; Type = COMPARE_NOTZERO; break; case 0x45: FLAGMask = 1 << FEXCore::X86State::RFLAG_ZF_LOC; Type = COMPARE_ZERO; break; case 0x46: FLAGMask = (1 << FEXCore::X86State::RFLAG_ZF_LOC) | (1 << FEXCore::X86State::RFLAG_CF_LOC); Type = COMPARE_NOTZERO; break; case 0x47: FLAGMask = (1 << FEXCore::X86State::RFLAG_ZF_LOC) | (1 << FEXCore::X86State::RFLAG_CF_LOC); Type = COMPARE_ZERO; break; case 0x48: FLAGMask = 1 << FEXCore::X86State::RFLAG_SF_LOC; Type = COMPARE_NOTZERO; break; case 0x49: FLAGMask = 1 << FEXCore::X86State::RFLAG_SF_LOC; Type = COMPARE_ZERO; break; case 0x4A: FLAGMask = 1 << FEXCore::X86State::RFLAG_PF_LOC; Type = COMPARE_NOTZERO; break; case 0x4B: FLAGMask = 1 << FEXCore::X86State::RFLAG_PF_LOC; Type = COMPARE_ZERO; break; case 0x4C: { // SF <> OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag1, Flag2, Src, Dest); break; } case 0x4D: { // SF = OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag1, Flag2, Src, Dest); break; } case 0x4E: { // ZF = 1 || SF <> OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, OneConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_NEQ, Flag2, Flag3, OneConst, ZeroConst); auto Check = _Or(Select1, Select2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, Src, Dest); break; } case 0x4F: { // ZF = 0 && SSF = OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, ZeroConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_EQ, Flag2, Flag3, OneConst, ZeroConst); auto Check = _And(Select1, Select2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, Src, Dest); break; } default: LogMan::Msg::A("Unhandled CMOV op: 0x%x", Op->OP); break; } if (Type != COMPARE_OTHER) { auto MaskConst = _Constant(FLAGMask); auto RFLAG = GetPackedRFLAG(false); auto AndOp = _And(RFLAG, MaskConst); switch (Type) { case COMPARE_ZERO: { SrcCond = _Select(FEXCore::IR::COND_EQ, AndOp, ZeroConst, Src, Dest); break; } case COMPARE_NOTZERO: { SrcCond = _Select(FEXCore::IR::COND_NEQ, AndOp, ZeroConst, Src, Dest); break; } case COMPARE_EQUALMASK: { SrcCond = _Select(FEXCore::IR::COND_EQ, AndOp, MaskConst, Src, Dest); break; } case COMPARE_OTHER: break; } } StoreResult(GPRClass, Op, SrcCond, -1); } void OpDispatchBuilder::CPUIDOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); auto Res = _CPUID(Src); _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), _ExtractElement(Res, 0)); _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RBX]), _ExtractElement(Res, 1)); _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), _ExtractElement(Res, 2)); _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), _ExtractElement(Res, 3)); } template<bool SHL1Bit> void OpDispatchBuilder::SHLOp(OpcodeArgs) { OrderedNode *Src; OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); if (SHL1Bit) { Src = _Constant(1); } else { Src = LoadSource(GPRClass, Op, Op->Src[1], Op->Flags, -1); } auto Size = GetSrcSize(Op) * 8; // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(0x3F)); else Src = _And(Src, _Constant(0x1F)); auto ALUOp = _Lshl(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This isn't correct // GenerateFlags_Shift(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } template<bool SHR1Bit> void OpDispatchBuilder::SHROp(OpcodeArgs) { OrderedNode *Src; auto Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); if (SHR1Bit) { Src = _Constant(1); } else { Src = LoadSource(GPRClass, Op, Op->Src[1], Op->Flags, -1); } auto Size = GetSrcSize(Op) * 8; // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(0x3F)); else Src = _And(Src, _Constant(0x1F)); if (Size != 64) { Dest = _Bfe(Size, 0, Dest); } auto ALUOp = _Lshr(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This isn't correct GenerateFlags_Logical(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); if (SHR1Bit) { SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Bfe(1, Size - 1, Src)); } } void OpDispatchBuilder::SHLDOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Shift = LoadSource_WithOpSize(GPRClass, Op, Op->Src[1], 1, Op->Flags, -1); auto Size = GetSrcSize(Op) * 8; // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Shift = _And(Shift, _Constant(0x3F)); else Shift = _And(Shift, _Constant(0x1F)); auto ShiftRight = _Sub(_Constant(Size), Shift); OrderedNode *Res{}; if (Size == 16) { LogMan::Msg::A("Unsupported Op"); } else { auto Tmp1 = _Lshl(Dest, Shift); auto Tmp2 = _Lshr(Src, ShiftRight); Res = _Or(Tmp1, Tmp2); } StoreResult(GPRClass, Op, Res, -1); // XXX: This isn't correct // GenerateFlags_Shift(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } void OpDispatchBuilder::SHRDOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Shift{}; if (Op->OP == 0xAC) { LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); Shift = _Constant(Op->Src[1].TypeLiteral.Literal); } else Shift = _LoadContext(1, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); auto Size = GetSrcSize(Op) * 8; // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Shift = _And(Shift, _Constant(0x3F)); else Shift = _And(Shift, _Constant(0x1F)); auto ShiftRight = _Neg(Shift); OrderedNode *Res{}; if (Size == 16) { LogMan::Msg::A("Unsupported Op"); } else { auto Tmp1 = _Lshr(Dest, Shift); auto Tmp2 = _Lshl(Src, ShiftRight); Res = _Or(Tmp1, Tmp2); } StoreResult(GPRClass, Op, Res, -1); // XXX: This isn't correct // GenerateFlags_Shift(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } void OpDispatchBuilder::ASHROp(OpcodeArgs) { bool SHR1Bit = false; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) switch (Op->OP) { case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 7): case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 7): SHR1Bit = true; break; } #undef OPD OrderedNode *Src; OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op) * 8; if (SHR1Bit) { Src = _Constant(Size, 1); } else { Src = LoadSource(GPRClass, Op, Op->Src[1], Op->Flags, -1); } // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(Size, 0x3F)); else Src = _And(Src, _Constant(Size, 0x1F)); auto ALUOp = _Ashr(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This isn't correct GenerateFlags_Logical(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); if (SHR1Bit) { SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Bfe(1, Size - 1, Src)); } } template<uint32_t SrcIndex> void OpDispatchBuilder::ROROp(OpcodeArgs) { bool Is1Bit = false; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) switch (Op->OP) { case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 1): case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 1): Is1Bit = true; break; } #undef OPD OrderedNode *Src; OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op) * 8; if (Is1Bit) { Src = _Constant(Size, 1); } else { Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); } // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(Size, 0x3F)); else Src = _And(Src, _Constant(Size, 0x1F)); auto ALUOp = _Ror(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This is incorrect GenerateFlags_Rotate(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); if (Is1Bit) { SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Bfe(1, Size - 1, Src)); } } template<uint32_t SrcIndex> void OpDispatchBuilder::ROLOp(OpcodeArgs) { bool Is1Bit = false; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) switch (Op->OP) { case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 0): case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 0): Is1Bit = true; break; default: break; } #undef OPD OrderedNode *Src; OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op) * 8; if (Is1Bit) { Src = _Constant(Size, 1); } else { Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); } // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(Size, 0x3F)); else Src = _And(Src, _Constant(Size, 0x1F)); auto ALUOp = _Rol(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This is incorrect GenerateFlags_Rotate(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); if (Is1Bit) { SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Bfe(1, Size - 1, Src)); } } template<uint32_t SrcIndex> void OpDispatchBuilder::BTOp(OpcodeArgs) { OrderedNode *Result; OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Result = _Lshr(Dest, Src); } else { // Load the address to the memory location OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); // Address is provided as bits we want BYTE offsets // Just shift by 3 to get the offset Src = _Lshr(Src, _Constant(3)); // Get the address offset by shifting out the size of the op (To shift out the bit selection) // Then use that to index in to the memory location by size of op // Now add the addresses together and load the memory OrderedNode *MemoryLocation = _Add(Dest, Src); Result = _LoadMem(GPRClass, Size, MemoryLocation, Size); // Now shift in to the correct bit location Result = _Lshr(Result, BitSelect); } SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(Result); } template<uint32_t SrcIndex> void OpDispatchBuilder::BTROp(OpcodeArgs) { OrderedNode *Result; OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Result = _Lshr(Dest, Src); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); BitMask = _Neg(BitMask); Dest = _And(Dest, BitMask); StoreResult(GPRClass, Op, Dest, -1); } else { // Load the address to the memory location OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); // Address is provided as bits we want BYTE offsets // Just shift by 3 to get the offset Src = _Lshr(Src, _Constant(3)); // Get the address offset by shifting out the size of the op (To shift out the bit selection) // Then use that to index in to the memory location by size of op // Now add the addresses together and load the memory OrderedNode *MemoryLocation = _Add(Dest, Src); OrderedNode *Value = _LoadMem(GPRClass, Size, MemoryLocation, Size); // Now shift in to the correct bit location Result = _Lshr(Value, BitSelect); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); BitMask = _Neg(BitMask); Value = _And(Value, BitMask); _StoreMem(GPRClass, Size, MemoryLocation, Value, Size); } SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(Result); } template<uint32_t SrcIndex> void OpDispatchBuilder::BTSOp(OpcodeArgs) { OrderedNode *Result; OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Result = _Lshr(Dest, Src); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); Dest = _Or(Dest, BitMask); StoreResult(GPRClass, Op, Dest, -1); } else { // Load the address to the memory location OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); // Address is provided as bits we want BYTE offsets // Just shift by 3 to get the offset Src = _Lshr(Src, _Constant(3)); // Get the address offset by shifting out the size of the op (To shift out the bit selection) // Then use that to index in to the memory location by size of op // Now add the addresses together and load the memory OrderedNode *MemoryLocation = _Add(Dest, Src); OrderedNode *Value = _LoadMem(GPRClass, Size, MemoryLocation, Size); // Now shift in to the correct bit location Result = _Lshr(Value, BitSelect); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); Value = _Or(Value, BitMask); _StoreMem(GPRClass, Size, MemoryLocation, Value, Size); } SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(Result); } template<uint32_t SrcIndex> void OpDispatchBuilder::BTCOp(OpcodeArgs) { OrderedNode *Result; OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Result = _Lshr(Dest, Src); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); Dest = _Xor(Dest, BitMask); StoreResult(GPRClass, Op, Dest, -1); } else { // Load the address to the memory location OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); // Address is provided as bits we want BYTE offsets // Just shift by 3 to get the offset Src = _Lshr(Src, _Constant(3)); // Get the address offset by shifting out the size of the op (To shift out the bit selection) // Then use that to index in to the memory location by size of op // Now add the addresses together and load the memory OrderedNode *MemoryLocation = _Add(Dest, Src); OrderedNode *Value = _LoadMem(GPRClass, Size, MemoryLocation, Size); // Now shift in to the correct bit location Result = _Lshr(Value, BitSelect); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); Value = _Xor(Value, BitMask); _StoreMem(GPRClass, Size, MemoryLocation, Value, Size); } SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(Result); } void OpDispatchBuilder::IMUL1SrcOp(OpcodeArgs) { OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto Dest = _Mul(Src1, Src2); StoreResult(GPRClass, Op, Dest, -1); GenerateFlags_MUL(Op, Dest, _MulH(Src1, Src2)); } void OpDispatchBuilder::IMUL2SrcOp(OpcodeArgs) { OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Src2 = LoadSource(GPRClass, Op, Op->Src[1], Op->Flags, -1); auto Dest = _Mul(Src1, Src2); StoreResult(GPRClass, Op, Dest, -1); GenerateFlags_MUL(Op, Dest, _MulH(Src1, Src2)); } void OpDispatchBuilder::IMULOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); if (Size != 8) { Src1 = _Sext(Size * 8, Src1); Src2 = _Sext(Size * 8, Src2); } OrderedNode *Result = _Mul(Src1, Src2); OrderedNode *ResultHigh{}; if (Size == 1) { // Result is stored in AX _StoreContext(GPRClass, 2, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); ResultHigh = _Bfe(8, 8, Result); ResultHigh = _Sext(Size * 8, ResultHigh); } else if (Size == 2) { // 16bits stored in AX // 16bits stored in DX _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); ResultHigh = _Bfe(16, 16, Result); ResultHigh = _Sext(Size * 8, ResultHigh); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } else if (Size == 4) { // 32bits stored in EAX // 32bits stored in EDX // Make sure they get Zext correctly OrderedNode *ResultLow = _Bfe(32, 0, Result); ResultLow = _Zext(Size * 8, ResultLow); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), ResultLow); ResultHigh = _Bfe(32, 32, Result); ResultHigh = _Zext(Size * 8, ResultHigh); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } else if (Size == 8) { // 64bits stored in RAX // 64bits stored in RDX ResultHigh = _MulH(Src1, Src2); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } GenerateFlags_MUL(Op, Result, ResultHigh); } void OpDispatchBuilder::MULOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); if (Size != 8) { Src1 = _Zext(Size * 8, Src1); Src2 = _Zext(Size * 8, Src2); } OrderedNode *Result = _UMul(Src1, Src2); OrderedNode *ResultHigh{}; if (Size == 1) { // Result is stored in AX _StoreContext(GPRClass, 2, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); ResultHigh = _Bfe(8, 8, Result); } else if (Size == 2) { // 16bits stored in AX // 16bits stored in DX _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); ResultHigh = _Bfe(16, 16, Result); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } else if (Size == 4) { // 32bits stored in EAX // 32bits stored in EDX // Make sure they get Zext correctly OrderedNode *ResultLow = _Bfe(32, 0, Result); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), ResultLow); ResultHigh = _Bfe(32, 32, Result); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } else if (Size == 8) { // 64bits stored in RAX // 64bits stored in RDX ResultHigh = _UMulH(Src1, Src2); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } GenerateFlags_UMUL(Op, ResultHigh); } void OpDispatchBuilder::NOTOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *MaskConst{}; if (Size == 8) { MaskConst = _Constant(~0ULL); } else { MaskConst = _Constant((1ULL << (Size * 8)) - 1); } OrderedNode *Src = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Src = _Xor(Src, MaskConst); StoreResult(GPRClass, Op, Src, -1); } void OpDispatchBuilder::XADDOp(OpcodeArgs) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // If this is a GPR then we can just do an Add and store auto Result = _Add(Dest, Src); StoreResult(GPRClass, Op, Result, -1); // Previous value in dest gets stored in src StoreResult(GPRClass, Op, Op->Src[0], Dest, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_ADD(Op, _Bfe(Size, 0, Result), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } else { auto Before = _AtomicFetchAdd(Dest, Src, GetSrcSize(Op)); StoreResult(GPRClass, Op, Op->Src[0], Before, -1); } } void OpDispatchBuilder::PopcountOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); Src = _Popcount(Src); StoreResult(GPRClass, Op, Src, -1); } void OpDispatchBuilder::RDTSCOp(OpcodeArgs) { auto Counter = _CycleCounter(); auto CounterLow = _Bfe(32, 0, Counter); auto CounterHigh = _Bfe(32, 32, Counter); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), CounterLow); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), CounterHigh); } void OpDispatchBuilder::INCOp(OpcodeArgs) { LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX), "Can't handle REP on this\n"); if (DestIsLockedMem(Op)) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); auto OneConst = _Constant(1); auto AtomicResult = _AtomicFetchAdd(Dest, OneConst, GetSrcSize(Op)); auto ALUOp = _Add(AtomicResult, OneConst); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_ADD(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, OneConst)); } else { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto OneConst = _Constant(1); auto ALUOp = _Add(Dest, OneConst); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_ADD(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, OneConst)); } } void OpDispatchBuilder::DECOp(OpcodeArgs) { LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX), "Can't handle REP on this\n"); if (DestIsLockedMem(Op)) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); auto OneConst = _Constant(1); auto AtomicResult = _AtomicFetchSub(Dest, OneConst, GetSrcSize(Op)); auto ALUOp = _Sub(AtomicResult, OneConst); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, OneConst)); } else { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto OneConst = _Constant(1); auto ALUOp = _Sub(Dest, OneConst); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, OneConst)); } } void OpDispatchBuilder::STOSOp(OpcodeArgs) { LogMan::Throw::A(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX, "Can't handle REP not existing on STOS\n"); auto Size = GetSrcSize(Op); // Create all our blocks auto LoopHead = CreateNewCodeBlock(); auto LoopTail = CreateNewCodeBlock(); auto LoopEnd = CreateNewCodeBlock(); // At the time this was written, our RA can't handle accessing nodes across blocks. // So we need to re-load and re-calculate essential values each iteration of the loop. // First thing we need to do is finish this block and jump to the start of the loop. _Jump(LoopHead); SetCurrentCodeBlock(LoopHead); { OrderedNode *Counter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); auto ZeroConst = _Constant(0); // Can we end the block? auto CanLeaveCond = _Select(FEXCore::IR::COND_EQ, Counter, ZeroConst, _Constant(1), ZeroConst); _CondJump(CanLeaveCond, LoopEnd, LoopTail); } SetCurrentCodeBlock(LoopTail); { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); // Store to memory where RDI points _StoreMem(GPRClass, Size, Dest, Src, Size); OrderedNode *TailCounter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); OrderedNode *TailDest = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); // Decrement counter TailCounter = _Sub(TailCounter, _Constant(1)); // Store the counter so we don't have to deal with PHI here _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), TailCounter); auto SizeConst = _Constant(Size); auto NegSizeConst = _Constant(-Size); // Calculate direction. auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), SizeConst, NegSizeConst); // Offset the pointer TailDest = _Add(TailDest, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), TailDest); // Jump back to the start, we have more work to do _Jump(LoopHead); } // Make sure to start a new block after ending this one SetCurrentCodeBlock(LoopEnd); } void OpDispatchBuilder::MOVSOp(OpcodeArgs) { LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REPNE_PREFIX), "Can't handle REPNE on MOVS\n"); if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX) { auto Size = GetSrcSize(Op); // Create all our blocks auto LoopHead = CreateNewCodeBlock(); auto LoopTail = CreateNewCodeBlock(); auto LoopEnd = CreateNewCodeBlock(); // At the time this was written, our RA can't handle accessing nodes across blocks. // So we need to re-load and re-calculate essential values each iteration of the loop. // First thing we need to do is finish this block and jump to the start of the loop. _Jump(LoopHead); SetCurrentCodeBlock(LoopHead); { OrderedNode *Counter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); auto ZeroConst = _Constant(0); // Can we end the block? auto CanLeaveCond = _Select(FEXCore::IR::COND_EQ, Counter, ZeroConst, _Constant(1), ZeroConst); _CondJump(CanLeaveCond, LoopEnd, LoopTail); } SetCurrentCodeBlock(LoopTail); { OrderedNode *Src = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), GPRClass); OrderedNode *Dest = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); Src = _LoadMem(GPRClass, Size, Src, Size); // Store to memory where RDI points _StoreMem(GPRClass, Size, Dest, Src, Size); OrderedNode *TailCounter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); // Decrement counter TailCounter = _Sub(TailCounter, _Constant(1)); // Store the counter so we don't have to deal with PHI here _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), TailCounter); auto SizeConst = _Constant(Size); auto NegSizeConst = _Constant(-Size); // Calculate direction. auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), SizeConst, NegSizeConst); // Offset the pointer OrderedNode *TailSrc = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), GPRClass); OrderedNode *TailDest = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); TailSrc = _Add(TailSrc, PtrDir); TailDest = _Add(TailDest, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), TailSrc); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), TailDest); // Jump back to the start, we have more work to do _Jump(LoopHead); } // Make sure to start a new block after ending this one SetCurrentCodeBlock(LoopEnd); } else { auto Size = GetSrcSize(Op); OrderedNode *RSI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), GPRClass); OrderedNode *RDI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); auto Src = _LoadMem(GPRClass, Size, RSI, Size); // Store to memory where RDI points _StoreMem(GPRClass, Size, RDI, Src, Size); auto SizeConst = _Constant(Size); auto NegSizeConst = _Constant(-Size); // Calculate direction. auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), SizeConst, NegSizeConst); RSI = _Add(RSI, PtrDir); RDI = _Add(RDI, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), RSI); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), RDI); } } void OpDispatchBuilder::CMPSOp(OpcodeArgs) { LogMan::Throw::A(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX, "Can't only handle REP\n"); LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REPNE_PREFIX), "Can't only handle REP\n"); LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_ADDRESS_SIZE), "Can't handle adddress size\n"); LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX), "Can't handle FS\n"); LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX), "Can't handle GS\n"); auto Size = GetSrcSize(Op); auto JumpStart = _Jump(); // Make sure to start a new block after ending this one auto LoopStart = CreateNewCodeBlock(); SetJumpTarget(JumpStart, LoopStart); SetCurrentCodeBlock(LoopStart); OrderedNode *Counter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); // Can we end the block? OrderedNode *CanLeaveCond = _Select(FEXCore::IR::COND_EQ, Counter, _Constant(0), _Constant(1), _Constant(0)); auto CondJump = _CondJump(CanLeaveCond); IRPair<IROp_CondJump> InternalCondJump; auto LoopTail = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, LoopTail); SetCurrentCodeBlock(LoopTail); // Working loop { OrderedNode *Dest_RDI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); OrderedNode *Dest_RSI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), GPRClass); auto Src1 = _LoadMem(GPRClass, Size, Dest_RDI, Size); auto Src2 = _LoadMem(GPRClass, Size, Dest_RSI, Size); auto ALUOp = _Sub(Src1, Src2); GenerateFlags_SUB(Op, _Bfe(Size * 8, 0, ALUOp), _Bfe(Size * 8, 0, Src1), _Bfe(Size * 8, 0, Src2)); OrderedNode *TailCounter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); // Decrement counter TailCounter = _Sub(TailCounter, _Constant(1)); // Store the counter so we don't have to deal with PHI here _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), TailCounter); auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), _Constant(Size), _Constant(-Size)); // Offset the pointer Dest_RDI = _Add(Dest_RDI, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), Dest_RDI); // Offset second pointer Dest_RSI = _Add(Dest_RSI, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), Dest_RSI); OrderedNode *ZF = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); InternalCondJump = _CondJump(ZF); // Jump back to the start if we have more work to do SetTrueJumpTarget(InternalCondJump, LoopStart); } // Make sure to start a new block after ending this one auto LoopEnd = CreateNewCodeBlock(); SetTrueJumpTarget(CondJump, LoopEnd); SetFalseJumpTarget(InternalCondJump, LoopEnd); SetCurrentCodeBlock(LoopEnd); } void OpDispatchBuilder::SCASOp(OpcodeArgs) { LogMan::Throw::A(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REPNE_PREFIX, "Can only handle REPNE\n"); auto Size = GetSrcSize(Op); auto JumpStart = _Jump(); // Make sure to start a new block after ending this one auto LoopStart = CreateNewCodeBlock(); SetJumpTarget(JumpStart, LoopStart); SetCurrentCodeBlock(LoopStart); auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); OrderedNode *Counter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); // Can we end the block? OrderedNode *CanLeaveCond = _Select(FEXCore::IR::COND_EQ, Counter, ZeroConst, OneConst, ZeroConst); // We leave if RCX = 0 auto CondJump = _CondJump(CanLeaveCond); IRPair<IROp_CondJump> InternalCondJump; auto LoopTail = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, LoopTail); SetCurrentCodeBlock(LoopTail); // Working loop { OrderedNode *Dest_RDI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); auto Src1 = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto Src2 = _LoadMem(GPRClass, Size, Dest_RDI, Size); auto ALUOp = _Sub(Src1, Src2); GenerateFlags_SUB(Op, ALUOp, Src1, Src2); OrderedNode *TailCounter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); OrderedNode *TailDest_RDI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); // Decrement counter TailCounter = _Sub(TailCounter, _Constant(1)); // Store the counter so we don't have to deal with PHI here _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), TailCounter); auto SizeConst = _Constant(Size); auto NegSizeConst = _Constant(-Size); auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), SizeConst, NegSizeConst); // Offset the pointer TailDest_RDI = _Add(TailDest_RDI, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), TailDest_RDI); OrderedNode *ZF = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); InternalCondJump = _CondJump(ZF); // Jump back to the start if we have more work to do SetFalseJumpTarget(InternalCondJump, LoopStart); } // Make sure to start a new block after ending this one auto LoopEnd = CreateNewCodeBlock(); SetTrueJumpTarget(CondJump, LoopEnd); SetTrueJumpTarget(InternalCondJump, LoopEnd); SetCurrentCodeBlock(LoopEnd); } void OpDispatchBuilder::BSWAPOp(OpcodeArgs) { OrderedNode *Dest; if (GetSrcSize(Op) == 2) { // BSWAP of 16bit is undef. ZEN+ causes the lower 16bits to get zero'd Dest = _Constant(0); } else { Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Dest = _Rev(Dest); } StoreResult(GPRClass, Op, Dest, -1); } void OpDispatchBuilder::NEGOp(OpcodeArgs) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto ZeroConst = _Constant(0); auto ALUOp = _Sub(ZeroConst, Dest); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, ZeroConst), _Bfe(Size, 0, Dest)); } void OpDispatchBuilder::DIVOp(OpcodeArgs) { // This loads the divisor OrderedNode *Divisor = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op); if (Size == 1) { OrderedNode *Src1 = _LoadContext(2, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); auto UDivOp = _UDiv(Src1, Divisor); auto URemOp = _URem(Src1, Divisor); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]) + 1, URemOp); } else if (Size == 2) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LUDiv(Src1, Src2, Divisor); auto URemOp = _LURem(Src1, Src2, Divisor); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), URemOp); } else if (Size == 4) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LUDiv(Src1, Src2, Divisor); auto URemOp = _LURem(Src1, Src2, Divisor); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), _Zext(32, UDivOp)); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), _Zext(32, URemOp)); } else if (Size == 8) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LUDiv(Src1, Src2, Divisor); auto URemOp = _LURem(Src1, Src2, Divisor); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), URemOp); } } void OpDispatchBuilder::IDIVOp(OpcodeArgs) { // This loads the divisor OrderedNode *Divisor = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op); if (Size == 1) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); auto UDivOp = _Div(Src1, Divisor); auto URemOp = _Rem(Src1, Divisor); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]) + 1, URemOp); } else if (Size == 2) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LDiv(Src1, Src2, Divisor); auto URemOp = _LRem(Src1, Src2, Divisor); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), URemOp); } else if (Size == 4) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LDiv(Src1, Src2, Divisor); auto URemOp = _LRem(Src1, Src2, Divisor); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), _Zext(32, UDivOp)); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), _Zext(32, URemOp)); } else if (Size == 8) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LDiv(Src1, Src2, Divisor); auto URemOp = _LRem(Src1, Src2, Divisor); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), URemOp); } } void OpDispatchBuilder::BSFOp(OpcodeArgs) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // Find the LSB of this source auto Result = _FindLSB(Src); auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); // If Src was zero then the destination doesn't get modified auto SelectOp = _Select(FEXCore::IR::COND_EQ, Src, ZeroConst, Dest, Result); // ZF is set to 1 if the source was zero auto ZFSelectOp = _Select(FEXCore::IR::COND_EQ, Src, ZeroConst, OneConst, ZeroConst); StoreResult(GPRClass, Op, SelectOp, -1); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(ZFSelectOp); } void OpDispatchBuilder::BSROp(OpcodeArgs) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // Find the MSB of this source auto Result = _FindMSB(Src); auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); // If Src was zero then the destination doesn't get modified auto SelectOp = _Select(FEXCore::IR::COND_EQ, Src, ZeroConst, Dest, Result); // ZF is set to 1 if the source was zero auto ZFSelectOp = _Select(FEXCore::IR::COND_EQ, Src, ZeroConst, OneConst, ZeroConst); StoreResult(GPRClass, Op, SelectOp, -1); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(ZFSelectOp); } void OpDispatchBuilder::MOVAPSOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); StoreResult(FPRClass, Op, Src, -1); } void OpDispatchBuilder::MOVUPSOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, 1); StoreResult(FPRClass, Op, Src, 1); } void OpDispatchBuilder::MOVLHPSOp(OpcodeArgs) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, 8); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, 8); auto Result = _VInsElement(16, 8, 1, 0, Dest, Src); StoreResult(FPRClass, Op, Result, 8); } void OpDispatchBuilder::MOVHPDOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); // This instruction is a bit special that if the destination is a register then it'll ZEXT the 64bit source to 128bit if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // If the destination is a GPR then the source is memory // xmm1[127:64] = src OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, 16, Op->Flags, -1); auto Result = _VInsElement(16, 8, 1, 0, Dest, Src); StoreResult(FPRClass, Op, Result, -1); } else { // In this case memory is the destination and the high bits of the XMM are source // Mem64 = xmm1[127:64] auto Result = _VExtractToGPR(16, 8, Src, 1); StoreResult(GPRClass, Op, Result, -1); } } void OpDispatchBuilder::MOVLPOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, 8); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, 8, 16); auto Result = _VInsElement(16, 8, 0, 0, Dest, Src); StoreResult_WithOpSize(FPRClass, Op, Op->Dest, Result, 8, 16); } else { StoreResult_WithOpSize(FPRClass, Op, Op->Dest, Src, 8, 8); } } void OpDispatchBuilder::MOVSSOp(OpcodeArgs) { if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // MOVSS xmm1, xmm2 OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, 16, Op->Flags, -1); OrderedNode *Src = LoadSource_WithOpSize(FPRClass, Op, Op->Src[0], 4, Op->Flags, -1); auto Result = _VInsElement(16, 4, 0, 0, Dest, Src); StoreResult(FPRClass, Op, Result, -1); } else if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // MOVSS xmm1, mem32 // xmm1[127:0] <- zext(mem32) OrderedNode *Src = LoadSource_WithOpSize(FPRClass, Op, Op->Src[0], 4, Op->Flags, -1); Src = _Zext(32, Src); Src = _Zext(64, Src); StoreResult(FPRClass, Op, Src, -1); } else { // MOVSS mem32, xmm1 OrderedNode *Src = LoadSource_WithOpSize(FPRClass, Op, Op->Src[0], 4, Op->Flags, -1); StoreResult_WithOpSize(FPRClass, Op, Op->Dest, Src, 4, -1); } } void OpDispatchBuilder::MOVSDOp(OpcodeArgs) { if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // xmm1[63:0] <- xmm2[63:0] OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); auto Result = _VInsElement(16, 8, 0, 0, Dest, Src); StoreResult(FPRClass, Op, Result, -1); } else if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // xmm1[127:0] <- zext(mem64) OrderedNode *Src = LoadSource_WithOpSize(GPRClass, Op, Op->Src[0], 8, Op->Flags, -1); Src = _Zext(64, Src); StoreResult(FPRClass, Op, Src, -1); } else { // In this case memory is the destination and the low bits of the XMM are source // Mem64 = xmm2[63:0] OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); StoreResult_WithOpSize(FPRClass, Op, Op->Dest, Src, 8, -1); } } template<size_t ElementSize> void OpDispatchBuilder::PADDQOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VAdd(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PSUBQOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VSub(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PMINUOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VUMin(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PMAXUOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VUMax(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } void OpDispatchBuilder::PMINSWOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VSMin(Size, 2, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<FEXCore::IR::IROps IROp, size_t ElementSize> void OpDispatchBuilder::VectorALUOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VAdd(Size, ElementSize, Dest, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; StoreResult(FPRClass, Op, ALUOp, -1); } template<FEXCore::IR::IROps IROp, size_t ElementSize> void OpDispatchBuilder::VectorScalarALUOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); // If OpSize == ElementSize then it only does the lower scalar op auto ALUOp = _VAdd(ElementSize, ElementSize, Dest, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; // Insert the lower bits auto Result = _VInsElement(Size, ElementSize, 0, 0, Dest, ALUOp); StoreResult(FPRClass, Op, Result, -1); } template<FEXCore::IR::IROps IROp, size_t ElementSize, bool Scalar> void OpDispatchBuilder::VectorUnaryOp(OpcodeArgs) { auto Size = GetSrcSize(Op); if (Scalar) { Size = ElementSize; } OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VFSqrt(Size, ElementSize, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; if (Scalar) { // Insert the lower bits auto Result = _VInsElement(GetSrcSize(Op), ElementSize, 0, 0, Dest, ALUOp); StoreResult(FPRClass, Op, Result, -1); } else { StoreResult(FPRClass, Op, ALUOp, -1); } } void OpDispatchBuilder::MOVQOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); // This instruction is a bit special that if the destination is a register then it'll ZEXT the 64bit source to 128bit if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, xmm[Op->Dest.TypeGPR.GPR - FEXCore::X86State::REG_XMM_0][0]), Src); auto Const = _Constant(0); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, xmm[Op->Dest.TypeGPR.GPR - FEXCore::X86State::REG_XMM_0][1]), Const); } else { // This is simple, just store the result StoreResult(FPRClass, Op, Src, -1); } } template<size_t ElementSize> void OpDispatchBuilder::MOVMSKOp(OpcodeArgs) { auto Size = GetSrcSize(Op); uint8_t NumElements = Size / ElementSize; OrderedNode *CurrentVal = _Constant(0); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); for (unsigned i = 0; i < NumElements; ++i) { // Extract the top bit of the element OrderedNode *Tmp = _Bfe(1, ((i + 1) * (ElementSize * 8)) - 1, Src); // Shift it to the correct location Tmp = _Lshl(Tmp, _Constant(i)); // Or it with the current value CurrentVal = _Or(CurrentVal, Tmp); } StoreResult(GPRClass, Op, CurrentVal, -1); } template<size_t ElementSize> void OpDispatchBuilder::PUNPCKLOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); auto ALUOp = _VZip(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PUNPCKHOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); auto ALUOp = _VZip2(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize, bool Low> void OpDispatchBuilder::PSHUFDOp(OpcodeArgs) { LogMan::Throw::A(ElementSize != 0, "What. No element size?"); auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); uint8_t Shuffle = Op->Src[1].TypeLiteral.Literal; uint8_t NumElements = Size / ElementSize; // 16bit is a bit special of a shuffle // It only ever operates on half the register // Then there is a high and low variant of the instruction to determine where the destination goes // and where the source comes from if (ElementSize == 2) { NumElements /= 2; } uint8_t BaseElement = Low ? 0 : NumElements; auto Dest = Src; for (uint8_t Element = 0; Element < NumElements; ++Element) { Dest = _VInsElement(Size, ElementSize, BaseElement + Element, BaseElement + (Shuffle & 0b11), Dest, Src); Shuffle >>= 2; } StoreResult(FPRClass, Op, Dest, -1); } template<size_t ElementSize> void OpDispatchBuilder::SHUFOp(OpcodeArgs) { LogMan::Throw::A(ElementSize != 0, "What. No element size?"); auto Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); uint8_t Shuffle = Op->Src[1].TypeLiteral.Literal; uint8_t NumElements = Size / ElementSize; auto Dest = Src1; std::array<OrderedNode*, 4> Srcs = { }; for (int i = 0; i < (NumElements >> 1); ++i) { Srcs[i] = Src1; } for (int i = (NumElements >> 1); i < NumElements; ++i) { Srcs[i] = Src2; } // 32bit: // [31:0] = Src1[Selection] // [63:32] = Src1[Selection] // [95:64] = Src2[Selection] // [127:96] = Src2[Selection] // 64bit: // [63:0] = Src1[Selection] // [127:64] = Src2[Selection] uint8_t SelectionMask = NumElements - 1; uint8_t ShiftAmount = __builtin_popcount(SelectionMask); for (uint8_t Element = 0; Element < NumElements; ++Element) { Dest = _VInsElement(Size, ElementSize, Element, Shuffle & SelectionMask, Dest, Srcs[Element]); Shuffle >>= ShiftAmount; } StoreResult(FPRClass, Op, Dest, -1); } void OpDispatchBuilder::ANDNOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); // Dest = ~Src1 & Src2 Src1 = _VNot(Size, Size, Src1); auto Dest = _VAnd(Size, Size, Src1, Src2); StoreResult(FPRClass, Op, Dest, -1); } template<size_t ElementSize> void OpDispatchBuilder::PINSROp(OpcodeArgs) { auto Size = GetDstSize(Op); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, GetDstSize(Op), Op->Flags, -1); LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Index = Op->Src[1].TypeLiteral.Literal; // This maps 1:1 to an AArch64 NEON Op auto ALUOp = _VInsGPR(Size, ElementSize, Dest, Src, Index); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PCMPEQOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); // This maps 1:1 to an AArch64 NEON Op auto ALUOp = _VCMPEQ(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PCMPGTOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); // This maps 1:1 to an AArch64 NEON Op auto ALUOp = _VCMPGT(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } void OpDispatchBuilder::MOVDOp(OpcodeArgs) { if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Dest.TypeGPR.GPR >= FEXCore::X86State::REG_XMM_0) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // When destination is XMM then it is zext to 128bit uint64_t SrcSize = GetSrcSize(Op) * 8; while (SrcSize != 128) { Src = _Zext(SrcSize, Src); SrcSize *= 2; } StoreResult(FPRClass, Op, Op->Dest, Src, -1); } else { // Destination is GPR or mem // Extract from XMM first uint8_t ElementSize = 4; if (Op->Flags & X86Tables::DecodeFlags::FLAG_REX_WIDENING) ElementSize = 8; OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0],Op->Flags, -1); Src = _VExtractToGPR(GetSrcSize(Op), ElementSize, Src, 0); StoreResult(GPRClass, Op, Op->Dest, Src, -1); } } void OpDispatchBuilder::CMPXCHGOp(OpcodeArgs) { // CMPXCHG ModRM, reg, {RAX} // MemData = *ModRM.dest // if (RAX == MemData) // modRM.dest = reg; // ZF = 1 // else // ZF = 0 // RAX = MemData // // CASL Xs, Xt, Xn // MemData = *Xn // if (MemData == Xs) // *Xn = Xt // Xs = MemData auto Size = GetSrcSize(Op); // If this is a memory location then we want the pointer to it OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX) { Src1 = _Add(Src1, _LoadContext(8, offsetof(FEXCore::Core::CPUState, fs), GPRClass)); } else if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX) { Src1 = _Add(Src1, _LoadContext(8, offsetof(FEXCore::Core::CPUState, gs), GPRClass)); } // This is our source register OrderedNode *Src2 = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Src3 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); // 0x80014000 // 0x80064000 // 0x80064000 auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // If our destination is a GPR then this behaves differently // RAX = RAX == Op1 ? RAX : Op1 // AKA if they match then don't touch RAX value // Otherwise set it to the rm operand OrderedNode *RAXResult = _Select(FEXCore::IR::COND_EQ, Src1, Src3, Src3, Src1); // Op1 = RAX == Op1 ? Op2 : Op1 // If they match then set the rm operand to the input // else don't set the rm operand OrderedNode *DestResult = _Select(FEXCore::IR::COND_EQ, Src1, Src3, Src2, Src1); // ZF = RAX == Op1 ? 1 : 0 // Result of compare OrderedNode *ZFResult = _Select(FEXCore::IR::COND_EQ, Src1, Src3, OneConst, ZeroConst); // Set ZF SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(ZFResult); if (Size < 4) { _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), RAXResult); } else { if (Size == 4) { RAXResult = _Zext(32, RAXResult); } _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), RAXResult); } // Store in to GPR Dest // Have to make sure this is after the result store in RAX for when Dest == RAX StoreResult(GPRClass, Op, DestResult, -1); } else { // DataSrc = *Src1 // if (DataSrc == Src3) { *Src1 == Src2; } Src2 = DataSrc // This will write to memory! Careful! // Third operand must be a calculated guest memory address OrderedNode *CASResult = _CAS(Src3, Src2, Src1); // If our CASResult(OldMem value) is equal to our comparison // Then we managed to set the memory OrderedNode *ZFResult = _Select(FEXCore::IR::COND_EQ, CASResult, Src3, OneConst, ZeroConst); // RAX gets the result of the CAS op if (Size < 4) { _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), CASResult); } else { if (Size == 4) { CASResult = _Zext(32, CASResult); } _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), CASResult); } // Set ZF SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(ZFResult); } } OpDispatchBuilder::IRPair<IROp_CodeBlock> OpDispatchBuilder::CreateNewCodeBlock() { auto OldCursor = GetWriteCursor(); SetWriteCursor(CodeBlocks.back()); auto CodeNode = CreateCodeNode(); auto NewNode = _Dummy(); SetCodeNodeBegin(CodeNode, NewNode); auto EndBlock = _EndBlock(0); SetCodeNodeLast(CodeNode, EndBlock); if (CurrentCodeBlock) { LinkCodeBlocks(CurrentCodeBlock, CodeNode); } SetWriteCursor(OldCursor); return CodeNode; } void OpDispatchBuilder::SetCurrentCodeBlock(OrderedNode *Node) { CurrentCodeBlock = Node; LogMan::Throw::A(Node->Op(Data.Begin())->Op == OP_CODEBLOCK, "Node wasn't codeblock. It was '%s'", std::string(IR::GetName(Node->Op(Data.Begin())->Op)).c_str()); SetWriteCursor(Node->Op(Data.Begin())->CW<IROp_CodeBlock>()->Begin.GetNode(ListData.Begin())); } void OpDispatchBuilder::CreateJumpBlocks(std::vector<FEXCore::Frontend::Decoder::DecodedBlocks> const *Blocks) { OrderedNode *PrevCodeBlock{}; for (auto &Target : *Blocks) { auto CodeNode = CreateCodeNode(); auto NewNode = _Dummy(); SetCodeNodeBegin(CodeNode, NewNode); auto EndBlock = _EndBlock(0); SetCodeNodeLast(CodeNode, EndBlock); JumpTargets.try_emplace(Target.Entry, JumpTargetInfo{CodeNode, false}); if (PrevCodeBlock) { LinkCodeBlocks(PrevCodeBlock, CodeNode); } PrevCodeBlock = CodeNode; } } void OpDispatchBuilder::BeginFunction(uint64_t RIP, std::vector<FEXCore::Frontend::Decoder::DecodedBlocks> const *Blocks) { Entry = RIP; auto IRHeader = _IRHeader(InvalidNode, RIP, 0); CreateJumpBlocks(Blocks); auto Block = GetNewJumpBlock(RIP); SetCurrentCodeBlock(Block); IRHeader.first->Blocks = Block->Wrapped(ListData.Begin()); } void OpDispatchBuilder::Finalize() { // Node 0 is invalid node OrderedNode *RealNode = reinterpret_cast<OrderedNode*>(GetNode(1)); FEXCore::IR::IROp_Header *IROp = RealNode->Op(Data.Begin()); LogMan::Throw::A(IROp->Op == OP_IRHEADER, "First op in function must be our header"); // Let's walk the jump blocks and see if we have handled every block target for (auto &Handler : JumpTargets) { if (Handler.second.HaveEmitted) continue; // We haven't emitted. Dump out to the dispatcher SetCurrentCodeBlock(Handler.second.BlockEntry); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), _Constant(Handler.first)); _ExitFunction(); } CodeBlocks.clear(); } void OpDispatchBuilder::ExitFunction() { _ExitFunction(); } uint8_t OpDispatchBuilder::GetDstSize(FEXCore::X86Tables::DecodedOp Op) { constexpr std::array<uint8_t, 8> Sizes = { 0, // Invalid DEF 1, 2, 4, 8, 16, 32, 0, // Invalid DEF }; uint32_t DstSizeFlag = FEXCore::X86Tables::DecodeFlags::GetSizeDstFlags(Op->Flags); uint8_t Size = Sizes[DstSizeFlag]; LogMan::Throw::A(Size != 0, "Invalid destination size for op"); return Size; } uint8_t OpDispatchBuilder::GetSrcSize(FEXCore::X86Tables::DecodedOp Op) { constexpr std::array<uint8_t, 8> Sizes = { 0, // Invalid DEF 1, 2, 4, 8, 16, 32, 0, // Invalid DEF }; uint32_t SrcSizeFlag = FEXCore::X86Tables::DecodeFlags::GetSizeSrcFlags(Op->Flags); uint8_t Size = Sizes[SrcSizeFlag]; LogMan::Throw::A(Size != 0, "Invalid destination size for op"); return Size; } OrderedNode *OpDispatchBuilder::LoadSource_WithOpSize(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp const& Op, FEXCore::X86Tables::DecodedOperand const& Operand, uint8_t OpSize, uint32_t Flags, int8_t Align, bool LoadData, bool ForceLoad) { LogMan::Throw::A(Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_DIRECT || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_INDIRECT || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_RIP_RELATIVE || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_SIB , "Unsupported Src type"); OrderedNode *Src {nullptr}; bool LoadableType = false; if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL) { Src = _Constant(Operand.TypeLiteral.Size * 8, Operand.TypeLiteral.Literal); } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { if (Operand.TypeGPR.GPR >= FEXCore::X86State::REG_XMM_0) { Src = _LoadContext(OpSize, offsetof(FEXCore::Core::CPUState, xmm[Operand.TypeGPR.GPR - FEXCore::X86State::REG_XMM_0][Operand.TypeGPR.HighBits ? 1 : 0]), FPRClass); } else { Src = _LoadContext(OpSize, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]) + (Operand.TypeGPR.HighBits ? 1 : 0), GPRClass); } } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_DIRECT) { Src = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]), GPRClass); LoadableType = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_INDIRECT) { auto GPR = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPRIndirect.GPR]), GPRClass); auto Constant = _Constant(Operand.TypeGPRIndirect.Displacement); Src = _Add(GPR, Constant); LoadableType = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_RIP_RELATIVE) { Src = _Constant(Operand.TypeRIPLiteral.Literal + Op->PC + Op->InstSize); LoadableType = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_SIB) { OrderedNode *Tmp {}; if (Operand.TypeSIB.Index != FEXCore::X86State::REG_INVALID) { Tmp = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeSIB.Index]), GPRClass); if (Operand.TypeSIB.Scale != 1) { auto Constant = _Constant(Operand.TypeSIB.Scale); Tmp = _Mul(Tmp, Constant); } } if (Operand.TypeSIB.Base != FEXCore::X86State::REG_INVALID) { auto GPR = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeSIB.Base]), GPRClass); if (Tmp != nullptr) { Tmp = _Add(Tmp, GPR); } else { Tmp = GPR; } } if (Operand.TypeSIB.Offset) { if (Tmp != nullptr) { Src = _Add(Tmp, _Constant(Operand.TypeSIB.Offset)); } else { Src = _Constant(Operand.TypeSIB.Offset); } } else { if (Tmp != nullptr) { Src = Tmp; } else { Src = _Constant(0); } } LoadableType = true; } else { LogMan::Msg::A("Unknown Src Type: %d\n", Operand.TypeNone.Type); } if ((LoadableType && LoadData) || ForceLoad) { if (Flags & FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX) { Src = _Add(Src, _LoadContext(8, offsetof(FEXCore::Core::CPUState, fs), GPRClass)); } else if (Flags & FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX) { Src = _Add(Src, _LoadContext(8, offsetof(FEXCore::Core::CPUState, gs), GPRClass)); } Src = _LoadMem(Class, OpSize, Src, Align == -1 ? OpSize : Align); } return Src; } OrderedNode *OpDispatchBuilder::LoadSource(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp const& Op, FEXCore::X86Tables::DecodedOperand const& Operand, uint32_t Flags, int8_t Align, bool LoadData, bool ForceLoad) { uint8_t OpSize = GetSrcSize(Op); return LoadSource_WithOpSize(Class, Op, Operand, OpSize, Flags, Align, LoadData, ForceLoad); } void OpDispatchBuilder::StoreResult_WithOpSize(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp Op, FEXCore::X86Tables::DecodedOperand const& Operand, OrderedNode *const Src, uint8_t OpSize, int8_t Align) { LogMan::Throw::A((Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_DIRECT || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_INDIRECT || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_RIP_RELATIVE || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_SIB ), "Unsupported Dest type"); // 8Bit and 16bit destination types store their result without effecting the upper bits // 32bit ops ZEXT the result to 64bit OrderedNode *MemStoreDst {nullptr}; bool MemStore = false; if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL) { MemStoreDst = _Constant(Operand.TypeLiteral.Size * 8, Operand.TypeLiteral.Literal); MemStore = true; // Literals are ONLY hardcoded memory destinations } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { if (Operand.TypeGPR.GPR >= FEXCore::X86State::REG_XMM_0) { _StoreContext(Src, OpSize, offsetof(FEXCore::Core::CPUState, xmm[Operand.TypeGPR.GPR - FEXCore::X86State::REG_XMM_0][Operand.TypeGPR.HighBits ? 1 : 0]), Class); } else { if (OpSize == 4) { LogMan::Throw::A(!Operand.TypeGPR.HighBits, "Can't handle 32bit store to high 8bit register"); auto ZextOp = _Zext(Src, 32); _StoreContext(ZextOp, 8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]), Class); } else { _StoreContext(Src, std::min(static_cast<uint8_t>(8), OpSize), offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]) + (Operand.TypeGPR.HighBits ? 1 : 0), Class); } } } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_DIRECT) { MemStoreDst = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]), GPRClass); MemStore = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_INDIRECT) { auto GPR = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPRIndirect.GPR]), GPRClass); auto Constant = _Constant(Operand.TypeGPRIndirect.Displacement); MemStoreDst = _Add(GPR, Constant); MemStore = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_RIP_RELATIVE) { MemStoreDst = _Constant(Operand.TypeRIPLiteral.Literal + Op->PC + Op->InstSize); MemStore = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_SIB) { OrderedNode *Tmp {}; if (Operand.TypeSIB.Index != FEXCore::X86State::REG_INVALID) { Tmp = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeSIB.Index]), GPRClass); if (Operand.TypeSIB.Scale != 1) { auto Constant = _Constant(Operand.TypeSIB.Scale); Tmp = _Mul(Tmp, Constant); } } if (Operand.TypeSIB.Base != FEXCore::X86State::REG_INVALID) { auto GPR = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeSIB.Base]), GPRClass); if (Tmp != nullptr) { Tmp = _Add(Tmp, GPR); } else { Tmp = GPR; } } if (Operand.TypeSIB.Offset) { if (Tmp != nullptr) { MemStoreDst = _Add(Tmp, _Constant(Operand.TypeSIB.Offset)); } else { MemStoreDst = _Constant(Operand.TypeSIB.Offset); } } else { if (Tmp != nullptr) { MemStoreDst = Tmp; } else { MemStoreDst = _Constant(0); } } MemStore = true; } if (MemStore) { if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX) { MemStoreDst = _Add(MemStoreDst, _LoadContext(8, offsetof(FEXCore::Core::CPUState, fs), GPRClass)); } else if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX) { MemStoreDst = _Add(MemStoreDst, _LoadContext(8, offsetof(FEXCore::Core::CPUState, gs), GPRClass)); } if (OpSize == 10) { // For X87 extended doubles, split before storing _StoreMem(FPRClass, 8, MemStoreDst, Src, Align); auto Upper = _VExtractToGPR(16, 8, Src, 1); auto DestAddr = _Add(MemStoreDst, _Constant(8)); _StoreMem(GPRClass, 2, DestAddr, Upper, std::min<uint8_t>(Align, 8)); } else { _StoreMem(Class, OpSize, MemStoreDst, Src, Align == -1 ? OpSize : Align); } } } void OpDispatchBuilder::StoreResult(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp Op, FEXCore::X86Tables::DecodedOperand const& Operand, OrderedNode *const Src, int8_t Align) { StoreResult_WithOpSize(Class, Op, Operand, Src, GetDstSize(Op), Align); } void OpDispatchBuilder::StoreResult(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp Op, OrderedNode *const Src, int8_t Align) { StoreResult(Class, Op, Op->Dest, Src, Align); } OpDispatchBuilder::OpDispatchBuilder() : Data {8 * 1024 * 1024} , ListData {8 * 1024 * 1024} { ResetWorkingList(); } void OpDispatchBuilder::ResetWorkingList() { Data.Reset(); ListData.Reset(); CodeBlocks.clear(); JumpTargets.clear(); BlockSetRIP = false; CurrentWriteCursor = nullptr; // This is necessary since we do "null" pointer checks InvalidNode = reinterpret_cast<OrderedNode*>(ListData.Allocate(sizeof(OrderedNode))); DecodeFailure = false; ShouldDump = false; CurrentCodeBlock = nullptr; } template<unsigned BitOffset> void OpDispatchBuilder::SetRFLAG(OrderedNode *Value) { _StoreFlag(Value, BitOffset); } void OpDispatchBuilder::SetRFLAG(OrderedNode *Value, unsigned BitOffset) { _StoreFlag(Value, BitOffset); } OrderedNode *OpDispatchBuilder::GetRFLAG(unsigned BitOffset) { return _LoadFlag(BitOffset); } constexpr std::array<uint32_t, 17> FlagOffsets = { FEXCore::X86State::RFLAG_CF_LOC, FEXCore::X86State::RFLAG_PF_LOC, FEXCore::X86State::RFLAG_AF_LOC, FEXCore::X86State::RFLAG_ZF_LOC, FEXCore::X86State::RFLAG_SF_LOC, FEXCore::X86State::RFLAG_TF_LOC, FEXCore::X86State::RFLAG_IF_LOC, FEXCore::X86State::RFLAG_DF_LOC, FEXCore::X86State::RFLAG_OF_LOC, FEXCore::X86State::RFLAG_IOPL_LOC, FEXCore::X86State::RFLAG_NT_LOC, FEXCore::X86State::RFLAG_RF_LOC, FEXCore::X86State::RFLAG_VM_LOC, FEXCore::X86State::RFLAG_AC_LOC, FEXCore::X86State::RFLAG_VIF_LOC, FEXCore::X86State::RFLAG_VIP_LOC, FEXCore::X86State::RFLAG_ID_LOC, }; void OpDispatchBuilder::SetPackedRFLAG(bool Lower8, OrderedNode *Src) { uint8_t NumFlags = FlagOffsets.size(); if (Lower8) { NumFlags = 5; } auto OneConst = _Constant(1); for (int i = 0; i < NumFlags; ++i) { auto Tmp = _And(_Lshr(Src, _Constant(FlagOffsets[i])), OneConst); SetRFLAG(Tmp, FlagOffsets[i]); } } OrderedNode *OpDispatchBuilder::GetPackedRFLAG(bool Lower8) { OrderedNode *Original = _Constant(2); uint8_t NumFlags = FlagOffsets.size(); if (Lower8) { NumFlags = 5; } for (int i = 0; i < NumFlags; ++i) { OrderedNode *Flag = _LoadFlag(FlagOffsets[i]); Flag = _Zext(32, Flag); Flag = _Lshl(Flag, _Constant(FlagOffsets[i])); Original = _Or(Original, Flag); } return Original; } void OpDispatchBuilder::GenerateFlags_ADC(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2, OrderedNode *CF) { auto Size = GetSrcSize(Op) * 8; // AF { OrderedNode *AFRes = _Xor(_Xor(Src1, Src2), Res); AFRes = _Bfe(1, 4, AFRes); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(AFRes); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto PopCountOp = _Popcount(_And(Res, _Constant(0xFF))); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto Dst8 = _Bfe(Size, 0, Res); auto SelectOp = _Select(FEXCore::IR::COND_EQ, Dst8, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF // Unsigned { auto Dst8 = _Bfe(Size, 0, Res); auto Src8 = _Bfe(Size, 0, Src2); auto SelectOpLT = _Select(FEXCore::IR::COND_ULT, Dst8, Src8, _Constant(1), _Constant(0)); auto SelectOpLE = _Select(FEXCore::IR::COND_ULE, Dst8, Src8, _Constant(1), _Constant(0)); auto SelectCF = _Select(FEXCore::IR::COND_EQ, CF, _Constant(1), SelectOpLE, SelectOpLT); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectCF); } // OF // Signed { auto NegOne = _Constant(~0ULL); auto XorOp1 = _Xor(_Xor(Src1, Src2), NegOne); auto XorOp2 = _Xor(Res, Src1); OrderedNode *AndOp1 = _And(XorOp1, XorOp2); switch (Size) { case 8: AndOp1 = _Bfe(1, 7, AndOp1); break; case 16: AndOp1 = _Bfe(1, 15, AndOp1); break; case 32: AndOp1 = _Bfe(1, 31, AndOp1); break; case 64: AndOp1 = _Bfe(1, 63, AndOp1); break; default: LogMan::Msg::A("Unknown BFESize: %d", Size); break; } SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(AndOp1); } } void OpDispatchBuilder::GenerateFlags_SBB(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2, OrderedNode *CF) { // AF { OrderedNode *AFRes = _Xor(_Xor(Src1, Src2), Res); AFRes = _Bfe(1, 4, AFRes); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(AFRes); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto PopCountOp = _Popcount(_And(Res, _Constant(0xFF))); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto SelectOp = _Select(FEXCore::IR::COND_EQ, Res, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF // Unsigned { auto Dst8 = _Bfe(GetSrcSize(Op) * 8, 0, Res); auto Src8_1 = _Bfe(GetSrcSize(Op) * 8, 0, Src1); auto SelectOpLT = _Select(FEXCore::IR::COND_UGT, Dst8, Src8_1, _Constant(1), _Constant(0)); auto SelectOpLE = _Select(FEXCore::IR::COND_UGE, Dst8, Src8_1, _Constant(1), _Constant(0)); auto SelectCF = _Select(FEXCore::IR::COND_EQ, CF, _Constant(1), SelectOpLE, SelectOpLT); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectCF); } // OF // Signed { auto XorOp1 = _Xor(Src1, Src2); auto XorOp2 = _Xor(Res, Src1); OrderedNode *AndOp1 = _And(XorOp1, XorOp2); switch (GetSrcSize(Op)) { case 1: AndOp1 = _Bfe(1, 7, AndOp1); break; case 2: AndOp1 = _Bfe(1, 15, AndOp1); break; case 4: AndOp1 = _Bfe(1, 31, AndOp1); break; case 8: AndOp1 = _Bfe(1, 63, AndOp1); break; default: LogMan::Msg::A("Unknown BFESize: %d", GetSrcSize(Op)); break; } SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(AndOp1); } } void OpDispatchBuilder::GenerateFlags_SUB(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { // AF { OrderedNode *AFRes = _Xor(_Xor(Src1, Src2), Res); AFRes = _Bfe(1, 4, AFRes); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(AFRes); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto EightBitMask = _Constant(0xFF); auto PopCountOp = _Popcount(_And(Res, EightBitMask)); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); auto Bfe8 = _Bfe(GetSrcSize(Op) * 8, 0, Res); auto SelectOp = _Select(FEXCore::IR::COND_EQ, Bfe8, ZeroConst, OneConst, ZeroConst); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF { auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); auto SelectOp = _Select(FEXCore::IR::COND_ULT, Src1, Src2, OneConst, ZeroConst); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectOp); } // OF { auto XorOp1 = _Xor(Src1, Src2); auto XorOp2 = _Xor(Res, Src1); OrderedNode *FinalAnd = _And(XorOp1, XorOp2); switch (GetSrcSize(Op)) { case 1: FinalAnd = _Bfe(1, 7, FinalAnd); break; case 2: FinalAnd = _Bfe(1, 15, FinalAnd); break; case 4: FinalAnd = _Bfe(1, 31, FinalAnd); break; case 8: FinalAnd = _Bfe(1, 63, FinalAnd); break; default: LogMan::Msg::A("Unknown BFESize: %d", GetSrcSize(Op)); break; } SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(FinalAnd); } } void OpDispatchBuilder::GenerateFlags_ADD(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { // AF { OrderedNode *AFRes = _Xor(_Xor(Src1, Src2), Res); AFRes = _Bfe(1, 4, AFRes); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(AFRes); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto EightBitMask = _Constant(0xFF); auto PopCountOp = _Popcount(_And(Res, EightBitMask)); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto SelectOp = _Select(FEXCore::IR::COND_EQ, Res, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF { auto Dst8 = _Bfe(GetSrcSize(Op) * 8, 0, Res); auto Src8 = _Bfe(GetSrcSize(Op) * 8, 0, Src2); auto SelectOp = _Select(FEXCore::IR::COND_ULT, Dst8, Src8, _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectOp); } // OF { auto NegOne = _Constant(~0ULL); auto XorOp1 = _Xor(_Xor(Src1, Src2), NegOne); auto XorOp2 = _Xor(Res, Src1); OrderedNode *AndOp1 = _And(XorOp1, XorOp2); switch (GetSrcSize(Op)) { case 1: AndOp1 = _Bfe(1, 7, AndOp1); break; case 2: AndOp1 = _Bfe(1, 15, AndOp1); break; case 4: AndOp1 = _Bfe(1, 31, AndOp1); break; case 8: AndOp1 = _Bfe(1, 63, AndOp1); break; default: LogMan::Msg::A("Unknown BFESize: %d", GetSrcSize(Op)); break; } SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(AndOp1); } } void OpDispatchBuilder::GenerateFlags_MUL(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *High) { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); // PF/AF/ZF/SF // Undefined { SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(_Constant(0)); } // CF/OF { // CF and OF are set if the result of the operation can't be fit in to the destination register // If the value can fit then the top bits will be zero auto SignBit = _Ashr(Res, SignBitConst); auto SelectOp = _Select(FEXCore::IR::COND_EQ, High, SignBit, _Constant(0), _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectOp); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(SelectOp); } } void OpDispatchBuilder::GenerateFlags_UMUL(FEXCore::X86Tables::DecodedOp Op, OrderedNode *High) { // AF/SF/PF/ZF // Undefined { SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(_Constant(0)); } // CF/OF { // CF and OF are set if the result of the operation can't be fit in to the destination register // The result register will be all zero if it can't fit due to how multiplication behaves auto SelectOp = _Select(FEXCore::IR::COND_EQ, High, _Constant(0), _Constant(0), _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectOp); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(SelectOp); } } void OpDispatchBuilder::GenerateFlags_Logical(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { // AF { // Undefined // Set to zero anyway SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(_Constant(0)); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto EightBitMask = _Constant(0xFF); auto PopCountOp = _Popcount(_And(Res, EightBitMask)); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto SelectOp = _Select(FEXCore::IR::COND_EQ, Res, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF/OF { SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Constant(0)); } } void OpDispatchBuilder::GenerateFlags_Shift(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { auto CmpResult = _Select(FEXCore::IR::COND_EQ, Src2, _Constant(0), _Constant(1), _Constant(0)); auto CondJump = _CondJump(CmpResult); // Make sure to start a new block after ending this one auto JumpTarget = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, JumpTarget); SetCurrentCodeBlock(JumpTarget); // AF { // Undefined // Set to zero anyway SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(_Constant(0)); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto EightBitMask = _Constant(0xFF); auto PopCountOp = _Popcount(_And(Res, EightBitMask)); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto SelectOp = _Select(FEXCore::IR::COND_EQ, Res, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF/OF { SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Constant(0)); } auto Jump = _Jump(); auto NextJumpTarget = CreateNewCodeBlock(); SetJumpTarget(Jump, NextJumpTarget); SetTrueJumpTarget(CondJump, NextJumpTarget); SetCurrentCodeBlock(NextJumpTarget); } void OpDispatchBuilder::GenerateFlags_Rotate(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { // CF/OF // XXX: These are wrong { SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Constant(0)); } } void OpDispatchBuilder::UnhandledOp(OpcodeArgs) { DecodeFailure = true; } template<uint32_t SrcIndex> void OpDispatchBuilder::MOVGPROp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, 1); StoreResult(GPRClass, Op, Src, 1); } void OpDispatchBuilder::MOVVectorOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, 1); StoreResult(FPRClass, Op, Src, 1); } template<uint32_t SrcIndex> void OpDispatchBuilder::ALUOp(OpcodeArgs) { FEXCore::IR::IROps IROp; switch (Op->OP) { case 0x0: case 0x1: case 0x2: case 0x3: case 0x4: case 0x5: IROp = FEXCore::IR::IROps::OP_ADD; break; case 0x8: case 0x9: case 0xA: case 0xB: case 0xC: case 0xD: IROp = FEXCore::IR::IROps::OP_OR; break; case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: IROp = FEXCore::IR::IROps::OP_AND; break; case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: IROp = FEXCore::IR::IROps::OP_SUB; break; case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: IROp = FEXCore::IR::IROps::OP_XOR; break; default: IROp = FEXCore::IR::IROps::OP_LAST; LogMan::Msg::A("Unknown ALU Op: 0x%x", Op->OP); break; } // X86 basic ALU ops just do the operation between the destination and a single source OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Result{}; OrderedNode *Dest{}; if (DestIsLockedMem(Op)) { OrderedNode *DestMem = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); switch (IROp) { case FEXCore::IR::IROps::OP_ADD: { Dest = _AtomicFetchAdd(DestMem, Src, GetSrcSize(Op)); Result = _Add(Dest, Src); break; } case FEXCore::IR::IROps::OP_SUB: { Dest = _AtomicFetchSub(DestMem, Src, GetSrcSize(Op)); Result = _Sub(Dest, Src); break; } case FEXCore::IR::IROps::OP_OR: { Dest = _AtomicFetchOr(DestMem, Src, GetSrcSize(Op)); Result = _Or(Dest, Src); break; } case FEXCore::IR::IROps::OP_AND: { Dest = _AtomicFetchAnd(DestMem, Src, GetSrcSize(Op)); Result = _And(Dest, Src); break; } case FEXCore::IR::IROps::OP_XOR: { Dest = _AtomicFetchXor(DestMem, Src, GetSrcSize(Op)); Result = _Xor(Dest, Src); break; } default: LogMan::Msg::A("Unknown Atomic IR Op: %d", IROp); break; } } else { Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _Add(Dest, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; StoreResult(GPRClass, Op, ALUOp, -1); Result = ALUOp; } // Flags set { auto Size = GetSrcSize(Op) * 8; switch (IROp) { case FEXCore::IR::IROps::OP_ADD: GenerateFlags_ADD(Op, _Bfe(Size, 0, Result), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; case FEXCore::IR::IROps::OP_SUB: GenerateFlags_SUB(Op, _Bfe(Size, 0, Result), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; case FEXCore::IR::IROps::OP_MUL: GenerateFlags_MUL(Op, _Bfe(Size, 0, Result), _MulH(Dest, Src)); break; case FEXCore::IR::IROps::OP_AND: case FEXCore::IR::IROps::OP_XOR: case FEXCore::IR::IROps::OP_OR: { GenerateFlags_Logical(Op, _Bfe(Size, 0, Result), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; } default: break; } } } void OpDispatchBuilder::INTOp(OpcodeArgs) { uint8_t Reason{}; uint8_t Literal{}; bool setRIP = false; switch (Op->OP) { case 0xCD: Reason = 1; Literal = Op->Src[0].TypeLiteral.Literal; break; case 0xCE: Reason = 2; break; case 0xF1: Reason = 3; break; case 0xF4: { Reason = 4; setRIP = true; break; } case 0x0B: Reason = 5; case 0xCC: Reason = 6; setRIP = true; break; break; } if (setRIP) { BlockSetRIP = setRIP; // We want to set RIP to the next instruction after HLT/INT3 auto NewRIP = _Constant(Op->PC + Op->InstSize); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); } if (Op->OP == 0xCE) { // Conditional to only break if Overflow == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); // If condition doesn't hold then keep going auto CondJump = _CondJump(_Xor(Flag, _Constant(1))); auto FalseBlock = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, FalseBlock); SetCurrentCodeBlock(FalseBlock); _Break(Reason, Literal); // Make sure to start a new block after ending this one auto JumpTarget = CreateNewCodeBlock(); SetTrueJumpTarget(CondJump, JumpTarget); SetCurrentCodeBlock(JumpTarget); } else { _Break(Reason, Literal); } } template<size_t ElementSize, uint32_t SrcIndex> void OpDispatchBuilder::PSRLD(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op); auto Shift = _VUShr(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, Shift, -1); } template<size_t ElementSize> void OpDispatchBuilder::PSRLI(OpcodeArgs) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t ShiftConstant = Op->Src[1].TypeLiteral.Literal; auto Size = GetSrcSize(Op); auto Shift = _VUShrI(Size, ElementSize, Dest, ShiftConstant); StoreResult(FPRClass, Op, Shift, -1); } template<size_t ElementSize> void OpDispatchBuilder::PSLLI(OpcodeArgs) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t ShiftConstant = Op->Src[1].TypeLiteral.Literal; auto Size = GetSrcSize(Op); auto Shift = _VShlI(Size, ElementSize, Dest, ShiftConstant); StoreResult(FPRClass, Op, Shift, -1); } template<size_t ElementSize, bool Scalar, uint32_t SrcIndex> void OpDispatchBuilder::PSLL(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); OrderedNode *Result{}; if (Scalar) { Result = _VUShlS(Size, ElementSize, Dest, Src); } else { Result = _VUShl(Size, ElementSize, Dest, Src); } StoreResult(FPRClass, Op, Result, -1); } template<size_t ElementSize, bool Scalar, uint32_t SrcIndex> void OpDispatchBuilder::PSRAOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); OrderedNode *Result{}; if (Scalar) { Result = _VSShrS(Size, ElementSize, Dest, Src); } else { Result = _VSShr(Size, ElementSize, Dest, Src); } StoreResult(FPRClass, Op, Result, -1); } void OpDispatchBuilder::PSRLDQ(OpcodeArgs) { LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Shift = Op->Src[1].TypeLiteral.Literal; OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); auto Result = _VSRI(Size, 16, Dest, Shift); StoreResult(FPRClass, Op, Result, -1); } void OpDispatchBuilder::PSLLDQ(OpcodeArgs) { LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Shift = Op->Src[1].TypeLiteral.Literal; OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); auto Result = _VSLI(Size, 16, Dest, Shift); StoreResult(FPRClass, Op, Result, -1); } template<size_t ElementSize> void OpDispatchBuilder::PSRAIOp(OpcodeArgs) { LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Shift = Op->Src[1].TypeLiteral.Literal; OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); auto Result = _VSShrI(Size, ElementSize, Dest, Shift); StoreResult(FPRClass, Op, Result, -1); } void OpDispatchBuilder::MOVDDUPOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Res = _SplatVector2(Src); StoreResult(FPRClass, Op, Res, -1); } template<size_t DstElementSize, bool Signed> void OpDispatchBuilder::CVT(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); if (Op->Flags & X86Tables::DecodeFlags::FLAG_REX_WIDENING) { // Source is 64bit if (DstElementSize == 4) { Src = _Bfe(32, 0, Src); } } else { // Source is 32bit if (DstElementSize == 8) { if (Signed) Src = _Sext(32, Src); else Src = _Zext(32, Src); } } if (Signed) Src = _SCVTF(Src, DstElementSize); else Src = _UCVTF(Src, DstElementSize); OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, 16, Op->Flags, -1); Src = _VInsElement(16, DstElementSize, 0, 0, Dest, Src); StoreResult(FPRClass, Op, Src, -1); } template<size_t SrcElementSize, bool Signed> void OpDispatchBuilder::FCVT(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); if (Signed) Src = _FCVTZS(Src, SrcElementSize); else Src = _FCVTZU(Src, SrcElementSize); StoreResult_WithOpSize(GPRClass, Op, Op->Dest, Src, SrcElementSize, -1); } template<size_t SrcElementSize, bool Signed, bool Widen> void OpDispatchBuilder::VFCVT(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); size_t ElementSize = SrcElementSize; size_t Size = GetDstSize(Op); if (Widen) { Src = _VSXTL(Src, Size, ElementSize); ElementSize <<= 1; } if (Signed) Src = _VSCVTF(Src, Size, ElementSize); else Src = _VUCVTF(Src, Size, ElementSize); StoreResult(FPRClass, Op, Src, -1); } template<size_t DstElementSize, size_t SrcElementSize> void OpDispatchBuilder::FCVTF(OpcodeArgs) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); Src = _FCVTF(Src, DstElementSize, SrcElementSize); Src = _VInsElement(16, DstElementSize, 0, 0, Dest, Src); StoreResult(FPRClass, Op, Src, -1); } template<size_t DstElementSize, size_t SrcElementSize> void OpDispatchBuilder::VFCVTF(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); size_t Size = GetDstSize(Op); if (DstElementSize > SrcElementSize) { Src = _VFCVTL(Src, Size, SrcElementSize); } else { Src = _VFCVTN(Src, Size, SrcElementSize); } StoreResult(FPRClass, Op, Src, -1); } void OpDispatchBuilder::TZCNT(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); Src = _FindTrailingZeros(Src); StoreResult(GPRClass, Op, Src, -1); } template<size_t ElementSize, bool Scalar> void OpDispatchBuilder::VFCMPOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, GetDstSize(Op), Op->Flags, -1); uint8_t CompType = Op->Src[1].TypeLiteral.Literal; OrderedNode *Result{}; // This maps 1:1 to an AArch64 NEON Op //auto ALUOp = _VCMPGT(Size, ElementSize, Dest, Src); switch (CompType) { case 0x00: case 0x08: case 0x10: case 0x18: // EQ Result = _VFCMPEQ(Size, ElementSize, Dest, Src); break; case 0x01: case 0x09: case 0x11: case 0x19: // LT, GT(Swapped operand) Result = _VFCMPLT(Size, ElementSize, Dest, Src); break; case 0x02: case 0x0A: case 0x12: case 0x1A: // LE, GE(Swapped operand) Result = _VFCMPLE(Size, ElementSize, Dest, Src); break; case 0x04: case 0x0C: case 0x14: case 0x1C: // NEQ Result = _VFCMPNEQ(Size, ElementSize, Dest, Src); break; case 0x05: case 0x0D: case 0x15: case 0x1D: // NLT, NGT(Swapped operand) Result = _VFCMPLE(Size, ElementSize, Src, Dest); break; case 0x06: case 0x0E: case 0x16: case 0x1E: // NLE, NGE(Swapped operand) Result = _VFCMPLT(Size, ElementSize, Src, Dest); break; default: LogMan::Msg::A("Unknown Comparison type: %d", CompType); } if (Scalar) { // Insert the lower bits Result = _VInsElement(GetDstSize(Op), ElementSize, 0, 0, Dest, Result); } StoreResult(FPRClass, Op, Result, -1); } OrderedNode *OpDispatchBuilder::GetX87Top() { // Yes, we are storing 3 bits in a single flag register. // Deal with it return _LoadContext(1, offsetof(FEXCore::Core::CPUState, flags) + FEXCore::X86State::X87FLAG_TOP_LOC, GPRClass); } void OpDispatchBuilder::SetX87Top(OrderedNode *Value) { _StoreContext(Value, 1, offsetof(FEXCore::Core::CPUState, flags) + FEXCore::X86State::X87FLAG_TOP_LOC, GPRClass); } template<size_t width> void OpDispatchBuilder::FLD(OpcodeArgs) { // Update TOP auto orig_top = GetX87Top(); auto top = _And(_Sub(orig_top, _Constant(1)), _Constant(7)); SetX87Top(top); size_t read_width = (width == 80) ? 16 : width / 8; // Read from memory auto data = LoadSource_WithOpSize(GPRClass, Op, Op->Src[0], read_width, Op->Flags, -1); OrderedNode *converted; // Convert to 80bit float if (width == 32 || width == 64) { _Zext(32, data); if (width == 32) data = _Zext(32, data); constexpr size_t mantissa_bits = (width == 32) ? 23 : 52; constexpr size_t sign_bits = width - (mantissa_bits + 1); uint64_t sign_mask = (width == 32) ? 0x80000000 : 0x8000000000000000; uint64_t exponent_mask = (width == 32) ? 0x7F800000 : 0x7FE0000000000000; uint64_t lower_mask = (width == 32) ? 0x007FFFFF : 0x001FFFFFFFFFFFFF; auto sign = _Lshr(_And(data, _Constant(sign_mask)), _Constant(width - 16)); auto exponent = _Lshr(_And(data, _Constant(exponent_mask)), _Constant(mantissa_bits)); auto lower = _Lshl(_And(data, _Constant(lower_mask)), _Constant(63 - mantissa_bits)); // XXX: Need to handle NaN/Infinities constexpr size_t exponent_zero = (1 << (sign_bits-1)); auto adjusted_exponent = _Add(exponent, _Constant(0x4000 - exponent_zero)); auto upper = _Or(sign, adjusted_exponent); // XXX: Need to support decoding of denormals auto intergerBit = _Constant(1ULL << 63); converted = _VCastFromGPR(16, 8, _Or(intergerBit, lower)); converted = _VInsElement(16, 8, 1, 0, converted, _VCastFromGPR(16, 8, upper)); } else if (width == 80) { // TODO } // Write to ST[TOP] _StoreContextIndexed(converted, top, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); //_StoreContext(converted, 16, offsetof(FEXCore::Core::CPUState, mm[7][0])); } template<size_t width, bool pop> void OpDispatchBuilder::FST(OpcodeArgs) { auto orig_top = GetX87Top(); if (width == 80) { auto data = _LoadContextIndexed(orig_top, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); StoreResult_WithOpSize(FPRClass, Op, Op->Dest, data, 10, 1); } // TODO: Other widths if (pop) { auto top = _And(_Add(orig_top, _Constant(1)), _Constant(7)); SetX87Top(top); } } void OpDispatchBuilder::FADD(OpcodeArgs) { auto top = GetX87Top(); OrderedNode* arg; auto mask = _Constant(7); if (Op->Src[0].TypeNone.Type != 0) { // Memory arg arg = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); } else { // Implicit arg auto offset = _Constant(Op->OP & 7); arg = _And(_Add(top, offset), mask); } auto a = _LoadContextIndexed(top, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); auto b = _LoadContextIndexed(arg, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); // _StoreContext(a, 16, offsetof(FEXCore::Core::CPUState, mm[0][0])); // _StoreContext(b, 16, offsetof(FEXCore::Core::CPUState, mm[1][0])); auto ExponentMask = _Constant(0x7FFF); //auto result = _F80Add(a, b); // TODO: Handle sign and negative additions. // TODO: handle NANs (and other weird numbers?) auto a_Exponent = _And(_VExtractToGPR(16, 8, a, 1), ExponentMask); auto b_Exponent = _And(_VExtractToGPR(16, 8, b, 1), ExponentMask); auto shift = _Sub(a_Exponent, b_Exponent); auto zero = _Constant(0); auto ExponentLarger = _Select(COND_ULT, shift, zero, a_Exponent, b_Exponent); auto a_Mantissa = _VExtractToGPR(16, 8, a, 0); auto b_Mantissa = _VExtractToGPR(16, 8, b, 0); auto MantissaLarger = _Select(COND_ULT, shift, zero, a_Mantissa, b_Mantissa); auto MantissaSmaller = _Select(COND_ULT, shift, zero, b_Mantissa, a_Mantissa); auto invertedShift = _Select(COND_ULT, shift, zero, _Neg(shift), shift); auto MantissaSmallerShifted = _Lshr(MantissaSmaller, invertedShift); auto MantissaSummed = _Add(MantissaLarger, MantissaSmallerShifted); auto one = _Constant(1); // Hacky way to detect overflow and adjust auto ExponentAdjusted = _Select(COND_ULT, MantissaLarger, MantissaSummed, ExponentLarger, _Add(ExponentLarger, one)); auto MantissaShifted = _Or(_Constant(1ULL << 63), _Lshr(MantissaSummed, one)); auto MantissaAdjusted = _Select(COND_ULT, MantissaLarger, MantissaSummed, MantissaSummed, MantissaShifted); // TODO: Rounding, Infinities, exceptions, precision, tags? auto lower = _VCastFromGPR(16, 8, MantissaAdjusted); auto upper = _VCastFromGPR(16, 8, ExponentAdjusted); auto result = _VInsElement(16, 8, 1, 0, lower, upper); if ((Op->TableInfo->Flags & X86Tables::InstFlags::FLAGS_POP) != 0) { top = _And(_Add(top, one), mask); SetX87Top(top); } // Write to ST[TOP] _StoreContextIndexed(result, top, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); } void OpDispatchBuilder::FXSaveOp(OpcodeArgs) { OrderedNode *Mem = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); // Saves 512bytes to the memory location provided // Header changes depending on if REX.W is set or not if (Op->Flags & X86Tables::DecodeFlags::FLAG_REX_WIDENING) { // BYTE | 0 1 | 2 3 | 4 | 5 | 6 7 | 8 9 | a b | c d | e f | // ------------------------------------------ // 00 | FCW | FSW | FTW | <R> | FOP | FIP | // 16 | FDP | MXCSR | MXCSR_MASK| } else { // BYTE | 0 1 | 2 3 | 4 | 5 | 6 7 | 8 9 | a b | c d | e f | // ------------------------------------------ // 00 | FCW | FSW | FTW | <R> | FOP | FIP[31:0] | FCS | <R> | // 16 | FDP[31:0] | FDS | <R> | MXCSR | MXCSR_MASK| } // BYTE | 0 1 | 2 3 | 4 | 5 | 6 7 | 8 9 | a b | c d | e f | // ------------------------------------------ // 32 | ST0/MM0 | <R> // 48 | ST1/MM1 | <R> // 64 | ST2/MM2 | <R> // 80 | ST3/MM3 | <R> // 96 | ST4/MM4 | <R> // 112 | ST5/MM5 | <R> // 128 | ST6/MM6 | <R> // 144 | ST7/MM7 | <R> // 160 | XMM0 // 173 | XMM1 // 192 | XMM2 // 208 | XMM3 // 224 | XMM4 // 240 | XMM5 // 256 | XMM6 // 272 | XMM7 // 288 | XMM8 // 304 | XMM9 // 320 | XMM10 // 336 | XMM11 // 352 | XMM12 // 368 | XMM13 // 384 | XMM14 // 400 | XMM15 // 416 | <R> // 432 | <R> // 448 | <R> // 464 | Available // 480 | Available // 496 | Available // FCW: x87 FPU control word // FSW: x87 FPU status word // FTW: x87 FPU Tag word (Abridged) // FOP: x87 FPU opcode. Lower 11 bits of the opcode // FIP: x87 FPU instructyion pointer offset // FCS: x87 FPU instruction pointer selector. If CPUID_0000_0007_0000_00000:EBX[bit 13] = 1 then this is deprecated and stores as 0 // FDP: x87 FPU instruction operand (data) pointer offset // FDS: x87 FPU instruction operand (data) pointer selector. Same deprecation as FCS // MXCSR: If OSFXSR bit in CR4 is not set then this may not be saved // MXCSR_MASK: Mask for writes to the MXCSR register // If OSFXSR bit in CR4 is not set than FXSAVE /may/ not save the XMM registers // This is implementation dependent for (unsigned i = 0; i < 8; ++i) { OrderedNode *MMReg = _LoadContext(16, offsetof(FEXCore::Core::CPUState, mm[i]), FPRClass); OrderedNode *MemLocation = _Add(Mem, _Constant(i * 16 + 32)); _StoreMem(FPRClass, 16, MemLocation, MMReg, 16); } for (unsigned i = 0; i < 16; ++i) { OrderedNode *XMMReg = _LoadContext(16, offsetof(FEXCore::Core::CPUState, xmm[i]), FPRClass); OrderedNode *MemLocation = _Add(Mem, _Constant(i * 16 + 160)); _StoreMem(FPRClass, 16, MemLocation, XMMReg, 16); } } void OpDispatchBuilder::FXRStoreOp(OpcodeArgs) { OrderedNode *Mem = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1, false); for (unsigned i = 0; i < 8; ++i) { OrderedNode *MemLocation = _Add(Mem, _Constant(i * 16 + 32)); auto MMReg = _LoadMem(FPRClass, 16, MemLocation, 16); _StoreContext(FPRClass, 16, offsetof(FEXCore::Core::CPUState, mm[i]), MMReg); } for (unsigned i = 0; i < 16; ++i) { OrderedNode *MemLocation = _Add(Mem, _Constant(i * 16 + 160)); auto XMMReg = _LoadMem(FPRClass, 16, MemLocation, 16); _StoreContext(FPRClass, 16, offsetof(FEXCore::Core::CPUState, xmm[i]), XMMReg); } } void OpDispatchBuilder::PAlignrOp(OpcodeArgs) { OrderedNode *Src1 = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); uint8_t Index = Op->Src[1].TypeLiteral.Literal; OrderedNode *Res = _VExtr(GetDstSize(Op), 1, Src1, Src2, Index); StoreResult(FPRClass, Op, Res, -1); } void OpDispatchBuilder::LDMXCSR(OpcodeArgs) { } void OpDispatchBuilder::STMXCSR(OpcodeArgs) { // Default MXCSR StoreResult(GPRClass, Op, _Constant(0x1F80), -1); } template<size_t ElementSize> void OpDispatchBuilder::PACKUSOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Res = _VSQXTUN(Size, ElementSize, Dest); Res = _VSQXTUN2(Size, ElementSize, Res, Src); StoreResult(FPRClass, Op, Res, -1); } template<size_t ElementSize, bool Signed> void OpDispatchBuilder::PMULOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode* Srcs1[2]{}; OrderedNode* Srcs2[2]{}; Srcs1[0] = _VExtr(Size, ElementSize, Src1, Src1, 0); Srcs1[1] = _VExtr(Size, ElementSize, Src1, Src1, 2); Srcs2[0] = _VExtr(Size, ElementSize, Src2, Src2, 0); Srcs2[1] = _VExtr(Size, ElementSize, Src2, Src2, 2); Src1 = _VInsElement(Size, ElementSize, 1, 0, Srcs1[0], Srcs1[1]); Src2 = _VInsElement(Size, ElementSize, 1, 0, Srcs2[0], Srcs2[1]); OrderedNode *Res{}; if (Signed) { Res = _VSMull(Size, ElementSize, Src1, Src2); } else { Res = _VUMull(Size, ElementSize, Src1, Src2); } StoreResult(FPRClass, Op, Res, -1); } void OpDispatchBuilder::UnimplementedOp(OpcodeArgs) { // We don't actually support this instruction // Multiblock may hit it though _Break(0, 0); } #undef OpcodeArgs void OpDispatchBuilder::ReplaceAllUsesWithInclusive(OrderedNode *Node, OrderedNode *NewNode, IR::NodeWrapperIterator After, IR::NodeWrapperIterator End) { uintptr_t ListBegin = ListData.Begin(); uintptr_t DataBegin = Data.Begin(); while (After != End) { OrderedNodeWrapper *WrapperOp = After(); OrderedNode *RealNode = WrapperOp->GetNode(ListBegin); FEXCore::IR::IROp_Header *IROp = RealNode->Op(DataBegin); uint8_t NumArgs = IR::GetArgs(IROp->Op); for (uint8_t i = 0; i < NumArgs; ++i) { if (IROp->Args[i].ID() == Node->Wrapped(ListBegin).ID()) { Node->RemoveUse(); NewNode->AddUse(); IROp->Args[i].NodeOffset = NewNode->Wrapped(ListBegin).NodeOffset; } } ++After; } } void OpDispatchBuilder::RemoveArgUses(OrderedNode *Node) { uintptr_t ListBegin = ListData.Begin(); uintptr_t DataBegin = Data.Begin(); FEXCore::IR::IROp_Header *IROp = Node->Op(DataBegin); uint8_t NumArgs = IR::GetArgs(IROp->Op); for (uint8_t i = 0; i < NumArgs; ++i) { auto ArgNode = IROp->Args[i].GetNode(ListBegin); ArgNode->RemoveUse(); } } void OpDispatchBuilder::Remove(OrderedNode *Node) { RemoveArgUses(Node); Node->Unlink(ListData.Begin()); } void InstallOpcodeHandlers() { const std::vector<std::tuple<uint8_t, uint8_t, X86Tables::OpDispatchPtr>> BaseOpTable = { // Instructions {0x00, 1, &OpDispatchBuilder::ALUOp<0>}, {0x01, 1, &OpDispatchBuilder::ALUOp<0>}, {0x02, 1, &OpDispatchBuilder::ALUOp<0>}, {0x03, 1, &OpDispatchBuilder::ALUOp<0>}, {0x04, 1, &OpDispatchBuilder::ALUOp<0>}, {0x05, 1, &OpDispatchBuilder::ALUOp<0>}, {0x08, 1, &OpDispatchBuilder::ALUOp<0>}, {0x09, 1, &OpDispatchBuilder::ALUOp<0>}, {0x0A, 1, &OpDispatchBuilder::ALUOp<0>}, {0x0B, 1, &OpDispatchBuilder::ALUOp<0>}, {0x0C, 1, &OpDispatchBuilder::ALUOp<0>}, {0x0D, 1, &OpDispatchBuilder::ALUOp<0>}, {0x10, 1, &OpDispatchBuilder::ADCOp<0>}, {0x11, 1, &OpDispatchBuilder::ADCOp<0>}, {0x12, 1, &OpDispatchBuilder::ADCOp<0>}, {0x13, 1, &OpDispatchBuilder::ADCOp<0>}, {0x14, 1, &OpDispatchBuilder::ADCOp<0>}, {0x15, 1, &OpDispatchBuilder::ADCOp<0>}, {0x18, 1, &OpDispatchBuilder::SBBOp<0>}, {0x19, 1, &OpDispatchBuilder::SBBOp<0>}, {0x1A, 1, &OpDispatchBuilder::SBBOp<0>}, {0x1B, 1, &OpDispatchBuilder::SBBOp<0>}, {0x1C, 1, &OpDispatchBuilder::SBBOp<0>}, {0x1D, 1, &OpDispatchBuilder::SBBOp<0>}, {0x20, 1, &OpDispatchBuilder::ALUOp<0>}, {0x21, 1, &OpDispatchBuilder::ALUOp<0>}, {0x22, 1, &OpDispatchBuilder::ALUOp<0>}, {0x23, 1, &OpDispatchBuilder::ALUOp<0>}, {0x24, 1, &OpDispatchBuilder::ALUOp<0>}, {0x25, 1, &OpDispatchBuilder::ALUOp<0>}, {0x28, 1, &OpDispatchBuilder::ALUOp<0>}, {0x29, 1, &OpDispatchBuilder::ALUOp<0>}, {0x2A, 1, &OpDispatchBuilder::ALUOp<0>}, {0x2B, 1, &OpDispatchBuilder::ALUOp<0>}, {0x2C, 1, &OpDispatchBuilder::ALUOp<0>}, {0x2D, 1, &OpDispatchBuilder::ALUOp<0>}, {0x30, 1, &OpDispatchBuilder::ALUOp<0>}, {0x31, 1, &OpDispatchBuilder::ALUOp<0>}, {0x32, 1, &OpDispatchBuilder::ALUOp<0>}, {0x33, 1, &OpDispatchBuilder::ALUOp<0>}, {0x34, 1, &OpDispatchBuilder::ALUOp<0>}, {0x35, 1, &OpDispatchBuilder::ALUOp<0>}, {0x38, 6, &OpDispatchBuilder::CMPOp<0>}, {0x50, 8, &OpDispatchBuilder::PUSHOp}, {0x58, 8, &OpDispatchBuilder::POPOp}, {0x63, 1, &OpDispatchBuilder::MOVSXDOp}, {0x68, 1, &OpDispatchBuilder::PUSHOp}, {0x69, 1, &OpDispatchBuilder::IMUL2SrcOp}, {0x6A, 1, &OpDispatchBuilder::PUSHOp}, {0x6B, 1, &OpDispatchBuilder::IMUL2SrcOp}, {0x70, 16, &OpDispatchBuilder::CondJUMPOp}, {0x84, 2, &OpDispatchBuilder::TESTOp<0>}, {0x86, 2, &OpDispatchBuilder::XCHGOp}, {0x88, 4, &OpDispatchBuilder::MOVGPROp<0>}, {0x8D, 1, &OpDispatchBuilder::LEAOp}, {0x90, 8, &OpDispatchBuilder::XCHGOp}, {0x98, 1, &OpDispatchBuilder::CDQOp}, {0x99, 1, &OpDispatchBuilder::CQOOp}, {0x9E, 1, &OpDispatchBuilder::SAHFOp}, {0x9F, 1, &OpDispatchBuilder::LAHFOp}, {0xA0, 4, &OpDispatchBuilder::MOVOffsetOp}, {0xA4, 2, &OpDispatchBuilder::MOVSOp}, {0xA6, 2, &OpDispatchBuilder::CMPSOp}, {0xA8, 2, &OpDispatchBuilder::TESTOp<0>}, {0xAA, 2, &OpDispatchBuilder::STOSOp}, {0xAE, 2, &OpDispatchBuilder::SCASOp}, {0xB0, 16, &OpDispatchBuilder::MOVGPROp<0>}, {0xC2, 2, &OpDispatchBuilder::RETOp}, {0xC9, 1, &OpDispatchBuilder::LEAVEOp}, {0xCC, 2, &OpDispatchBuilder::INTOp}, {0xE8, 1, &OpDispatchBuilder::CALLOp}, {0xE9, 1, &OpDispatchBuilder::JUMPOp}, {0xEB, 1, &OpDispatchBuilder::JUMPOp}, {0xF1, 1, &OpDispatchBuilder::INTOp}, {0xF4, 1, &OpDispatchBuilder::INTOp}, {0xF5, 1, &OpDispatchBuilder::FLAGControlOp}, {0xF8, 2, &OpDispatchBuilder::FLAGControlOp}, {0xFC, 2, &OpDispatchBuilder::FLAGControlOp}, }; const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> TwoByteOpTable = { // Instructions {0x00, 1, nullptr}, // GROUP 6 {0x01, 1, nullptr}, // GROUP 7 {0x05, 1, &OpDispatchBuilder::SyscallOp}, {0x0B, 1, &OpDispatchBuilder::INTOp}, {0x0D, 1, nullptr}, // GROUP P {0x18, 1, nullptr}, // GROUP 16 {0x19, 7, &OpDispatchBuilder::NOPOp}, // NOP with ModRM {0x31, 1, &OpDispatchBuilder::RDTSCOp}, {0x40, 16, &OpDispatchBuilder::CMOVOp}, {0x6E, 1, &OpDispatchBuilder::UnhandledOp}, // MOVD {0x7E, 1, &OpDispatchBuilder::UnhandledOp}, // MOVD {0x80, 16, &OpDispatchBuilder::CondJUMPOp}, // XXX: Fails to fixup some jumps {0x90, 16, &OpDispatchBuilder::SETccOp}, // XXX: Causes some unit tests to fail due to flags being incorrect {0xA2, 1, &OpDispatchBuilder::CPUIDOp}, {0xA3, 1, &OpDispatchBuilder::BTOp<0>}, // BT {0xA4, 2, &OpDispatchBuilder::SHLDOp}, {0xAB, 1, &OpDispatchBuilder::BTSOp<0>}, {0xAC, 2, &OpDispatchBuilder::SHRDOp}, {0xAF, 1, &OpDispatchBuilder::IMUL1SrcOp}, // XXX: Causes issues with LLVM JIT {0xB0, 2, &OpDispatchBuilder::CMPXCHGOp}, // CMPXCHG {0xB3, 1, &OpDispatchBuilder::BTROp<0>}, {0xB6, 2, &OpDispatchBuilder::MOVZXOp}, {0xBB, 1, &OpDispatchBuilder::BTCOp<0>}, {0xBC, 1, &OpDispatchBuilder::BSFOp}, // BSF {0xBD, 1, &OpDispatchBuilder::BSROp}, // BSF {0xBE, 2, &OpDispatchBuilder::MOVSXOp}, {0xC0, 2, &OpDispatchBuilder::XADDOp}, {0xC8, 8, &OpDispatchBuilder::BSWAPOp}, // SSE // XXX: Broken on LLVM? {0x10, 2, &OpDispatchBuilder::MOVUPSOp}, {0x12, 2, &OpDispatchBuilder::MOVLPOp}, {0x14, 1, &OpDispatchBuilder::PUNPCKLOp<4>}, {0x15, 1, &OpDispatchBuilder::PUNPCKHOp<4>}, {0x16, 1, &OpDispatchBuilder::MOVLHPSOp}, {0x17, 1, &OpDispatchBuilder::MOVUPSOp}, {0x28, 2, &OpDispatchBuilder::MOVUPSOp}, {0x50, 1, &OpDispatchBuilder::MOVMSKOp<4>}, {0x54, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VAND, 16>}, {0x55, 1, &OpDispatchBuilder::ANDNOp}, {0x56, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VOR, 16>}, {0x57, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VXOR, 16>}, {0x58, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFADD, 4>}, {0x59, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMUL, 4>}, {0x5A, 1, &OpDispatchBuilder::VFCVTF<8, 4>}, {0x5B, 1, &OpDispatchBuilder::FCVT<4, true>}, {0x5C, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFSUB, 4>}, {0x5D, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMIN, 4>}, {0x5E, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFDIV, 4>}, {0x5F, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMAX, 4>}, {0x71, 1, nullptr}, // GROUP 12 {0x72, 1, nullptr}, // GROUP 13 {0x73, 1, nullptr}, // GROUP 14 {0xAE, 1, nullptr}, // GROUP 15 {0xB9, 1, nullptr}, // GROUP 10 {0xBA, 1, nullptr}, // GROUP 8 {0xC2, 1, &OpDispatchBuilder::VFCMPOp<4, false>}, {0xC6, 1, &OpDispatchBuilder::SHUFOp<4>}, {0xC7, 1, nullptr}, // GROUP 9 }; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> PrimaryGroupOpTable = { // GROUP 1 // XXX: Something in this group causing bad syscall when commented out {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 0), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 1), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 2), 1, &OpDispatchBuilder::ADCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 3), 1, &OpDispatchBuilder::SBBOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 4), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 5), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 6), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 7), 1, &OpDispatchBuilder::CMPOp<1>}, // CMP {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 0), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 1), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 2), 1, &OpDispatchBuilder::ADCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 3), 1, &OpDispatchBuilder::SBBOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 4), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 5), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 6), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 7), 1, &OpDispatchBuilder::CMPOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 0), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 1), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 2), 1, &OpDispatchBuilder::ADCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 3), 1, &OpDispatchBuilder::SBBOp<1>}, // Unit tests find this setting flags incorrectly {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 4), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 5), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 6), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 7), 1, &OpDispatchBuilder::CMPOp<1>}, // GROUP 2 {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 4), 1, &OpDispatchBuilder::SHLOp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 5), 1, &OpDispatchBuilder::SHROp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 4), 1, &OpDispatchBuilder::SHLOp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 5), 1, &OpDispatchBuilder::SHROp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 4), 1, &OpDispatchBuilder::SHLOp<true>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 5), 1, &OpDispatchBuilder::SHROp<true>}, // 1Bit SHR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 4), 1, &OpDispatchBuilder::SHLOp<true>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 5), 1, &OpDispatchBuilder::SHROp<true>}, // 1Bit SHR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 4), 1, &OpDispatchBuilder::SHLOp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 5), 1, &OpDispatchBuilder::SHROp<false>}, // SHR by CL {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 4), 1, &OpDispatchBuilder::SHLOp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 5), 1, &OpDispatchBuilder::SHROp<false>}, // SHR by CL {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR // GROUP 3 {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 0), 1, &OpDispatchBuilder::TESTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 2), 1, &OpDispatchBuilder::NOTOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 3), 1, &OpDispatchBuilder::NEGOp}, // NEG {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 4), 1, &OpDispatchBuilder::MULOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 5), 1, &OpDispatchBuilder::IMULOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 6), 1, &OpDispatchBuilder::DIVOp}, // DIV {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 7), 1, &OpDispatchBuilder::IDIVOp}, // IDIV {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 0), 1, &OpDispatchBuilder::TESTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 2), 1, &OpDispatchBuilder::NOTOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 3), 1, &OpDispatchBuilder::NEGOp}, // NEG {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 4), 1, &OpDispatchBuilder::MULOp}, // MUL {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 5), 1, &OpDispatchBuilder::IMULOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 6), 1, &OpDispatchBuilder::DIVOp}, // DIV {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 7), 1, &OpDispatchBuilder::IDIVOp}, // IDIV // GROUP 4 {OPD(FEXCore::X86Tables::TYPE_GROUP_4, OpToIndex(0xFE), 0), 1, &OpDispatchBuilder::INCOp}, // INC {OPD(FEXCore::X86Tables::TYPE_GROUP_4, OpToIndex(0xFE), 1), 1, &OpDispatchBuilder::DECOp}, // DEC // GROUP 5 {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 0), 1, &OpDispatchBuilder::INCOp}, // INC {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 1), 1, &OpDispatchBuilder::DECOp}, // DEC {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 2), 1, &OpDispatchBuilder::CALLAbsoluteOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 4), 1, &OpDispatchBuilder::JUMPAbsoluteOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 6), 1, &OpDispatchBuilder::PUSHOp}, // GROUP 11 {OPD(FEXCore::X86Tables::TYPE_GROUP_11, OpToIndex(0xC6), 0), 1, &OpDispatchBuilder::MOVGPROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_11, OpToIndex(0xC7), 0), 1, &OpDispatchBuilder::MOVGPROp<1>}, }; #undef OPD const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> RepModOpTable = { {0x10, 2, &OpDispatchBuilder::MOVSSOp}, {0x19, 7, &OpDispatchBuilder::NOPOp}, {0x2A, 1, &OpDispatchBuilder::CVT<4, true>}, {0x2C, 1, &OpDispatchBuilder::FCVT<4, true>}, {0x51, 1, &OpDispatchBuilder::VectorUnaryOp<IR::OP_VFSQRT, 4, true>}, {0x52, 1, &OpDispatchBuilder::VectorUnaryOp<IR::OP_VFRSQRT, 4, true>}, {0x58, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFADD, 4>}, {0x59, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMUL, 4>}, {0x5A, 1, &OpDispatchBuilder::FCVTF<8, 4>}, {0x5C, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFSUB, 4>}, {0x5D, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMIN, 4>}, {0x5E, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFDIV, 4>}, {0x5F, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMAX, 4>}, {0x6F, 1, &OpDispatchBuilder::MOVUPSOp}, {0x70, 1, &OpDispatchBuilder::PSHUFDOp<2, false>}, {0x7E, 1, &OpDispatchBuilder::MOVQOp}, {0x7F, 1, &OpDispatchBuilder::MOVUPSOp}, {0xB8, 1, &OpDispatchBuilder::PopcountOp}, {0xBC, 2, &OpDispatchBuilder::TZCNT}, {0xC2, 1, &OpDispatchBuilder::VFCMPOp<4, true>}, {0xE6, 1, &OpDispatchBuilder::VFCVT<4, true, true>}, }; const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> RepNEModOpTable = { {0x10, 2, &OpDispatchBuilder::MOVSDOp}, {0x12, 1, &OpDispatchBuilder::MOVDDUPOp}, {0x19, 7, &OpDispatchBuilder::NOPOp}, {0x2A, 1, &OpDispatchBuilder::CVT<8, true>}, {0x2C, 1, &OpDispatchBuilder::FCVT<8, true>}, {0x51, 1, &OpDispatchBuilder::VectorUnaryOp<IR::OP_VFSQRT, 8, true>}, //x52 = Invalid {0x58, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFADD, 8>}, {0x59, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMUL, 8>}, {0x5A, 1, &OpDispatchBuilder::FCVTF<4, 8>}, {0x5C, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFSUB, 8>}, {0x5D, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMIN, 8>}, {0x5E, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFDIV, 8>}, {0x5F, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMAX, 8>}, {0x70, 1, &OpDispatchBuilder::PSHUFDOp<2, true>}, {0xC2, 1, &OpDispatchBuilder::VFCMPOp<8, true>}, {0xF0, 1, &OpDispatchBuilder::MOVVectorOp}, }; const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> OpSizeModOpTable = { {0x10, 2, &OpDispatchBuilder::MOVVectorOp}, {0x12, 2, &OpDispatchBuilder::MOVLPOp}, {0x14, 1, &OpDispatchBuilder::PUNPCKLOp<8>}, {0x15, 1, &OpDispatchBuilder::PUNPCKHOp<8>}, {0x16, 2, &OpDispatchBuilder::MOVHPDOp}, {0x19, 7, &OpDispatchBuilder::NOPOp}, {0x28, 2, &OpDispatchBuilder::MOVAPSOp}, {0x40, 16, &OpDispatchBuilder::CMOVOp}, {0x50, 1, &OpDispatchBuilder::MOVMSKOp<8>}, {0x54, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VAND, 16>}, {0x55, 1, &OpDispatchBuilder::ANDNOp}, {0x56, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VOR, 16>}, {0x57, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VXOR, 16>}, {0x58, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFADD, 8>}, {0x59, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMUL, 8>}, {0x5A, 1, &OpDispatchBuilder::VFCVTF<4, 8>}, {0x5C, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFSUB, 8>}, {0x5D, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMIN, 8>}, {0x5E, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFDIV, 8>}, {0x5F, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMAX, 8>}, {0x60, 1, &OpDispatchBuilder::PUNPCKLOp<1>}, {0x61, 1, &OpDispatchBuilder::PUNPCKLOp<2>}, {0x62, 1, &OpDispatchBuilder::PUNPCKLOp<4>}, {0x64, 1, &OpDispatchBuilder::PCMPGTOp<1>}, {0x65, 1, &OpDispatchBuilder::PCMPGTOp<2>}, {0x66, 1, &OpDispatchBuilder::PCMPGTOp<4>}, {0x67, 1, &OpDispatchBuilder::PACKUSOp<2>}, {0x68, 1, &OpDispatchBuilder::PUNPCKHOp<1>}, {0x69, 1, &OpDispatchBuilder::PUNPCKHOp<2>}, {0x6A, 1, &OpDispatchBuilder::PUNPCKHOp<4>}, {0x6C, 1, &OpDispatchBuilder::PUNPCKLOp<8>}, {0x6D, 1, &OpDispatchBuilder::PUNPCKHOp<8>}, {0x6E, 1, &OpDispatchBuilder::MOVDOp}, {0x6F, 1, &OpDispatchBuilder::MOVUPSOp}, {0x70, 1, &OpDispatchBuilder::PSHUFDOp<4, true>}, // XXX: Causing IR interpreter some problems {0x74, 1, &OpDispatchBuilder::PCMPEQOp<1>}, {0x75, 1, &OpDispatchBuilder::PCMPEQOp<2>}, {0x76, 1, &OpDispatchBuilder::PCMPEQOp<4>}, {0x78, 1, nullptr}, // GROUP 17 {0x7E, 1, &OpDispatchBuilder::MOVDOp}, {0x7F, 1, &OpDispatchBuilder::MOVUPSOp}, {0xC2, 1, &OpDispatchBuilder::VFCMPOp<8, false>}, {0xC4, 1, &OpDispatchBuilder::PINSROp<2>}, {0xC6, 1, &OpDispatchBuilder::SHUFOp<8>}, {0xD4, 1, &OpDispatchBuilder::PADDQOp<8>}, // XXX: Causes LLVM to crash if commented out? {0xD6, 1, &OpDispatchBuilder::MOVQOp}, {0xD7, 1, &OpDispatchBuilder::MOVMSKOp<1>}, // PMOVMSKB // XXX: Untested {0xDA, 1, &OpDispatchBuilder::PMINUOp<1>}, {0xDB, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VAND, 16>}, {0xDE, 1, &OpDispatchBuilder::PMAXUOp<1>}, {0xDF, 1, &OpDispatchBuilder::ANDNOp}, {0xE1, 1, &OpDispatchBuilder::PSRAOp<2, true, 0>}, {0xE2, 1, &OpDispatchBuilder::PSRAOp<4, true, 0>}, {0xE7, 1, &OpDispatchBuilder::MOVVectorOp}, {0xEA, 1, &OpDispatchBuilder::PMINSWOp}, {0xEB, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VOR, 16>}, {0xEC, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VSQADD, 1>}, {0xED, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VSQADD, 2>}, {0xEE, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VSMAX, 2>}, {0xEF, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VXOR, 16>}, {0xF2, 1, &OpDispatchBuilder::PSLL<4, true, 0>}, {0xF3, 1, &OpDispatchBuilder::PSLL<8, true, 0>}, {0xF4, 1, &OpDispatchBuilder::PMULOp<4, false>}, {0xF8, 1, &OpDispatchBuilder::PSUBQOp<1>}, {0xF9, 1, &OpDispatchBuilder::PSUBQOp<2>}, {0xFA, 1, &OpDispatchBuilder::PSUBQOp<4>}, {0xFB, 1, &OpDispatchBuilder::PSUBQOp<8>}, {0xFD, 1, &OpDispatchBuilder::PADDQOp<2>}, {0xFE, 1, &OpDispatchBuilder::PADDQOp<4>}, }; constexpr uint16_t PF_NONE = 0; constexpr uint16_t PF_F3 = 1; constexpr uint16_t PF_66 = 2; constexpr uint16_t PF_F2 = 3; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_6) << 5) | (prefix) << 3 | (Reg)) const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> SecondaryExtensionOpTable = { // GROUP 8 {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_NONE, 4), 1, &OpDispatchBuilder::BTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F3, 4), 1, &OpDispatchBuilder::BTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_66, 4), 1, &OpDispatchBuilder::BTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F2, 4), 1, &OpDispatchBuilder::BTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_NONE, 5), 1, &OpDispatchBuilder::BTSOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F3, 5), 1, &OpDispatchBuilder::BTSOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_66, 5), 1, &OpDispatchBuilder::BTSOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F2, 5), 1, &OpDispatchBuilder::BTSOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_NONE, 6), 1, &OpDispatchBuilder::BTROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F3, 6), 1, &OpDispatchBuilder::BTROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_66, 6), 1, &OpDispatchBuilder::BTROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F2, 6), 1, &OpDispatchBuilder::BTROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_NONE, 7), 1, &OpDispatchBuilder::BTCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F3, 7), 1, &OpDispatchBuilder::BTCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_66, 7), 1, &OpDispatchBuilder::BTCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F2, 7), 1, &OpDispatchBuilder::BTCOp<1>}, // GROUP 12 {OPD(FEXCore::X86Tables::TYPE_GROUP_12, PF_66, 2), 1, &OpDispatchBuilder::PSRLI<2>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_12, PF_66, 4), 1, &OpDispatchBuilder::PSRAIOp<2>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_12, PF_66, 6), 1, &OpDispatchBuilder::PSLLI<2>}, // GROUP 13 {OPD(FEXCore::X86Tables::TYPE_GROUP_13, PF_66, 2), 1, &OpDispatchBuilder::PSRLI<4>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_13, PF_66, 4), 1, &OpDispatchBuilder::PSRAIOp<4>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_13, PF_66, 6), 1, &OpDispatchBuilder::PSLLI<4>}, // GROUP 14 {OPD(FEXCore::X86Tables::TYPE_GROUP_14, PF_66, 2), 1, &OpDispatchBuilder::PSRLI<8>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_14, PF_66, 3), 1, &OpDispatchBuilder::PSRLDQ}, {OPD(FEXCore::X86Tables::TYPE_GROUP_14, PF_66, 6), 1, &OpDispatchBuilder::PSLLI<8>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_14, PF_66, 7), 1, &OpDispatchBuilder::PSLLDQ}, // GROUP 15 {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 0), 1, &OpDispatchBuilder::FXSaveOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 1), 1, &OpDispatchBuilder::FXRStoreOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 2), 1, &OpDispatchBuilder::LDMXCSR}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 3), 1, &OpDispatchBuilder::STMXCSR}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 5), 1, &OpDispatchBuilder::NOPOp}, //LFENCE {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 6), 1, &OpDispatchBuilder::NOPOp}, //MFENCE {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 7), 1, &OpDispatchBuilder::NOPOp}, //SFENCE {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_F3, 5), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_F3, 6), 1, &OpDispatchBuilder::UnimplementedOp}, // GROUP 16 {OPD(FEXCore::X86Tables::TYPE_GROUP_16, PF_NONE, 0), 8, &OpDispatchBuilder::NOPOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_16, PF_F3, 0), 8, &OpDispatchBuilder::NOPOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_16, PF_66, 0), 8, &OpDispatchBuilder::NOPOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_16, PF_F2, 0), 8, &OpDispatchBuilder::NOPOp}, }; #undef OPD const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> SecondaryModRMExtensionOpTable = { // REG /2 {((1 << 3) | 0), 1, &OpDispatchBuilder::UnimplementedOp}, }; #define OPDReg(op, reg) (((op - 0xD8) << 8) | (reg << 3)) #define OPD(op, modrmop) (((op - 0xD8) << 8) | modrmop) const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> X87OpTable = { {OPDReg(0xD9, 0) | 0x00, 8, &OpDispatchBuilder::FLD<32>}, {OPDReg(0xD9, 0) | 0x40, 8, &OpDispatchBuilder::FLD<32>}, {OPDReg(0xD9, 0) | 0x80, 8, &OpDispatchBuilder::FLD<32>}, {OPDReg(0xD9, 5) | 0x00, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FLDCW {OPDReg(0xD9, 5) | 0x40, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FLDCW {OPDReg(0xD9, 5) | 0x80, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FLDCW {OPDReg(0xD9, 7) | 0x00, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FNSTCW {OPDReg(0xD9, 7) | 0x40, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FNSTCW {OPDReg(0xD9, 7) | 0x80, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FNSTCW {OPDReg(0xDB, 7) | 0x00, 8, &OpDispatchBuilder::FST<80, true>}, {OPDReg(0xDB, 7) | 0x40, 8, &OpDispatchBuilder::FST<80, true>}, {OPDReg(0xDB, 7) | 0x80, 8, &OpDispatchBuilder::FST<80, true>}, {OPDReg(0xDD, 0) | 0x00, 8, &OpDispatchBuilder::FLD<64>}, {OPDReg(0xDD, 0) | 0x40, 8, &OpDispatchBuilder::FLD<64>}, {OPDReg(0xDD, 0) | 0x80, 8, &OpDispatchBuilder::FLD<64>}, {OPD(0xDE, 0xC0), 8, &OpDispatchBuilder::FADD}, }; #undef OPD #undef OPDReg #define OPD(prefix, opcode) ((prefix << 8) | opcode) constexpr uint16_t PF_38_NONE = 0; constexpr uint16_t PF_38_66 = 1; constexpr uint16_t PF_38_F2 = 2; const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> H0F38Table = { {OPD(PF_38_66, 0x00), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(PF_38_66, 0x3B), 1, &OpDispatchBuilder::UnimplementedOp}, }; #undef OPD #define OPD(REX, prefix, opcode) ((REX << 9) | (prefix << 8) | opcode) #define PF_3A_NONE 0 #define PF_3A_66 1 const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> H0F3ATable = { {OPD(0, PF_3A_66, 0x0F), 1, &OpDispatchBuilder::PAlignrOp}, {OPD(1, PF_3A_66, 0x0F), 1, &OpDispatchBuilder::PAlignrOp}, }; #undef PF_3A_NONE #undef PF_3A_66 #undef OPD #define OPD(map_select, pp, opcode) (((map_select - 1) << 10) | (pp << 8) | (opcode)) const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> VEXTable = { {OPD(1, 0b01, 0x6E), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x6F), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b10, 0x6F), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x74), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x75), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x76), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b00, 0x77), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x7E), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x7F), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b10, 0x7F), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0xD7), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0xEB), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0xEF), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x3B), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x58), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x59), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x5A), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x78), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x79), 1, &OpDispatchBuilder::UnimplementedOp}, }; #undef OPD const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> EVEXTable = { {0x10, 1, &OpDispatchBuilder::UnimplementedOp}, {0x11, 1, &OpDispatchBuilder::UnimplementedOp}, {0x59, 1, &OpDispatchBuilder::UnimplementedOp}, {0x7F, 1, &OpDispatchBuilder::UnimplementedOp}, }; uint64_t NumInsts{}; auto InstallToTable = [&NumInsts](auto& FinalTable, auto& LocalTable) { for (auto Op : LocalTable) { auto OpNum = std::get<0>(Op); auto Dispatcher = std::get<2>(Op); for (uint8_t i = 0; i < std::get<1>(Op); ++i) { LogMan::Throw::A(FinalTable[OpNum + i].OpcodeDispatcher == nullptr, "Duplicate Entry"); FinalTable[OpNum + i].OpcodeDispatcher = Dispatcher; if (Dispatcher) ++NumInsts; } } }; [[maybe_unused]] auto CheckTable = [](auto& FinalTable) { for (size_t i = 0; i < FinalTable.size(); ++i) { auto const &Op = FinalTable.at(i); if (Op.Type != X86Tables::TYPE_INST) continue; // Invalid op, we don't care if (Op.OpcodeDispatcher == nullptr) { LogMan::Msg::D("Op: 0x%lx %s didn't have an OpDispatcher", i, Op.Name); } } }; InstallToTable(FEXCore::X86Tables::BaseOps, BaseOpTable); InstallToTable(FEXCore::X86Tables::SecondBaseOps, TwoByteOpTable); InstallToTable(FEXCore::X86Tables::PrimaryInstGroupOps, PrimaryGroupOpTable); InstallToTable(FEXCore::X86Tables::RepModOps, RepModOpTable); InstallToTable(FEXCore::X86Tables::RepNEModOps, RepNEModOpTable); InstallToTable(FEXCore::X86Tables::OpSizeModOps, OpSizeModOpTable); InstallToTable(FEXCore::X86Tables::SecondInstGroupOps, SecondaryExtensionOpTable); InstallToTable(FEXCore::X86Tables::SecondModRMTableOps, SecondaryModRMExtensionOpTable); InstallToTable(FEXCore::X86Tables::X87Ops, X87OpTable); InstallToTable(FEXCore::X86Tables::H0F38TableOps, H0F38Table); InstallToTable(FEXCore::X86Tables::H0F3ATableOps, H0F3ATable); InstallToTable(FEXCore::X86Tables::VEXTableOps, VEXTable); InstallToTable(FEXCore::X86Tables::EVEXTableOps, EVEXTable); // Useful for debugging // CheckTable(FEXCore::X86Tables::BaseOps); printf("We installed %ld instructions to the tables\n", NumInsts); } }
177,837
75,446
//===----------------------------------------------------------------------===// // // BusTub // // lru_replacer.cpp // // Identification: src/buffer/lru_replacer.cpp // // Copyright (c) 2015-2019, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "buffer/lru_replacer.h" namespace bustub { LRUReplacer::LRUReplacer(size_t num_pages) { head_ = new FrameListNode(-1); tail_ = new FrameListNode(-1); head_->next_ = tail_; tail_->prev_ = head_; capacity_ = num_pages; size_ = 0; lru_map_.reserve(num_pages); } // initialization. head and tail are consecutive, LRUReplacer::~LRUReplacer() { for (size_t i = 0; i < size_ + 2; ++i) { tail_ = head_->next_; delete head_; head_ = tail_; } } // victim // find the frame_id according to LRU algorithm // kick the elment with such frame_id out of the LRU map, size --; // remove the related MyListNode out of the List; // bool LRUReplacer::Victim(frame_id_t *frame_id) { std::lock_guard<std::mutex> guard(frame_list_mutex_); if (Size() == 0) { return false; } *frame_id = tail_->prev_->l_data_; lru_map_.erase(*frame_id); size_ --; Remove(tail_->prev_); return true; // shall we remove ?? who has the priviledge to change data member of LRU?? remove, insert? and what/?? } void LRUReplacer::Pin(frame_id_t frame_id) { // kick it out of the list // 1. find the ListNode* // remove(ListNode*) from the list; // remove the listnode from the map; std::lock_guard<std::mutex> guard(frame_list_mutex_); if (lru_map_.count(frame_id) == 0) { return; } auto node2remove = lru_map_[frame_id]; Remove(node2remove); lru_map_.erase(frame_id); size_ --; } void LRUReplacer::Unpin(frame_id_t frame_id) { // find the related initiate a new listnode for it // put it into map; // // insert into map, list, ?? how to solve it?? if (lru_map_.count(frame_id) != 0) { return; } auto node2insert = new FrameListNode(frame_id); std::lock_guard<std::mutex> guard(frame_list_mutex_); lru_map_.insert({frame_id, node2insert}); size_ ++; Insert(node2insert); // delete node2insert; } size_t LRUReplacer::Size() { return size_; } } // namespace bustub
2,298
860
#include "array.h" int main() { ArrayList<int> list1(10); list1.append(5); list1.insert(7); list1.goToStart(); list1.insert(8); list1.next(); int a = list1.remove(); cout << a; return 0; }
225
93
#include <memory> #include <openclx/array_view> #include <openclx/binary> #include <openclx/bits/macros> #include <openclx/build_status> #include <openclx/context> #include <openclx/device> #include <openclx/downcast> #include <openclx/kernel> #include <openclx/program> void clx::program::build(const std::string& options, const device_array& devices) { CLX_CHECK(::clBuildProgram( this->_ptr, devices.size(), downcast(devices.data()), options.data(), nullptr, nullptr )); } clx::build_status clx::program::build_status(const device& dev) const { CLX_BODY_SCALAR( ::clGetProgramBuildInfo, ::clx::build_status, dev.get(), CL_PROGRAM_BUILD_STATUS ) } #if CL_TARGET_VERSION >= 120 clx::binary_types clx::program::binary_type(const device& dev) const { CLX_BODY_SCALAR( ::clGetProgramBuildInfo, ::clx::binary_types, dev.get(), CL_PROGRAM_BINARY_TYPE ) } #endif #if CL_TARGET_VERSION >= 200 size_t clx::program::size_of_global_variables(const device& dev) const { CLX_BODY_SCALAR( ::clGetProgramBuildInfo, size_t, dev.get(), CL_PROGRAM_BUILD_GLOBAL_VARIABLE_TOTAL_SIZE ) } #endif std::string clx::program::options(const device& dev) const { std::string value(4096, ' '); int_type ret; bool success = false; size_t actual_size = 0; while (!success) { ret = ::clGetProgramBuildInfo( this->_ptr, dev.get(), CL_PROGRAM_BUILD_OPTIONS, sizeof(value), &value, nullptr ); value.resize(actual_size); if (errc(ret) != errc::invalid_value && actual_size <= value.size()) { CLX_CHECK(ret); success = true; } } return value; } std::string clx::program::build_log(const device& dev) const { std::string value(4096, ' '); int_type ret; size_t actual_size = 0; ret = ::clGetProgramBuildInfo( this->_ptr, dev.get(), CL_PROGRAM_BUILD_LOG, 0, nullptr, &actual_size ); CLX_CHECK(ret); value.resize(actual_size); ret = ::clGetProgramBuildInfo( this->_ptr, dev.get(), CL_PROGRAM_BUILD_LOG, value.size(), &value[0], nullptr ); CLX_CHECK(ret); return value; } std::vector<clx::binary> clx::program::binaries() const { unsigned_int_type ndevices = this->num_devices(); std::vector<size_t> sizes(ndevices); CLX_CHECK(::clGetProgramInfo( this->_ptr, CL_PROGRAM_BINARY_SIZES, sizes.size()*sizeof(size_t), sizes.data(), nullptr )); static_assert( sizeof(std::unique_ptr<unsigned char>) == sizeof(unsigned char*), "bad size" ); std::vector<std::unique_ptr<unsigned char[]>> binaries; binaries.reserve(ndevices); for (const auto& s : sizes) { binaries.emplace_back(new unsigned char[s]); } CLX_CHECK(::clGetProgramInfo( this->_ptr, CL_PROGRAM_BINARIES, binaries.size()*sizeof(unsigned char*), binaries.data(), nullptr )); std::vector<binary> result; result.reserve(ndevices); for (unsigned_int_type i=0; i<ndevices; ++i) { result.emplace_back(binaries[i].get(), sizes[i]); } return result; } #if CL_TARGET_VERSION >= 120 && defined(CLX_HAVE_clCompileProgram) void clx::program::compile( const std::string& options, const header_array& headers, const device_array& devices ) { std::vector<program_type> programs; programs.reserve(headers.size()); std::vector<const char*> names; names.reserve(headers.size()); for (const auto& h : headers) { programs.emplace_back(h.program.get()); names.emplace_back(h.name.data()); } CLX_CHECK(::clCompileProgram( this->_ptr, devices.size(), downcast(devices.data()), options.data(), headers.size(), programs.data(), names.data(), nullptr, nullptr )); } #endif std::vector<clx::kernel> clx::program::kernels() const { std::vector<::clx::kernel> result(4096 / sizeof(::clx::kernel)); int_type ret = 0; bool success = false; unsigned_int_type actual_size = 0; while (!success) { ret = ::clCreateKernelsInProgram( this->_ptr, result.size(), downcast(result.data()), &actual_size ); result.resize(actual_size); if (errc(ret) != errc::invalid_value && actual_size <= result.size()) { CLX_CHECK(ret); success = true; } } return result; } clx::kernel clx::program::kernel(const char* name) const { int_type ret = 0; auto krnl = ::clCreateKernel(this->_ptr, name, &ret); CLX_CHECK(ret); return static_cast<::clx::kernel>(krnl); } CLX_METHOD_SCALAR(clx::program::context, ::clGetProgramInfo, ::clx::context, CL_PROGRAM_CONTEXT) CLX_METHOD_SCALAR(clx::program::num_references, ::clGetProgramInfo, unsigned_int_type, CL_PROGRAM_REFERENCE_COUNT) CLX_METHOD_SCALAR(clx::program::num_devices, ::clGetProgramInfo, unsigned_int_type, CL_PROGRAM_NUM_DEVICES) CLX_METHOD_ARRAY(clx::program::devices, ::clGetProgramInfo, CL_PROGRAM_DEVICES, device) CLX_METHOD_STRING(clx::program::source, ::clGetProgramInfo, CL_PROGRAM_SOURCE) #if CL_TARGET_VERSION >= 210 clx::intermediate_language clx::program::intermediate_language() const { size_t actual_size = 0; CLX_CHECK(::clGetProgramInfo( this->_ptr, CL_PROGRAM_IL, 0, nullptr, &actual_size )); ::clx::intermediate_language il(actual_size); CLX_CHECK(::clGetProgramInfo( this->_ptr, CL_PROGRAM_IL, actual_size, il.data(), nullptr )); return il; } #endif #if CL_TARGET_VERSION >= 120 && defined(CLX_HAVE_clLinkProgram) clx::program clx::link( const array_view<program>& programs, const std::string& options, const array_view<device>& devices ) { if (programs.empty()) { throw std::invalid_argument("empty programs"); } int_type ret = 0; auto prog = ::clLinkProgram( programs.front().context().get(), devices.size(), downcast(devices.data()), options.data(), programs.size(), downcast(programs.data()), nullptr, nullptr, &ret ); CLX_CHECK(ret); return static_cast<program>(prog); } #endif
6,443
2,277
#pragma once /// @file #include "nlohmann/json.hpp" namespace neon { using json = nlohmann::json; }
104
46
// This file is part of the QuantumGate project. For copyright and // licensing information refer to the license file(s) in the project root. #include "pch.h" #include "Ping.h" #include "..\Common\Random.h" #include "..\Common\ScopeGuard.h" #include <Iphlpapi.h> #include <Ipexport.h> #include <icmpapi.h> #include <winternl.h> // for IO_STATUS_BLOCK namespace QuantumGate::Implementation::Network { bool Ping::Execute(const bool use_os_api) noexcept { Reset(); switch (m_DestinationIPAddress.AddressFamily) { case BinaryIPAddress::Family::IPv4: case BinaryIPAddress::Family::IPv6: if (use_os_api) return ExecuteOS(); else return ExecuteRAW(); default: assert(false); break; } LogErr(L"Ping failed due to invalid IP address family"); m_Status = Status::Failed; return false; } bool Ping::ExecuteOS() noexcept { String error; try { LogDbg(L"Pinging %s (Buffer: %u bytes, TTL: %llus, Timeout: %llums)", IPAddress(m_DestinationIPAddress).GetString().c_str(), m_BufferSize, m_TTL.count(), m_Timeout.count()); IPAddr dest_addr4{ 0 }; sockaddr_in6 src_addr6{ 0 }; sockaddr_in6 dest_addr6{ 0 }; Size reply_size{ 0 }; HANDLE icmp_handle{ INVALID_HANDLE_VALUE }; if (m_DestinationIPAddress.AddressFamily == BinaryIPAddress::Family::IPv4) { dest_addr4 = m_DestinationIPAddress.UInt32s[0]; reply_size = sizeof(ICMP_ECHO_REPLY) + m_BufferSize + 8 + sizeof(IO_STATUS_BLOCK); icmp_handle = IcmpCreateFile(); } else { src_addr6.sin6_family = AF_INET6; dest_addr6.sin6_family = AF_INET6; static_assert(sizeof(BinaryIPAddress::Bytes) == sizeof(IPV6_ADDRESS_EX::sin6_addr), "Should be same size"); std::memcpy(&dest_addr6.sin6_addr, &m_DestinationIPAddress.Bytes, sizeof(in6_addr)); reply_size = sizeof(ICMPV6_ECHO_REPLY) + m_BufferSize + 8 + sizeof(IO_STATUS_BLOCK); icmp_handle = Icmp6CreateFile(); } if (icmp_handle != INVALID_HANDLE_VALUE) { // Cleanup when we leave auto sg = MakeScopeGuard([&]() noexcept { IcmpCloseHandle(icmp_handle); }); IP_OPTION_INFORMATION ip_opts{ 0 }; ip_opts.Ttl = static_cast<UCHAR>(m_TTL.count()); auto icmp_data = Random::GetPseudoRandomBytes(m_BufferSize); Buffer reply_buffer(reply_size); const auto num_replies = std::invoke([&]() { if (m_DestinationIPAddress.AddressFamily == BinaryIPAddress::Family::IPv4) { return IcmpSendEcho2( icmp_handle, nullptr, nullptr, nullptr, dest_addr4, icmp_data.GetBytes(), static_cast<WORD>(icmp_data.GetSize()), &ip_opts, reply_buffer.GetBytes(), static_cast<DWORD>(reply_buffer.GetSize()), static_cast<DWORD>(m_Timeout.count())); } else { return Icmp6SendEcho2( icmp_handle, nullptr, nullptr, nullptr, &src_addr6, &dest_addr6, icmp_data.GetBytes(), static_cast<WORD>(icmp_data.GetSize()), &ip_opts, reply_buffer.GetBytes(), static_cast<DWORD>(reply_buffer.GetSize()), static_cast<DWORD>(m_Timeout.count())); } }); if (num_replies != 0) { ULONG status{ 0 }; BinaryIPAddress rip; ULONG rtt{ 0 }; std::optional<ULONG> ttl; if (m_DestinationIPAddress.AddressFamily == BinaryIPAddress::Family::IPv4) { const auto echo_reply = reinterpret_cast<ICMP_ECHO_REPLY*>(reply_buffer.GetBytes()); status = echo_reply->Status; rtt = echo_reply->RoundTripTime; ttl = echo_reply->Options.Ttl; rip.AddressFamily = BinaryIPAddress::Family::IPv4; rip.UInt32s[0] = echo_reply->Address; } else { if (Icmp6ParseReplies(reply_buffer.GetBytes(), static_cast<DWORD>(reply_buffer.GetSize())) == 1) { const auto echo_reply = reinterpret_cast<ICMPV6_ECHO_REPLY*>(reply_buffer.GetBytes()); status = echo_reply->Status; rtt = echo_reply->RoundTripTime; rip.AddressFamily = BinaryIPAddress::Family::IPv6; static_assert(sizeof(BinaryIPAddress::Bytes) == sizeof(IPV6_ADDRESS_EX::sin6_addr), "Should be same size"); std::memcpy(&rip.Bytes, &dest_addr6.sin6_addr, sizeof(IPV6_ADDRESS_EX::sin6_addr)); } else error = L"failed to parse ICMP6 reply"; } switch (status) { case IP_SUCCESS: m_Status = Status::Succeeded; break; case IP_TTL_EXPIRED_TRANSIT: m_Status = Status::TimeToLiveExceeded; break; case IP_DEST_NET_UNREACHABLE: case IP_DEST_HOST_UNREACHABLE: case IP_BAD_DESTINATION: m_Status = Status::DestinationUnreachable; break; case IP_REQ_TIMED_OUT: m_Status = Status::Timedout; default: break; } switch (m_Status) { case Status::Succeeded: case Status::DestinationUnreachable: case Status::TimeToLiveExceeded: if (ttl.has_value()) m_ResponseTTL = std::chrono::seconds(*ttl); m_RespondingIPAddress = rip; m_RoundTripTime = std::chrono::milliseconds(rtt); return true; case Status::Timedout: return true; default: break; } } else { if (GetLastError() == IP_REQ_TIMED_OUT) { m_Status = Status::Timedout; return true; } error = Util::FormatString(L"failed to send ICMP echo request (%s)", GetLastSocketErrorString().c_str()); } } else error = Util::FormatString(L"failed to create ICMP file handle (%s)", GetLastSocketErrorString().c_str()); } catch (...) { error = L"an exception was thrown"; } LogErr(L"Pinging IP address %s failed - %s", IPAddress(m_DestinationIPAddress).GetString().c_str(), error.c_str()); m_Status = Status::Failed; return false; } bool Ping::ExecuteRAW() noexcept { // Currently only supports IPv4. On Windows this does not fully work for // because the OS does not notify the socket of Time Exceeded ICMP // messages. assert(m_DestinationIPAddress.AddressFamily == BinaryIPAddress::Family::IPv4); String error; try { LogDbg(L"Pinging %s (Buffer: %u bytes, TTL: %llus, Timeout: %llums)", IPAddress(m_DestinationIPAddress).GetString().c_str(), m_BufferSize, m_TTL.count(), m_Timeout.count()); ICMP::EchoMessage icmp_hdr; icmp_hdr.Header.Type = static_cast<UInt8>(ICMP::MessageType::Echo); icmp_hdr.Header.Code = 0; icmp_hdr.Header.Checksum = 0; const UInt64 num = Random::GetPseudoRandomNumber(); icmp_hdr.Identifier = static_cast<UInt16>(num); icmp_hdr.SequenceNumber = static_cast<UInt16>(num >> 32); const auto icmp_data = Random::GetPseudoRandomBytes(m_BufferSize); Buffer icmp_msg(reinterpret_cast<Byte*>(&icmp_hdr), sizeof(icmp_hdr)); icmp_msg += icmp_data; reinterpret_cast<ICMP::EchoMessage*>(icmp_msg.GetBytes())->Header.Checksum = ICMP::CalculateChecksum(icmp_msg); Socket socket(IP::AddressFamily::IPv4, Socket::Type::RAW, IP::Protocol::ICMP); if (!socket.SetIPTimeToLive(m_TTL)) return false; if (socket.SendTo(IPEndpoint(m_DestinationIPAddress, 0), icmp_msg) && icmp_msg.IsEmpty()) { const auto snd_steady_time = Util::GetCurrentSteadyTime(); if (socket.UpdateIOStatus(m_Timeout)) { const auto rcv_steady_time = Util::GetCurrentSteadyTime(); if (socket.GetIOStatus().CanRead()) { IPEndpoint endpoint; Buffer data; if (socket.ReceiveFrom(endpoint, data)) { if (data.GetSize() >= sizeof(IP::Header)) { const auto ip_hdr = reinterpret_cast<const IP::Header*>(data.GetBytes()); if (ip_hdr->Protocol == static_cast<UInt8>(IP::Protocol::ICMP)) { const auto ttl = ip_hdr->TTL; const auto msg_type = ProcessICMPReply(data, icmp_hdr.Identifier, icmp_hdr.SequenceNumber, icmp_data); if (msg_type.has_value()) { switch (*msg_type) { case ICMP::MessageType::EchoReply: m_Status = Status::Succeeded; break; case ICMP::MessageType::DestinationUnreachable: m_Status = Status::DestinationUnreachable; break; case ICMP::MessageType::TimeExceeded: m_Status = Status::TimeToLiveExceeded; break; default: assert(false); break; } if (m_Status != Status::Unknown) { m_ResponseTTL = std::chrono::seconds(ttl); m_RespondingIPAddress = endpoint.GetIPAddress().GetBinary(); m_RoundTripTime = std::chrono::duration_cast<std::chrono::milliseconds>(rcv_steady_time - snd_steady_time); return true; } } } error = L"received unrecognized ICMP reply"; } else error = L"not enough data received for IP header"; } else error = L"failed to receive from socket"; } else if (socket.GetIOStatus().HasException()) { error = L"exception on socket (" + GetSysErrorString(socket.GetIOStatus().GetErrorCode()) + L")"; } else { m_Status = Status::Timedout; return true; } } else error = L"failed to update socket state"; } else error = L"failed to send ICMP packet"; } catch (...) { error = L"an exception was thrown"; } LogErr(L"Pinging IP address %s failed - %s", IPAddress(m_DestinationIPAddress).GetString().c_str(), error.c_str()); m_Status = Status::Failed; return false; } std::optional<ICMP::MessageType> Ping::ProcessICMPReply(BufferView buffer, const UInt16 expected_id, const UInt16 expected_sequence_number, const BufferView expected_data) const noexcept { if (buffer.GetSize() >= sizeof(IP::Header) + sizeof(ICMP::Header)) { // Remove IP header buffer.RemoveFirst(sizeof(IP::Header)); auto icmp_hdr = *reinterpret_cast<const ICMP::Header*>(buffer.GetBytes()); switch (static_cast<ICMP::MessageType>(icmp_hdr.Type)) { case ICMP::MessageType::DestinationUnreachable: if (buffer.GetSize() >= (sizeof(ICMP::DestinationUnreachableMessage) + sizeof(IP::Header) + sizeof(ICMP::EchoMessage))) { if (VerifyICMPMessageChecksum(buffer)) { auto du_msg = *reinterpret_cast<const ICMP::DestinationUnreachableMessage*>(buffer.GetBytes()); if (du_msg.Unused == 0) { buffer.RemoveFirst(sizeof(ICMP::DestinationUnreachableMessage)); buffer.RemoveFirst(sizeof(IP::Header)); if (VerifyICMPEchoMessage(buffer, expected_id, expected_sequence_number, expected_data)) { return ICMP::MessageType::DestinationUnreachable; } else LogErr(L"Received ICMP destination unreachable message with invalid original echo message data"); } } } else LogErr(L"Received ICMP destination unreachable message with unexpected size of %zu bytes", buffer.GetSize()); break; case ICMP::MessageType::TimeExceeded: if (buffer.GetSize() >= (sizeof(ICMP::TimeExceededMessage) + sizeof(IP::Header) + sizeof(ICMP::EchoMessage))) { if (VerifyICMPMessageChecksum(buffer)) { auto te_msg = *reinterpret_cast<const ICMP::TimeExceededMessage*>(buffer.GetBytes()); if (te_msg.Unused == 0) { buffer.RemoveFirst(sizeof(ICMP::TimeExceededMessage)); buffer.RemoveFirst(sizeof(IP::Header)); if (VerifyICMPEchoMessage(buffer, expected_id, expected_sequence_number, expected_data)) { return ICMP::MessageType::TimeExceeded; } else LogErr(L"Received ICMP time exceeded message with invalid original echo message data"); } } } else LogErr(L"Received ICMP time exceeded message with unexpected size of %zu bytes", buffer.GetSize()); break; case ICMP::MessageType::EchoReply: if (buffer.GetSize() >= sizeof(ICMP::EchoMessage)) { if (VerifyICMPMessageChecksum(buffer)) { auto echo_msg = *reinterpret_cast<const ICMP::EchoMessage*>(buffer.GetBytes()); if (echo_msg.Header.Code == 0 && echo_msg.Identifier == expected_id && echo_msg.SequenceNumber == expected_sequence_number) { buffer.RemoveFirst(sizeof(ICMP::EchoMessage)); if (buffer == expected_data) { return ICMP::MessageType::EchoReply; } } else LogErr(L"Received ICMP echo reply message with unexpected code, ID or sequence number"); } } else LogErr(L"Received ICMP echo reply message with unexpected size of %zu bytes", buffer.GetSize()); break; default: LogErr(L"Received unrecognized ICMP message type %u", icmp_hdr.Type); break; } } return std::nullopt; } bool Ping::VerifyICMPEchoMessage(BufferView buffer, const UInt16 expected_id, const UInt16 expected_sequence_number, const BufferView expected_data) const noexcept { if (buffer.GetSize() >= sizeof(ICMP::EchoMessage)) { auto echo_msg = *reinterpret_cast<const ICMP::EchoMessage*>(buffer.GetBytes()); if (echo_msg.Identifier == expected_id && echo_msg.SequenceNumber == expected_sequence_number) { buffer.RemoveFirst(sizeof(ICMP::EchoMessage)); auto cmp_size = expected_data.GetSize(); // We'll compare at most the first 64 bits // which are required according to RFC 792 if (cmp_size > 8) cmp_size = 8; if (buffer.GetSize() >= cmp_size) { return (buffer.GetFirst(cmp_size) == expected_data.GetFirst(cmp_size)); } } } return false; } bool Ping::VerifyICMPMessageChecksum(BufferView buffer) const noexcept { try { // We should require at least the basic ICMP header if (buffer.GetSize() >= sizeof(ICMP::Header)) { Buffer chksum_buf{ buffer }; // Reset checksum to zeros before calculating reinterpret_cast<ICMP::Header*>(chksum_buf.GetBytes())->Checksum = 0; if (reinterpret_cast<const ICMP::Header*>(buffer.GetBytes())->Checksum == ICMP::CalculateChecksum(chksum_buf)) return true; LogErr(L"ICMP message checksum failed verification"); } } catch (...) { LogErr(L"Failed to verify ICMP message checksum due to exception"); } return false; } String Ping::GetString() const noexcept { try { String str = Util::FormatString(L"Destination [IP: %s, Timeout: %llums, Buffer size: %u bytes, TTL: %llus]", IPAddress(m_DestinationIPAddress).GetString().c_str(), m_Timeout.count(), m_BufferSize, m_TTL.count()); String rttl_str; if (m_ResponseTTL.has_value()) { rttl_str += Util::FormatString(L", Response TTL: %llus", m_ResponseTTL->count()); } switch (m_Status) { case Status::Succeeded: str += Util::FormatString(L" / Result [Succeeded, Responding IP: %s, Response time: %llums%s]", IPAddress(*m_RespondingIPAddress).GetString().c_str(), m_RoundTripTime->count(), rttl_str.c_str()); break; case Status::TimeToLiveExceeded: str += Util::FormatString(L" / Result [TTL Exceeded, Responding IP: %s, Response time: %llums%s]", IPAddress(*m_RespondingIPAddress).GetString().c_str(), m_RoundTripTime->count(), rttl_str.c_str()); break; case Status::DestinationUnreachable: str += Util::FormatString(L" / Result [Destination unreachable, Responding IP: %s, Response time: %llums%s]", IPAddress(*m_RespondingIPAddress).GetString().c_str(), m_RoundTripTime->count(), rttl_str.c_str()); break; case Status::Timedout: str += L" / Result [Timed out]"; break; case Status::Failed: str += L" / Result [Failed]"; break; default: str += L" / Result [None]"; break; } return str; } catch (...) {} return {}; } std::ostream& operator<<(std::ostream& stream, const Ping& ping) { stream << Util::ToStringA(ping.GetString()); return stream; } std::wostream& operator<<(std::wostream& stream, const Ping& ping) { stream << ping.GetString(); return stream; } }
16,091
7,276
#include "tools.h" #include <iostream> using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { std::cout << "Tools::CalculateRMSE" << std::endl; VectorXd rmse(4); rmse << 0,0,0,0; // TODO: YOUR CODE HERE // check the validity of the following inputs: // * the estimation vector size should not be zero // * the estimation vector size should equal ground truth vector size if(estimations.size() < 0) { std::cout<<"estimation.rows() < 0"; } if(estimations.size() != ground_truth.size()) { std::cout<<"estimations.size() != ground_truth.size()"; } // TODO: accumulate squared residuals for (int i=0; i < estimations.size(); ++i) { // ... your code here VectorXd residual; residual = estimations[i] - ground_truth[i]; residual = residual.array().square(); rmse = rmse + residual; } // TODO: calculate the mean rmse = rmse / estimations.size(); // TODO: calculate the squared root rmse = rmse.array().sqrt(); // return the result VectorXd max_error(4); max_error << .11, .11, 0.52, 0.52; if((rmse.array() > max_error.array()).any()) std::cout <<"RMSE > max_error"<<std::endl; return rmse; } MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { /** * TODO: * Calculate a Jacobian here. */ // std::cout<< "Tools::CalculateJacobian" << std::endl; MatrixXd Hj(3,4); // recover state parameters float px = x_state(0); float py = x_state(1); float vx = x_state(2); float vy = x_state(3); // TODO: YOUR CODE HERE // check division by zero if( px==0 && py==0 ) { std::cout<<"Division by 0"; return Hj; } // compute the Jacobian matrix float pxpy_2 = px*px + py*py; float sqrt_pxpy_2 = sqrt(pxpy_2); Hj(0,0) = px/sqrt_pxpy_2; Hj(0,1) = py/sqrt_pxpy_2; Hj(0,2) = 0.0; Hj(0,3) = 0.0; Hj(1,0) = -py/pxpy_2; Hj(1,1) = px/pxpy_2; Hj(1,2) = 0.0; Hj(1,3) = 0.0; Hj(2,0) = py*(vx*py-vy*px)/ pow(pxpy_2, 3.0/2.0); Hj(2,1) = px*(vy*px-vx*py)/ pow(pxpy_2, 3.0/2.0); Hj(2,2) = px/sqrt_pxpy_2; Hj(2,3) = py/sqrt_pxpy_2; // std::cout<< "End Tools::CalculateJacobian" << std::endl; return Hj; }
2,358
1,028
//---------------------------------------------------------------------------- /** @file SgBoardConst.cpp See SgBoardConst.h */ //---------------------------------------------------------------------------- #include "SgSystem.h" #include "SgBoardConst.h" #include <algorithm> #include "SgInit.h" #include "SgStack.h" using namespace std; using SgPointUtil::Pt; //---------------------------------------------------------------------------- SgBoardConst::BoardConstImpl::BoardConstImpl(SgGrid size) : m_size(size), m_firstBoardPoint(Pt(1, 1)), m_lastBoardPoint(Pt(size, size)) { m_gridToLine.Fill(0); m_gridToPos.Fill(0); m_up.Fill(0); for (SgGrid line = 0; line <= SG_MAX_SIZE / 2; ++line) m_line[line].Clear(); // Set up values for points on the board. m_boardIterEnd = m_boardIter; SgGrid halfSize = (m_size + 1) / 2; for (SgGrid row = 1; row <= m_size; ++row) { for (SgGrid col = 1; col <= m_size; ++col) { SgPoint p = Pt(col, row); SgGrid lineRow = row > halfSize ? m_size + 1 - row : row; SgGrid lineCol = col > halfSize ? m_size + 1 - col : col; SgGrid line = min(lineRow, lineCol); SgGrid pos = max(lineRow, lineCol); m_gridToLine[p] = line; m_gridToPos[p] = pos; m_line[line - 1].Include(p); const int MAX_EDGE = m_size > 11 ? 4 : 3; if (line <= MAX_EDGE) { if (pos <= MAX_EDGE + 1) m_corners.Include(p); else m_edges.Include(p); } else m_centers.Include(p); int nuNb = 0; if (row > 1) m_neighbors[p][nuNb++] = Pt(col, row - 1); if (col > 1) m_neighbors[p][nuNb++] = Pt(col - 1, row); if (col < m_size) m_neighbors[p][nuNb++] = Pt(col + 1, row); if (row < m_size) m_neighbors[p][nuNb++] = Pt(col, row + 1); m_neighbors[p][nuNb] = SG_ENDPOINT; *(m_boardIterEnd++) = p; } } // Set up direction to point on line above. for (SgPoint p = 0; p < SG_MAXPOINT; ++p) { if (m_gridToLine[p] != 0) { SgGrid line = m_gridToLine[p]; if (m_gridToLine[p - SG_NS] == line + 1) m_up[p] = -SG_NS; if (m_gridToLine[p - SG_WE] == line + 1) m_up[p] = -SG_WE; if (m_gridToLine[p + SG_WE] == line + 1) m_up[p] = SG_WE; if (m_gridToLine[p + SG_NS] == line + 1) m_up[p] = SG_NS; // If no line above vertically or horizontally, try diagonally. if (m_up[p] == 0) { if (m_gridToLine[p - SG_NS - SG_WE] == line + 1) m_up[p] = -SG_NS - SG_WE; if (m_gridToLine[p - SG_NS + SG_WE] == line + 1) m_up[p] = -SG_NS + SG_WE; if (m_gridToLine[p + SG_NS - SG_WE] == line + 1) m_up[p] = SG_NS - SG_WE; if (m_gridToLine[p + SG_NS + SG_WE] == line + 1) m_up[p] = SG_NS + SG_WE; } } } // Set up direction to the sides, based on Up. Always list clockwise // direction first. { for (int i = 0; i <= 2 * (SG_NS + SG_WE); ++i) { m_side[0][i] = 0; m_side[1][i] = 0; } // When Up is towards center, sides are orthogonal to Up. m_side[0][-SG_NS + (SG_NS + SG_WE)] = -SG_WE; m_side[1][-SG_NS + (SG_NS + SG_WE)] = +SG_WE; m_side[0][-SG_WE + (SG_NS + SG_WE)] = +SG_NS; m_side[1][-SG_WE + (SG_NS + SG_WE)] = -SG_NS; m_side[0][+SG_WE + (SG_NS + SG_WE)] = -SG_NS; m_side[1][+SG_WE + (SG_NS + SG_WE)] = +SG_NS; m_side[0][+SG_NS + (SG_NS + SG_WE)] = +SG_WE; m_side[1][+SG_NS + (SG_NS + SG_WE)] = -SG_WE; // When Up is diagonal, sides are along different sides of board. m_side[0][-SG_NS - SG_WE + (SG_NS + SG_WE)] = -SG_WE; m_side[1][-SG_NS - SG_WE + (SG_NS + SG_WE)] = -SG_NS; m_side[0][-SG_NS + SG_WE + (SG_NS + SG_WE)] = -SG_NS; m_side[1][-SG_NS + SG_WE + (SG_NS + SG_WE)] = +SG_WE; m_side[0][+SG_NS - SG_WE + (SG_NS + SG_WE)] = +SG_NS; m_side[1][+SG_NS - SG_WE + (SG_NS + SG_WE)] = -SG_WE; m_side[0][+SG_NS + SG_WE + (SG_NS + SG_WE)] = +SG_WE; m_side[1][+SG_NS + SG_WE + (SG_NS + SG_WE)] = +SG_NS; } // Terminate board iterator. *m_boardIterEnd = SG_ENDPOINT; // Set up line iterators. { int lineIndex = 0; for (SgGrid line = 1; line <= (SG_MAX_SIZE / 2) + 1; ++line) { m_lineIterAddress[line - 1] = &m_lineIter[lineIndex]; for (SgPoint p = m_firstBoardPoint; p <= m_lastBoardPoint; ++p) { if (m_gridToLine[p] == line) m_lineIter[lineIndex++] = p; } m_lineIter[lineIndex++] = SG_ENDPOINT; ////SG_ASSERT(lineIndex //<= SG_MAX_SIZE * SG_MAX_SIZE + (SG_MAX_SIZE / 2) + 1); } ////SG_ASSERT(lineIndex == m_size * m_size + (SG_MAX_SIZE / 2) + 1); } // Set up corner iterator. m_cornerIter[0] = Pt(1, 1); m_cornerIter[1] = Pt(m_size, 1); m_cornerIter[2] = Pt(1, m_size); m_cornerIter[3] = Pt(m_size, m_size); m_cornerIter[4] = SG_ENDPOINT; m_sideExtensions = m_line[2 - 1] | m_line[3 - 1] | m_line[4 - 1]; // LineSet(line) == m_line[line - 1], see .h // exclude diagonals, so that different sides from corner are in different // sets. m_sideExtensions.Exclude(Pt(2, 2)); m_sideExtensions.Exclude(Pt(2, m_size + 1 - 2)); m_sideExtensions.Exclude(Pt(m_size + 1 - 2, 2)); m_sideExtensions.Exclude(Pt(m_size + 1 - 2, m_size + 1 - 2)); if (m_size > 2) { m_sideExtensions.Exclude(Pt(3, 3)); m_sideExtensions.Exclude(Pt(3, m_size + 1 - 3)); m_sideExtensions.Exclude(Pt(m_size + 1 - 3, 3)); m_sideExtensions.Exclude(Pt(m_size + 1 - 3, m_size + 1 - 3)); if (m_size > 3) { m_sideExtensions.Exclude(Pt(4, 4)); m_sideExtensions.Exclude(Pt(4, m_size + 1 - 4)); m_sideExtensions.Exclude(Pt(m_size + 1 - 4, 4)); m_sideExtensions.Exclude(Pt(m_size + 1 - 4, m_size + 1 - 4)); } } } //---------------------------------------------------------------------------- SgBoardConst::BoardConstImplArray SgBoardConst::s_const; void SgBoardConst::Create(SgGrid size) { //SG_ASSERT_GRIDRANGE(size); if (! s_const[size]) s_const[size] = boost::shared_ptr<BoardConstImpl>(new BoardConstImpl(size)); m_const = s_const[size]; ////SG_ASSERT(m_const); } SgBoardConst::SgBoardConst(SgGrid size) { //SG_ASSERT_GRIDRANGE(size); SgInitCheck(); Create(size); } void SgBoardConst::ChangeSize(SgGrid newSize) { //SG_ASSERT_GRIDRANGE(newSize); ////SG_ASSERT(m_const); // Don't do anything if called with same size. SgGrid oldSize = m_const->m_size; if (newSize != oldSize) Create(newSize); } //----------------------------------------------------------------------------
7,384
2,938
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <string.h> #include <vector> #include "tensorflow/contrib/lite/builtin_op_data.h" #include "tensorflow/contrib/lite/context.h" #include "tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/contrib/lite/kernels/internal/tensor.h" #include "tensorflow/contrib/lite/kernels/kernel_util.h" #include "tensorflow/contrib/lite/kernels/op_macros.h" namespace tflite { namespace ops { namespace builtin { namespace transpose { // This file has two implementations of Transpose. enum KernelType { kReference, }; struct TransposeContext { TransposeContext(TfLiteContext* context, TfLiteNode* node) { input = GetInput(context, node, 0); perm = GetInput(context, node, 1); output = GetOutput(context, node, 0); } TfLiteTensor* input; TfLiteTensor* perm; TfLiteTensor* output; }; TfLiteStatus ResizeOutputTensor(TfLiteContext* context, TransposeContext* op_context) { int dims = NumDimensions(op_context->input); const int* perm_data = GetTensorData<int32_t>(op_context->perm); // Ensure validity of the permutations tensor as a 1D tensor. TF_LITE_ENSURE_EQ(context, NumDimensions(op_context->perm), 1); TF_LITE_ENSURE_EQ(context, op_context->perm->dims->data[0], dims); for (int idx = 0; idx < dims; ++idx) { TF_LITE_ENSURE_MSG(context, (perm_data[idx] >= 0 && perm_data[idx] < dims), "Transpose op permutations array is out of bounds."); } // Determine size of output tensor. TfLiteIntArray* input_size = op_context->input->dims; TfLiteIntArray* output_size = TfLiteIntArrayCopy(input_size); for (int idx = 0; idx < dims; ++idx) { output_size->data[idx] = input_size->data[perm_data[idx]]; } return context->ResizeTensor(context, op_context->output, output_size); } TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TransposeContext op_context(context, node); // Ensure validity of input tensor. TF_LITE_ENSURE_MSG(context, NumDimensions(op_context.input) <= 4, "Transpose op only supports 1D-4D input arrays."); TF_LITE_ENSURE_EQ(context, op_context.input->type, op_context.output->type); if (!IsConstantTensor(op_context.perm)) { SetTensorToDynamic(op_context.output); return kTfLiteOk; } return ResizeOutputTensor(context, &op_context); } template <KernelType kernel_type> TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { TransposeContext op_context(context, node); // Resize the output tensor if the output tensor is dynamic. if (IsDynamicTensor(op_context.output)) { TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, &op_context)); TfLiteTensorRealloc(op_context.output->bytes, op_context.output); } // Reverse the permuted axes and convert to 4D due to the way Dims are // constructed in GetTensorDims. const int* perm_data = GetTensorData<int32_t>(op_context.perm); const int size = op_context.perm->dims->data[0]; const int kOutputDimensionNum = 4; int reversed_perm[kOutputDimensionNum]; for (int output_k = 0, input_k = size - 1; output_k < size; ++output_k, --input_k) { reversed_perm[output_k] = size - perm_data[input_k] - 1; } for (int k = size; k < kOutputDimensionNum; ++k) { reversed_perm[k] = k; } #define TF_LITE_TRANSPOSE(type, scalar) \ type::Transpose(GetTensorData<scalar>(op_context.input), \ GetTensorDims(op_context.input), \ GetTensorData<scalar>(op_context.output), \ GetTensorDims(op_context.output), reversed_perm) switch (op_context.input->type) { case kTfLiteFloat32: if (kernel_type == kReference) { TF_LITE_TRANSPOSE(reference_ops, float); } break; case kTfLiteUInt8: if (kernel_type == kReference) { TF_LITE_TRANSPOSE(reference_ops, uint8_t); } break; case kTfLiteInt32: if (kernel_type == kReference) { TF_LITE_TRANSPOSE(reference_ops, int32_t); } break; case kTfLiteInt64: if (kernel_type == kReference) { TF_LITE_TRANSPOSE(reference_ops, int64_t); } break; default: context->ReportError(context, "Type is currently not supported by Transpose."); return kTfLiteError; } #undef TF_LITE_TRANSPOSE return kTfLiteOk; } } // namespace transpose TfLiteRegistration* Register_TRANSPOSE_REF() { static TfLiteRegistration r = {nullptr, nullptr, transpose::Prepare, transpose::Eval<transpose::kReference>}; return &r; } TfLiteRegistration* Register_TRANSPOSE() { return Register_TRANSPOSE_REF(); } } // namespace builtin } // namespace ops } // namespace tflite
5,551
1,946
#ifndef PEMDAS_MUSICPAGE_HPP #define PEMDAS_MUSICPAGE_HPP #include <QObject> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QMenu> #include <QAction> #include <vector> #include "utils.hpp" #include "player.hpp" #include "ui_pemdas.h" class musicpage : public QObject { Q_OBJECT public: musicpage(Ui::pemdas &t_ui, mpd::player &t_player); void setup_ui(); void update(); private slots: void tree_item_double_clicked(QTreeWidgetItem *item, int column); void context_menu(const QPoint &pos); private: Ui::pemdas &m_ui; mpd::player &m_player; }; #endif//PEMDAS_MUSICPAGE_HPP
624
255
#include <iostream> #include <string> #include <algorithm> using namespace std; bool is_palindrome(string s) { string temp = s; reverse(s.begin(), s.end()); if (temp == s) return true; else return false; } int main() { int t; cin >> t; while(t--) { string s; cin >> s; if ( is_palindrome(s) ) { bool found = false; [&](){ for (int j = 0; j < s.length() - 1; ++j) { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; if ( !is_palindrome(s) ) { found = true; return; } } }(); if (found) cout << s << endl; else cout << -1 << endl; } else cout << s << endl; } return 0; }
891
287
/** * @file system.cpp * @author Susanna Maria, David Silver * @brief system handling impletionments * @version 1.0 * @date 2020-06-21 * * @copyright MIT License * */ #include "system.h" #include <unistd.h> #include <cstddef> #include <iostream> #include <set> #include <string> #include <vector> #include "linux_parser.h" #include "process.h" #include "process_container.h" #include "processor.h" using LinuxParser::ProcessStates; using std::set; using std::size_t; using std::string; using std::vector; /** * Return the system's CPU * * @return Processor& */ Processor& System::Cpu() { return cpu_; } /** * Return a container composed of the system's processes * * @return vector<Process>& */ vector<Process>& System::Processes() { return process_container_.Processes(); } /** * Return the system's kernel identifier (string) * * @return std::string */ std::string System::Kernel() const { return LinuxParser::Kernel(); } /** * Return the system's memory utilization * * @return float */ float System::MemoryUtilization() const { return LinuxParser::MemoryUtilization(); } /** * Return the operating system name * * @return std::string */ std::string System::OperatingSystem() const { return LinuxParser::OperatingSystem(); } /** * Return the number of processes actively running on the system * * @return int */ int System::RunningProcesses() const { return LinuxParser::RunningProcesses(); } /** * Return the total number of processes on the system * * @return int */ int System::TotalProcesses() const { return LinuxParser::TotalProcesses(); } /** * Return the number of seconds since the system started running * * @return long int */ long int System::UpTime() const { return LinuxParser::UpTime(); }
1,764
538
#ifndef S2SFUNC #define S2SFUNC #include "rose.h" #include "s2sDefines.hpp" #include "api.hpp" #include <sstream> #include <string> #include <iostream> #include <vector> //int MAQAO_DEBUG_LEVEL=0; static int identifierFunctions=0; class ASTFunction; class Function; struct variable_spe; /** * ASTFunction class : * Represent the top of the tree * A tree root is the global scope of a file and all nodes are functions definitions */ class ASTFunction { protected: // size_t id; // to match with maqao id function // std::string name; // Name of the function SgGlobal* root; // Represent a node above the subtree of functions (it should be a SgNode*) std::vector<Function*> internalFunctionsList; // Vector which contain list of all functions of the file public: //Constructor ASTFunction(SgSourceFile*); ASTFunction(SgBasicBlock*); ASTFunction(SgGlobal* root); //Destructor ~ASTFunction(); //Accessors std::vector<Function*> get_internalFunctionsList(); void set_internalFunctionsList(std::vector<Function*> ); //Miscellaneous /** * Print functions which are marks as not found * Essentially use to compare which functions match with binary loops */ void printASTLines(); /** * Print functions which marks as not found * Essentially use to compare which functions match with binary functions */ void print_function_not_found(); /** * Print information about all functions of the subtree, * only print information about all functions in the file. */ void print(); /** * Print all functions names of the file where they're comme from. */ void print_names(); /** * Search into the global tree a function near of the start/end lines * * @param start - Line where the function start * @param end - Line where the function end * @return - Pointer on a Function which correspond to the lines */ Function* get_function_from_line(int start,int end=-1); /** * Search into the global tree a function with the name name * * @param name - The name of the function * @return - Pointer on a Function which correspond to the name */ Function* get_func_from_name(std::string name); /** * Search into the global tree which function contains a maqao directive and apply it */ void apply_directive(); /** * Return true if the gloabl tree is empty * @return - Return true if the gloabl scope doesn't have any function definition */ bool empty(); }; /** * Function class: * represent a function definition with its body and original body (before any transformation), its pointer on the Rose representation of the Function definition, the type of the function and its id. * */ class Function { public: enum functionType_ { SUBROUTINE, FUNCTION, UNKNOWN }; // Enum to represent the function type protected: size_t id; // Used to match with maqao id function, by default functions' id are set from 1 to n to the order of reading the source code SgFunctionDefinition * function; // Rose function SgBasicBlock * body_without_trans; functionType_ typeOfFunction; // The function type bool is_matching; // Only for internal used public: //CONSTRUCTOR Function(SgFunctionDefinition* f); ~Function(); //ACCESSORS SgFunctionDefinition* get_function(); SgFunctionDefinition* get_function() const; void set_function(SgFunctionDefinition* f); size_t get_id(); size_t get_id() const; void set_id(size_t ID); std::string get_name() const; std::string get_file_name() const; functionType_ get_functionType(); functionType_ get_functionType() const; void set_functionType(Function::functionType_); void set_functionType(std::string functionKeyword); int get_line_start(); int get_line_end(); /** * Return true or false if the function was already meets the binary function conrresponding or not. * @return Return true if the function was already meets the binary function conrresponding */ bool is_matching_with_bin_loop(); void set_matching_with_bin_loop(bool); //Prints /** * Print the type of the function (Fortran do; C/C++ "for" ; while ; etc) */ std::string print_functionType(); void print_statement_class(); /** * Print the function begining and ending lines. */ void printLines(); /** * Print information about the function */ void print(); /** * Print functions which marks as not found * Essentially use to compare which functions match with binary functions */ void print_function_not_found(); //miscellaneous /** * Attach a directive to the function * * @param s - string containing the directive line without the "!DIR$" */ void add_directive(std::string s); /** * Look for all maqao directive, * then apply transformations requested. */ bool apply_directive(); bool apply_directive(std::string dirctive); // void apply_directive2(); /** * Sepcialize a function for a special value, * this value can be specified explicitly than equals to a fix value. * Or it's possible to indicate what it's its limits, * for example, it's possible to indicate than a variable is < to 3 or is between {2,10} * * This function will analyze vectors of variable_spe and will create special function with there indications */ void specialize(std::vector<variable_spe*> var, bool create_call); // /!\ Deprecated void specialize_v2(std::vector<variable_spe*> var, bool create_call); /** * Add the call to the function of our library to modify prefect guided by a configuration define in the string s. * String s : The configuration name for prefetch. */ bool modify_prefetch(std::string s); }; /** * Build a conditionnal of a if stmt */ SgExprStatement* build_if_cond(variable_spe* var, SgSymbol* v_symbol, SgScopeStatement* function); /** * Continue to build the conditionnal of the if stmt */ SgExprStatement* build_if_cond_from_ifcond(variable_spe* var, SgSymbol* v_symbol, SgScopeStatement* function, SgExprStatement* ifcond); /** * Return a pointer on function corresponding to the function at line lstart */ Function* get_function_from_line(ASTFunction* ast, int lstart, int lend = -1, int delta=0); #endif
6,579
1,861
#include <Neosegment.h> /* This code can be used to display a value from a potentiometer, dynamically changing color depending on the value 2 Neosegment modules are used to display a number from 0 to 1023 Connect potentiometer to NodeMCU or similar as follows: 5V A0 GND | | | ---[ * ]-- This code uses an array of readings to display an average reading that avoids most of the flickering The code could be improved by only refreshing the digit that changes, instead of all digits */ int sensorReading = 0; // variable to read the value from the analog pin int oldSensorReading = 0; // variable to store previous reading int digitBuffer; int digitIndex; #define POTPIN A0 #define nDigits 4 #define PIN D5 // Which pin the Neosegment modules are connected to const int numReadings = 10; // how many readings to remember int readings[numReadings]; // the readings from the analog input int readIndex = 0; // the index of the current reading int total = 0; // the running total int average = 0; // average value Neosegment neosegment(nDigits, PIN, 100); // Helper function to return a color on a color wheel uint32_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if(WheelPos < 85) { return neosegment.Color(255 - WheelPos * 3, 0, WheelPos * 3); } if(WheelPos < 170) { WheelPos -= 85; return neosegment.Color(0, WheelPos * 3, 255 - WheelPos * 3); } WheelPos -= 170; return neosegment.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } void setup() { Serial.begin(115200); neosegment.begin(); neosegment.clearAll(); // initialize all the readings to 0: for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings[thisReading] = 0; } } void loop(){ // subtract the last reading: total = total - readings[readIndex]; // read from the sensor: readings[readIndex] = analogRead(POTPIN); // add the reading to the total: total = total + readings[readIndex]; // advance to the next position in the array: readIndex = readIndex + 1; // if we're at the end of the array... if (readIndex >= numReadings) { // ...wrap around to the beginning: readIndex = 0; } // calculate the average: average = total / numReadings; sensorReading = average; if (oldSensorReading != sensorReading) { oldSensorReading = sensorReading; } // If the sensor reading is below 1000, make sure the 0-th digit is off if(sensorReading < 1000) { neosegment.clearDigit(0); } // If the sensor reading is below 100, make sure the 0-th and 1-st digits are off if(sensorReading < 100) { neosegment.clearDigit(0); neosegment.clearDigit(1); } // If the sensor reading is below 100, make sure the 0-th, 1-st and 2-nd digits are off if(sensorReading < 10) { neosegment.clearDigit(0); neosegment.clearDigit(1); neosegment.clearDigit(2); } digitIndex = nDigits - 1; digitBuffer = sensorReading; // Start with the whole string of numbers // Display every digit from the sensor reading on appropriate Neosegment Digit while (digitBuffer > 0) { int digit = digitBuffer % 10; // Write digit to Neosegment display in color that corresponds to the sensor reading neosegment.setDigit( digitIndex, digit, Wheel(map(sensorReading, 0, 1024, 0, 255))); digitBuffer /= 10; digitIndex--; } delay(50); }
3,425
1,193
#include "example.h" #include <stdio.h> int x = 42; char *s = (char *)"Test"; void Sync::printer(void) { printf("The value of global s is %s\n", s); printf("The value of global x is %d\n", x); printf("The value of class s is %s\n", s); printf("The value of class x is %d\n", x); }
288
120
#include "CannotFindLutException.h" #include <iostream> using namespace std; CannotFindLutException::CannotFindLutException(const string path) { _message.append("LUT file error : cannot find "); _message.append(path); } CannotFindLutException::~CannotFindLutException() throw () { } const string CannotFindLutException::what() const throw() { return _message; }
392
126
#include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> #include <fstream> #include <cstring> #include <vector> #include <cctype> #include <locale> #include <algorithm> using namespace std; //fun todo list! // maybe make an output argument!?! // make a better help!!?!?!?!? inline bool exists (const std::string& name) { //stackoverflow!!! if (FILE *file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } std::vector<std::string> //not stackoverflow im pretty sure split( const std::string& input, const std::string& delims) { std::vector<std::string> ret; for (size_t start = 0, pos; ; start = pos + 1) { pos = input.find_first_of(delims, start); std::string token = input.substr(start, pos - start); if (token.length() > 0) // ignore empty tokens ret.push_back(token); if (pos == std::string::npos) break; } return ret; } using namespace std; vector<string> amountOccured(string str, string needle){ //stackoverflow!!! char *p; // split the string by spaces in a vector<string> a = split(str, " "); vector<string> occur; // search for pattern in a int c = 0; for (int i = 0; i < a.size(); i++){ if (needle == a[i]) { occur.push_back(a[i+1]); } } return occur; } string exec(string command){ //stackoverflow!!! char buffer[256]; string result = ""; FILE * pipe = popen(command.c_str(), "r"); if(!pipe){ return "couldn't make pipe :("; } while(!feof(pipe)){ if(fgets(buffer, 256, pipe) != NULL){ result += buffer; } } pclose(pipe); return result; } string addOption(string name, char** args, int argcount, string help, string def = ""){ //does the cool option thingy if(argcount > 1){ for(int i = 0; i < argcount; i++){ if(args[i] == "--" + name){ if(argcount-1 == i){ cout << '\n' << name << " argument help:\n" << help << '\n'; exit(0); } else{ string value = args[i+1]; return value; } } } return def; } return ""; } int main(int argc, char** argv){ //The args that are needed /* Arguments 0 Input file 1 Delete Residual files (0) 2 Silence Threshold (-50db) 3 Sound Speed (1) 4 Silent Speed (5) 5 The Silence Duration (2000) */ if(argc == 1){ cout << "Arguments\n file (default: none)\n deleteResidualFiles (default: 1)\n silenceThreshold (default 50, meaning -50db)\n soundSpeed (default: 1)\n silentSpeed (default: 5)\n silenceDuration (default: 2)\n silence (default: 0)"; cout << "\n\nUse --[argument name] to get more information about it"; exit(0); } //options!!!! string filepath = addOption("file", argv, argc, "The file to work on (required)"); string deleteResidual = addOption("deleteResidualFiles", argv, argc, "Remove all files other than the input file and the output file (not required)", "1"); string silenceThreshold = addOption("silenceThreshold", argv, argc, "The threshold to trigger \"silence\" from 0 (all sound) to 100 (nothing) (50)", "50"); string soundSpeed = addOption("soundSpeed", argv, argc, "The speed at which the parts of the video that has sound plays at (1x) (min: 0.5, max: 100)", "1"); string silentSpeed = addOption("silentSpeed", argv, argc, "The speed at which the parts of the video that does not have sound plays at (5x) (min: 0.5, max: 100)", "5"); string silenceDuration = addOption("silenceDuration", argv, argc, "The duration of the silence (in seconds) to trigger the \"silence\" (0.5s)", "0.5"); string silence = addOption("silent", argv, argc, "Suppress most messages that ffmpeg displays & most the messages outputted by this program (1 (silence) | 0 (normal) | debug)", "1"); if(argc == 2){ filepath = argv[1]; } vector<string> filepaths; if(argc > 2 && filepath == ""){ for(int i = 1; i < argc; i++){ filepaths.push_back(argv[i]); } } if(filepath == "" && filepaths.size() == 0){ cout << "\nThe argument 'file' is required\n"; exit(0); } else{ filepaths.push_back(filepath); } for(int pathi = 0; pathi < filepaths.size(); pathi++){ filepath = filepaths[pathi]; if(stoi(soundSpeed) > 100){ soundSpeed = "100"; } if(stof(soundSpeed) < 0.5){ soundSpeed = "0.5"; } if(stoi(silentSpeed) > 100){ silentSpeed = "100"; } if(stof(silentSpeed) < 0.5){ silentSpeed = "0.5"; } //need a filename to replace filepath when needed std::size_t found = filepath.find_last_of("/\\"); string filename = filepath.substr(found+1); string filedir = filepath.substr(0, found+1); replace(filedir.begin(), filedir.end(), '\\', '/'); string loglevel = (silence == "0" ? "" : " -loglevel warning "); if(silence == "debug"){ loglevel = " -loglevel debug "; } cout << "Making directory...\n"; exec("mkdir \"" + filedir +"temp\""); //1/2: Command that is not portable, but way more portable than the second... //the stuff that actually detects silence cout << "Detecting Silence...\n"; string out = exec("ffmpeg -i \"" + filepath + "\" -af silencedetect=n=-" + string(silenceThreshold) + "dB:d=" + silenceDuration + " -f null - 2>&1"); cout << out; vector<string> start = amountOccured(out.c_str(), "silence_start:"); vector<string> send = amountOccured(out.c_str(), "silence_end:"); for(int i = 0; i < start.size(); i++){ start[i] = start[i].substr(0, start[i].find('[')-1); } if(start.size() == 0 && send.size() == 0){ cout << "\n\nSeems to be that there was no silence in the video. You could try and lower the silence threshold or lower the silence duration."; exit(0); } cout << "Getting duration of video...\n"; string dur = exec("ffmpeg -i \"" + filepath + "\" -f null - 2>&1"); vector<string>splited = split(amountOccured(dur.c_str(), "Duration:")[0], ":"); float num = stoi(splited[0]) * 3600; //i could make this into one or two lines... but maybe later num += stoi(splited[1]) * 60; num += stof(splited[2]); start.push_back(to_string(num)); vector<string> filenamesSound; vector<string> filenamesSilent; //for the part of the video where there ISN'T silence cout << "Patching non silent video parts...\n"; for(int i = 0; i < start.size(); i++){ string command = "ffmpeg "; if(stof(start[i])-0.034 < (i == 0 ? 0 : stof(send[i-1]))){ //if the seek start is actually less than one frame (30 fps) than the to, then add a frame start[i] = to_string(stof(start[i]) + 0.034); } command.append(loglevel + " -to " + to_string(stof(start[i])) + " -ss "); //for some weird reason, it needs to be cast or else it will have 'frame=' on the last video clip if(i == 0){ command.append("0"); } else{ command.append(send[i-1]); } command.append(" -y -i \"" + filepath + "\" -filter_complex \"[0:v]setpts=" + to_string(1/stof(soundSpeed)) + "*PTS[v];[0:a]atempo=" + soundSpeed + "[a]\" -map \"[v]\" -map \"[a]\" \"" + filedir +"temp/" + filename + to_string(i) + "sound.mp4\"" ); if(start[i] != "0" && start[i] != send[abs(i)-1]){ //one of many error checking things that i have no idea why it works filenamesSound.push_back(filedir +"temp/" + filename + to_string(i) + "sound.mp4"); } else{ filenamesSound.push_back("0"); } exec(command); if(loglevel == " -loglevel warning "){ cout << "."; } } //for the part of the video where there IS silence cout << "Patching silent video parts...\n"; for(int i = 0; i < start.size()-1; i++){ string command = "ffmpeg "; command.append(loglevel + " -to " + send[i] + " -ss " + start[i]); command.append(" -y -i \"" + filepath + "\" -filter_complex \"[0:v]setpts=" + to_string(1/stof(silentSpeed)) + "*PTS[v];[0:a]atempo=" + silentSpeed + "[a]\" -map \"[v]\" -map \"[a]\" \"" + filedir +"temp/" + filename + to_string(i) + "silent.mp4\"" ); filenamesSilent.push_back(filedir +"temp/" + filename + to_string(i) + "silent.mp4"); exec(command); if(loglevel == " -loglevel warning "){ cout << "."; } } //converts all files to .ts/mpeg-2, and it does not work with the stuff above, you can't convert and use a filtergraph at the same time cout << "Converting files...\n"; for(int i = 0; i < filenamesSound.size(); i++){ if(exists(filenamesSound[i])){ exec("ffmpeg" + loglevel + " -y -i \"" + filenamesSound[i] + "\" -c copy -bsf:v h264_mp4toannexb -f mpegts \"" + filenamesSound[i] + ".ts\""); } else{ filenamesSound[i] = ""; } } for(int i = 0; i < filenamesSilent.size(); i++){ if(exists(filenamesSilent[i])){ exec("ffmpeg " + loglevel + "-y -i \"" + filenamesSilent[i] + "\" -c copy -bsf:v h264_mp4toannexb -f mpegts \"" + filenamesSilent[i] + ".ts\""); } else{ filenamesSilent[i] = ""; } } cout << "Patching in correct order...\n"; vector<string> correctOrder; //flip flops between starting with a sound clip or with a slient clip for(int i = 0; i < (filenamesSilent.size() > filenamesSound.size() ? filenamesSilent.size() : filenamesSound.size()) + 1; i++){ if(filenamesSound[0] == "0"){ //this means the video starts with silence if(filenamesSilent.size() > i && filenamesSilent[i] != "" && exists(filenamesSilent[i] + ".ts")){ correctOrder.push_back(filenamesSilent[i] + ".ts"); } if(filenamesSound.size() > i+1 && filenamesSound[i] != "" && exists(filenamesSound[i] + ".ts")){ correctOrder.push_back(filenamesSound[i+1] + ".ts"); } } else{ if(filenamesSound.size() > i && filenamesSound[i] != "" && exists(filenamesSound[i] + ".ts")){ correctOrder.push_back(filenamesSound[i] + ".ts"); } if(filenamesSilent.size() > i && filenamesSilent[i] != "" && exists(filenamesSilent[i] + ".ts")){ correctOrder.push_back(filenamesSilent[i] + ".ts"); } } } cout << "Stitching video parts...\n"; //i have to do this because of the command line character limit :( bool finishedConcat = false; int indexOrder = 0; //current index of the correctOrder vector to check if its done int numConcats = 0; //the number of concats to check if it needs to stitch it back to one file while(!finishedConcat){ string command = "ffmpeg "; command.append(loglevel); command.append("-y -i \"concat:"); cout << int(6000/(filedir.length()+filename.length()+8)); for(int i = 0; i < int(1000/(filedir.length()+filename.length()+8)); i++){ command.append(correctOrder[indexOrder] + "|"); //appends the filedirs to the command indexOrder++; if(indexOrder >= correctOrder.size()){ i = 10000; //you can never be too sure ;) //break; } } command = command.substr(0,command.length()-1); command.append("\" \"" + filedir + "temp/finished_" + filename + to_string(numConcats) + ".ts\""); cout << command; exec(command); //concats! if(indexOrder >= correctOrder.size()){ finishedConcat = true; } numConcats++; if(loglevel == " -loglevel warning "){ cout << "."; } } cout << "Creating final file...\n"; string command = "ffmpeg "; command.append(loglevel); command.append("-y -i \"concat:"); for(int i = 0; i < numConcats; i++){ command.append(filedir + "temp/finished_" + filename + to_string(i) + ".ts|"); } command = command.substr(0,command.length()-1); command.append("\" \"" + filedir + "finished_" + filename + "\""); cout << command; exec(command); //creates the final file! if(deleteResidual != "0"){ exec("rmdir /Q /S \"" + filedir +"temp\""); //2/2: Command that is *not* portable between systems. } cout << "\n\nFinished File #" + to_string(pathi) + ", you can find your created file in the same directory as the input file you put. It is called: finished_" << filename; } return 0; }
12,962
4,350
// Copyright Golden Hammer Software #include "GHParticleTransition.h" #include "GHParticleSystem.h" GHParticleTransition::GHParticleTransition(GHParticleSystem& particle) : mParticle(particle) { mParticle.getSpawner().setSpawningAllowed(false); } void GHParticleTransition::activate(void) { if (mParticle.isDead()) { mParticle.revive(); } mParticle.getSpawner().setSpawningAllowed(true); } void GHParticleTransition::deactivate(void) { mParticle.getSpawner().setSpawningAllowed(false); }
498
189
/*************************************************************************** * * Copyright (c) 2013 Baidu, Inc. 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. * **************************************************************************/ // Author: Wen Xiang <wenxiang@baidu.com> #include "flume/planner/pass_manager.h" #include <algorithm> #include <deque> #include "boost/foreach.hpp" #include "boost/tuple/tuple.hpp" #include "gflags/gflags.h" #include "glog/logging.h" #include "toft/base/scoped_ptr.h" #include "flume/planner/common/draw_plan_pass.h" #include "flume/planner/pass.h" #include "flume/planner/plan.h" DEFINE_int32(flume_planner_max_steps, 1000, "top limit of applied passes which are causing changes to plan."); namespace baidu { namespace flume { namespace planner { PassManager::PassMap* PassManager::s_depend_map = NULL; PassManager::PassMap* PassManager::s_apply_map = NULL; PassManager::PassMap* PassManager::s_invalidate_map = NULL; PassManager::PassMap* PassManager::s_preserve_map = NULL; PassManager::PassSet* PassManager::s_white_passes = NULL; PassManager::PassSet* PassManager::s_stable_passes = NULL; PassManager::PassSet* PassManager::s_recursive_passes = NULL; std::map<std::string, int32_t>* PassManager::s_pass_stage = NULL; void PassManager::InitPassRelations() { if (s_depend_map == NULL) { s_depend_map = new PassMap(); } if (s_apply_map == NULL) { s_apply_map = new PassMap(); } if (s_invalidate_map == NULL) { s_invalidate_map = new PassMap(); } if (s_preserve_map == NULL) { s_preserve_map = new PassMap(); } if (s_white_passes == NULL) { s_white_passes = new PassSet(); } if (s_stable_passes == NULL) { s_stable_passes = new PassSet(); } if (s_recursive_passes == NULL) { s_recursive_passes = new PassSet(); } if (s_pass_stage == NULL) { s_pass_stage = new std::map<std::string, int32_t>; } } inline PassManager::PassSet PassManager::LookUp(const PassMap* map, const std::string& name) { PassMap::const_iterator begin, end; boost::tie(begin, end) = map->equal_range(name); PassSet result; for (PassMap::const_iterator ptr = begin; ptr != end; ++ptr) { result.insert(ptr->second); } return result; } inline PassManager::PassSet PassManager::Union(const PassSet& set1, const PassSet& set2) { PassSet result; std::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(result, result.end())); return result; } inline PassManager::PassSet PassManager::Diff(const PassSet& set1, const PassSet& set2) { PassSet result; std::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(result, result.end())); return result; } inline PassManager::PassSet PassManager::Intersect(const PassSet& set1, const PassSet& set2) { PassSet result; std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(result, result.end())); return result; } inline bool PassManager::Includes(const PassSet& set1, const PassSet& set2) { return std::includes(set1.begin(), set1.end(), set2.begin(), set2.end()); } void PassManager::ShowPassRelations(std::ostream* stream) { InitPassRelations(); *stream << "Pass relations: " << std::endl; for (PassMap::iterator ptr = s_depend_map->begin(); ptr != s_depend_map->end(); ++ptr) { *stream << "\tRELY_PASS: " << ptr->first << " -> " << ptr->second << std::endl; } for (PassSet::iterator ptr = s_white_passes->begin(); ptr != s_white_passes->end(); ++ptr) { *stream << "\tPRESERVE_BY_DEFAULT: " << *ptr << std::endl; } for (PassSet::iterator ptr = s_stable_passes->begin(); ptr != s_stable_passes->end(); ++ptr) { *stream << "\tHOLD_BY_DEFAULT: " << *ptr << std::endl; } for (PassSet::iterator ptr = s_recursive_passes->begin(); ptr != s_recursive_passes->end(); ++ptr) { *stream << "\tRECURSIVE: " << *ptr << std::endl; } for (PassMap::iterator ptr = s_preserve_map->begin(); ptr != s_preserve_map->end(); ++ptr) { *stream << "\tPRESERVE_PASS: " << ptr->first << " -> " << ptr->second << std::endl; } for (PassMap::iterator ptr = s_invalidate_map->begin(); ptr != s_invalidate_map->end(); ++ptr) { *stream << "\tINVALIDATE_PASS: " << ptr->first << " -> " << ptr->second << std::endl; } } PassManager::PassManager(Plan* plan) : m_plan(plan), m_steps(0), m_debug_pass(NULL) { InitPassRelations(); } void PassManager::DeprecatedApplyRepeatedly(const std::string& pass) { PassSet needed_passes = LookUp(s_depend_map, pass); do { RunPasses(needed_passes); m_valid_passes.erase(pass); } while (RunPass(pass)); } // TODO(wenxiang): applying passes in topological order according to invalidating relations. bool PassManager::RunPasses(const PassSet& passes) { bool is_changed = false; // run all passes in order while (!Includes(m_valid_passes, passes)) { PassSet ready_passes = CollectReadyPasses(passes); // first apply passes who are immune from other passes BOOST_FOREACH(std::string pass, SelectSafePasses(ready_passes)) { is_changed |= RecursiveRunPass(pass); } BOOST_FOREACH(std::string pass, ready_passes) { is_changed |= RecursiveRunPass(pass); } } return is_changed; } // breadth-first search all related passes which are ready to run. PassManager::PassSet PassManager::CollectReadyPasses(const PassSet& needed_passes) { PassSet processed_passes; std::deque<std::string> processing_queue(needed_passes.begin(), needed_passes.end()); PassSet ready_passes; while (!processing_queue.empty()) { const std::string pass = processing_queue.front(); processing_queue.pop_front(); if (m_valid_passes.count(pass) != 0 || processed_passes.count(pass) != 0) { continue; } processed_passes.insert(pass); bool is_ready = true; PassMap::iterator ptr, end; for (boost::tie(ptr, end) = s_depend_map->equal_range(pass); ptr != end; ++ptr) { if (m_valid_passes.count(ptr->second) == 0) { processing_queue.push_back(ptr->second); is_ready = false; } } if (is_ready) { ready_passes.insert(pass); } } return ready_passes; } inline PassManager::PassSet PassManager::SelectSafePasses(const PassSet& passes) { PassSet safe_passes = passes; for (PassSet::iterator i = passes.begin(); i != passes.end() && !safe_passes.empty(); ++i) { safe_passes = QueryPreservedPasses(*i, safe_passes); } return safe_passes; } inline PassManager::PassSet PassManager::QueryPreservedPasses(const std::string& pass, const PassSet& total_passes) { // invalidate all other passes by default PassSet result; // for PRESERVE_BY_DEFAULT if (s_white_passes->count(pass) != 0) { result = total_passes; } // for HOLD_BY_DEFAULT result = Union(result, Intersect(total_passes, *s_stable_passes)); // for PRESERVE_PASS result = Union(result, Intersect(total_passes, LookUp(s_preserve_map, pass))); // for INVALIDATE_PASS result = Diff(result, LookUp(s_invalidate_map, pass)); // applied pass will re-validate itself. if (total_passes.count(pass) != 0 && s_recursive_passes->count(pass) == 0) { result.insert(pass); } return result; } inline bool PassManager::RecursiveRunPass(const std::string& pass) { bool is_changed = false; while (m_valid_passes.count(pass) == 0 && Includes(m_valid_passes, LookUp(s_depend_map, pass))) { is_changed |= RunPass(pass); } return is_changed; } namespace { std::string get_stage_name(OptimizingStage stage) { const static std::string stage_names[] = { "LOGICAL_OPTIMIZING", "TOPOLOGICAL_OPTIMIZING", "RUNTIME_OPTIMIZING", "TRANSLATION_OPTIMIZING" }; uint32_t n = static_cast<uint32_t>(stage); int pos[] = {-1, 0, 1, -1, 2, -1, -1, -1, 3}; CHECK_LE(pos[n], 3); CHECK_GE(pos[n], 0); return stage_names[pos[n]]; } } // namespace inline bool PassManager::RunPass(const std::string& name) { DCHECK(Includes(m_valid_passes, LookUp(s_depend_map, name))); DCHECK_EQ(0, m_valid_passes.count(name)); toft::scoped_ptr<Pass> deleter; Pass* pass = NULL; if (m_external_passes.count(name) != 0) { pass = m_external_passes[name]; } else { deleter.reset(flume::Reflection<Pass>::New(name)); pass = deleter.get(); } LOG(INFO) << "Applying pass " << name; if (s_pass_stage->count(name) != 0) { OptimizingStage stage = m_plan->Root()->get<OptimizingStage>(); CHECK((*s_pass_stage)[name] & stage) << "Pass [" << name << "] shouldn't have ran at stage " << get_stage_name(stage) <<", it may be a bug in planner."; } bool is_changed = pass->Run(m_plan); if (is_changed) { ++m_steps; m_valid_passes = QueryPreservedPasses(name, m_valid_passes); } if (m_steps > FLAGS_flume_planner_max_steps) { LOG(FATAL) << "Too many passes are applied, a dead loop may happens!"; } if (s_recursive_passes->count(name) == 0 || !is_changed) { m_valid_passes.insert(name); } if (m_debug_pass != NULL && (is_changed || m_plan->Root()->has<Debug>())) { DrawPlanPass::AddMessage(m_plan->Root(), "Apply " + name); m_debug_pass->Run(m_plan); } m_plan->Root()->clear<Debug>(); if (m_not_run_pass_name != name && m_valid_passes.count(name) != 0) { PassSet apply_passes = LookUp(s_apply_map, name); RunPasses(apply_passes); } return is_changed; } void PassManager::SetDebugPass(DrawPlanPass* pass) { m_debug_pass = pass; } } // namespace planner } // namespace flume } // namespace baidu
10,869
3,667
#include <iostream> #include "complejo.h" complejo::complejo(double real, double imaginario){ //Constructor por defecto parte_real = real; parte_imaginaria = imaginario; } void complejo::print(){ //Función print complejo std::cout<<"Su número complejo es: "<<parte_real<<"+"<<parte_imaginaria<<"i"<<std::endl; } double complejo::suma(double real, double imaginario, double real1, double imaginario1){ //Función suma de 2 complejos parte_real = (real+real1); parte_imaginaria = (imaginario+imaginario1); std::cout<<"La suma de sus 2 números complejos es: "<<parte_real<<"+"<<parte_imaginaria<<"i"<<std::endl; } double complejo::resta(double real, double imaginario, double real1, double imaginario1){ //Función resta de 2 complejos parte_real = (real-real1); parte_imaginaria = (imaginario-imaginario1); if (parte_imaginaria >= 0){ std::cout<<"La resta de sus 2 números complejos es: "<<parte_real<<"+"<<parte_imaginaria<<"i"<<std::endl; } if (parte_imaginaria < 0){ std::cout<<"La resta de sus 2 números complejos es: "<<parte_real<<"+("<<parte_imaginaria<<")i"<<std::endl; } }
1,159
426
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include <cmath> #include <cstdio> #include <cstring> #include "fix_langevin_kokkos.h" #include "atom_masks.h" #include "atom_kokkos.h" #include "force.h" #include "update.h" #include "respa.h" #include "error.h" #include "memory_kokkos.h" #include "group.h" #include "random_mars.h" #include "compute.h" #include "comm.h" #include "modify.h" #include "input.h" #include "variable.h" using namespace LAMMPS_NS; using namespace FixConst; enum{NOBIAS,BIAS}; enum{CONSTANT,EQUAL,ATOM}; #define SINERTIA 0.4 // moment of inertia prefactor for sphere #define EINERTIA 0.2 // moment of inertia prefactor for ellipsoid /* ---------------------------------------------------------------------- */ template<class DeviceType> FixLangevinKokkos<DeviceType>::FixLangevinKokkos(LAMMPS *lmp, int narg, char **arg) : FixLangevin(lmp, narg, arg),rand_pool(seed + comm->me) { kokkosable = 1; atomKK = (AtomKokkos *) atom; int ntypes = atomKK->ntypes; // allocate per-type arrays for force prefactors memoryKK->create_kokkos(k_gfactor1,gfactor1,ntypes+1,"langevin:gfactor1"); memoryKK->create_kokkos(k_gfactor2,gfactor2,ntypes+1,"langevin:gfactor2"); memoryKK->create_kokkos(k_ratio,ratio,ntypes+1,"langevin:ratio"); d_gfactor1 = k_gfactor1.template view<DeviceType>(); h_gfactor1 = k_gfactor1.template view<LMPHostType>(); d_gfactor2 = k_gfactor2.template view<DeviceType>(); h_gfactor2 = k_gfactor2.template view<LMPHostType>(); d_ratio = k_ratio.template view<DeviceType>(); h_ratio = k_ratio.template view<LMPHostType>(); // optional args for (int i = 1; i <= ntypes; i++) ratio[i] = 1.0; k_ratio.template modify<LMPHostType>(); if(gjfflag){ nvalues = 3; grow_arrays(atomKK->nmax); atom->add_callback(0); // initialize franprev to zero for (int i = 0; i < atomKK->nlocal; i++) { franprev[i][0] = 0.0; franprev[i][1] = 0.0; franprev[i][2] = 0.0; } k_franprev.template modify<LMPHostType>(); } if(zeroflag){ k_fsumall = tdual_double_1d_3n("langevin:fsumall"); h_fsumall = k_fsumall.template view<LMPHostType>(); d_fsumall = k_fsumall.template view<DeviceType>(); } execution_space = ExecutionSpaceFromDevice<DeviceType>::space; datamask_read = V_MASK | F_MASK | MASK_MASK | RMASS_MASK | TYPE_MASK; datamask_modify = F_MASK; } /* ---------------------------------------------------------------------- */ template<class DeviceType> FixLangevinKokkos<DeviceType>::~FixLangevinKokkos() { memoryKK->destroy_kokkos(k_gfactor1,gfactor1); memoryKK->destroy_kokkos(k_gfactor2,gfactor2); memoryKK->destroy_kokkos(k_ratio,ratio); memoryKK->destroy_kokkos(k_flangevin,flangevin); if(gjfflag) memoryKK->destroy_kokkos(k_franprev,franprev); memoryKK->destroy_kokkos(k_tforce,tforce); } /* ---------------------------------------------------------------------- */ template<class DeviceType> void FixLangevinKokkos<DeviceType>::init() { FixLangevin::init(); if(oflag) error->all(FLERR,"Fix langevin omega is not yet implemented with kokkos"); if(ascale) error->all(FLERR,"Fix langevin angmom is not yet implemented with kokkos"); // prefactors are modified in the init k_gfactor1.template modify<LMPHostType>(); k_gfactor2.template modify<LMPHostType>(); } /* ---------------------------------------------------------------------- */ template<class DeviceType> void FixLangevinKokkos<DeviceType>::grow_arrays(int nmax) { memoryKK->grow_kokkos(k_franprev,franprev,nmax,3,"langevin:franprev"); d_franprev = k_franprev.template view<DeviceType>(); h_franprev = k_franprev.template view<LMPHostType>(); } /* ---------------------------------------------------------------------- */ template<class DeviceType> void FixLangevinKokkos<DeviceType>::post_force(int vflag) { // sync the device views which might have been modified on host atomKK->sync(execution_space,datamask_read); rmass = atomKK->k_rmass.view<DeviceType>(); f = atomKK->k_f.template view<DeviceType>(); v = atomKK->k_v.template view<DeviceType>(); type = atomKK->k_type.template view<DeviceType>(); mask = atomKK->k_mask.template view<DeviceType>(); k_gfactor1.template sync<DeviceType>(); k_gfactor2.template sync<DeviceType>(); k_ratio.template sync<DeviceType>(); if(gjfflag) k_franprev.template sync<DeviceType>(); boltz = force->boltz; dt = update->dt; mvv2e = force->mvv2e; ftm2v = force->ftm2v; fran_prop_const = sqrt(24.0*boltz/t_period/dt/mvv2e); compute_target(); // modifies tforce vector, hence sync here k_tforce.template sync<DeviceType>(); double fsum[3],fsumall[3]; bigint count; int nlocal = atomKK->nlocal; if (zeroflag) { fsum[0] = fsum[1] = fsum[2] = 0.0; count = group->count(igroup); if (count == 0) error->all(FLERR,"Cannot zero Langevin force of 0 atoms"); } // reallocate flangevin if necessary if (tallyflag) { if (nlocal > maxatom1) { memoryKK->destroy_kokkos(k_flangevin,flangevin); maxatom1 = atomKK->nmax; memoryKK->create_kokkos(k_flangevin,flangevin,maxatom1,3,"langevin:flangevin"); d_flangevin = k_flangevin.template view<DeviceType>(); h_flangevin = k_flangevin.template view<LMPHostType>(); } } // account for bias velocity if(tbiasflag == BIAS){ atomKK->sync(temperature->execution_space,temperature->datamask_read); temperature->compute_scalar(); temperature->remove_bias_all(); // modifies velocities // if temeprature compute is kokkosized host-devcie comm won't be needed atomKK->modified(temperature->execution_space,temperature->datamask_modify); atomKK->sync(execution_space,temperature->datamask_modify); } // compute langevin force in parallel on the device FSUM s_fsum; if (tstyle == ATOM) if (gjfflag) if (tallyflag) if (tbiasflag == BIAS) if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,1,1,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,1,1,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,1,1,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,1,1,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,1,0,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,1,0,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,1,0,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,1,0,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (tbiasflag == BIAS) if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,0,1,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,0,1,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,0,1,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,0,1,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,0,0,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,0,0,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,0,0,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,1,0,0,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (tallyflag) if (tbiasflag == BIAS) if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,1,1,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,1,1,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,1,1,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,1,1,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,1,0,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,1,0,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,1,0,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,1,0,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (tbiasflag == BIAS) if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,0,1,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,0,1,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,0,1,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,0,1,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,0,0,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,0,0,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,0,0,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,1,0,0,0,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (gjfflag) if (tallyflag) if (tbiasflag == BIAS) if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,1,1,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,1,1,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,1,1,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,1,1,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,1,0,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,1,0,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,1,0,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,1,0,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (tbiasflag == BIAS) if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,0,1,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,0,1,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,0,1,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,0,1,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,0,0,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,0,0,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,0,0,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,1,0,0,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (tallyflag) if (tbiasflag == BIAS) if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,1,1,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,1,1,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,1,1,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,1,1,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,1,0,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,1,0,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,1,0,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,1,0,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (tbiasflag == BIAS) if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,0,1,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,0,1,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,0,1,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,0,1,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (rmass.data()) if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,0,0,1,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,0,0,1,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } else if (zeroflag) { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,0,0,0,1> post_functor(this); Kokkos::parallel_reduce(nlocal,post_functor,s_fsum); } else { FixLangevinKokkosPostForceFunctor<DeviceType,0,0,0,0,0,0> post_functor(this); Kokkos::parallel_for(nlocal,post_functor); } if(tbiasflag == BIAS){ atomKK->sync(temperature->execution_space,temperature->datamask_read); temperature->restore_bias_all(); // modifies velocities atomKK->modified(temperature->execution_space,temperature->datamask_modify); atomKK->sync(execution_space,temperature->datamask_modify); } // set modify flags for the views modified in post_force functor if (gjfflag) k_franprev.template modify<DeviceType>(); if (tallyflag) k_flangevin.template modify<DeviceType>(); // set total force to zero if (zeroflag) { fsum[0] = s_fsum.fx; fsum[1] = s_fsum.fy; fsum[2] = s_fsum.fz; MPI_Allreduce(fsum,fsumall,3,MPI_DOUBLE,MPI_SUM,world); h_fsumall(0) = fsumall[0]/count; h_fsumall(1) = fsumall[1]/count; h_fsumall(2) = fsumall[2]/count; k_fsumall.template modify<LMPHostType>(); k_fsumall.template sync<DeviceType>(); // set total force zero in parallel on the device FixLangevinKokkosZeroForceFunctor<DeviceType> zero_functor(this); Kokkos::parallel_for(nlocal,zero_functor); } // f is modified by both post_force and zero_force functors atomKK->modified(execution_space,datamask_modify); // thermostat omega and angmom // if (oflag) omega_thermostat(); // if (ascale) angmom_thermostat(); } /* ---------------------------------------------------------------------- */ template<class DeviceType> template<int Tp_TSTYLEATOM, int Tp_GJF, int Tp_TALLY, int Tp_BIAS, int Tp_RMASS, int Tp_ZERO> KOKKOS_INLINE_FUNCTION FSUM FixLangevinKokkos<DeviceType>::post_force_item(int i) const { FSUM fsum; double fdrag[3],fran[3]; double gamma1,gamma2; double fswap; double tsqrt_t = tsqrt; if (mask[i] & groupbit) { rand_type rand_gen = rand_pool.get_state(); if(Tp_TSTYLEATOM) tsqrt_t = sqrt(d_tforce[i]); if(Tp_RMASS){ gamma1 = -rmass[i] / t_period / ftm2v; gamma2 = sqrt(rmass[i]) * fran_prop_const / ftm2v; gamma1 *= 1.0/d_ratio[type[i]]; gamma2 *= 1.0/sqrt(d_ratio[type[i]]) * tsqrt_t; } else { gamma1 = d_gfactor1[type[i]]; gamma2 = d_gfactor2[type[i]] * tsqrt_t; } fran[0] = gamma2 * (rand_gen.drand() - 0.5); //(random->uniform()-0.5); fran[1] = gamma2 * (rand_gen.drand() - 0.5); //(random->uniform()-0.5); fran[2] = gamma2 * (rand_gen.drand() - 0.5); //(random->uniform()-0.5); if(Tp_BIAS){ fdrag[0] = gamma1*v(i,0); fdrag[1] = gamma1*v(i,1); fdrag[2] = gamma1*v(i,2); if (v(i,0) == 0.0) fran[0] = 0.0; if (v(i,1) == 0.0) fran[1] = 0.0; if (v(i,2) == 0.0) fran[2] = 0.0; } else { fdrag[0] = gamma1*v(i,0); fdrag[1] = gamma1*v(i,1); fdrag[2] = gamma1*v(i,2); } if (Tp_GJF) { fswap = 0.5*(fran[0]+d_franprev(i,0)); d_franprev(i,0) = fran[0]; fran[0] = fswap; fswap = 0.5*(fran[1]+d_franprev(i,1)); d_franprev(i,1) = fran[1]; fran[1] = fswap; fswap = 0.5*(fran[2]+d_franprev(i,2)); d_franprev(i,2) = fran[2]; fran[2] = fswap; fdrag[0] *= gjffac; fdrag[1] *= gjffac; fdrag[2] *= gjffac; fran[0] *= gjffac; fran[1] *= gjffac; fran[2] *= gjffac; f(i,0) *= gjffac; f(i,1) *= gjffac; f(i,2) *= gjffac; } f(i,0) += fdrag[0] + fran[0]; f(i,1) += fdrag[1] + fran[1]; f(i,2) += fdrag[2] + fran[2]; if (Tp_TALLY) { d_flangevin(i,0) = fdrag[0] + fran[0]; d_flangevin(i,1) = fdrag[1] + fran[1]; d_flangevin(i,2) = fdrag[2] + fran[2]; } if (Tp_ZERO) { fsum.fx = fran[0]; fsum.fy = fran[1]; fsum.fz = fran[2]; } rand_pool.free_state(rand_gen); } return fsum; } /* ---------------------------------------------------------------------- */ template<class DeviceType> KOKKOS_INLINE_FUNCTION void FixLangevinKokkos<DeviceType>::zero_force_item(int i) const { if (mask[i] & groupbit) { f(i,0) -= d_fsumall[0]; f(i,1) -= d_fsumall[1]; f(i,2) -= d_fsumall[2]; } } /* ---------------------------------------------------------------------- set current t_target and t_sqrt ------------------------------------------------------------------------- */ template<class DeviceType> void FixLangevinKokkos<DeviceType>::compute_target() { atomKK->sync(Host, MASK_MASK); mask = atomKK->k_mask.template view<DeviceType>(); int nlocal = atomKK->nlocal; double delta = update->ntimestep - update->beginstep; if (delta != 0.0) delta /= update->endstep - update->beginstep; // if variable temp, evaluate variable, wrap with clear/add // reallocate tforce array if necessary if (tstyle == CONSTANT) { t_target = t_start + delta * (t_stop-t_start); tsqrt = sqrt(t_target); } else { modify->clearstep_compute(); if (tstyle == EQUAL) { t_target = input->variable->compute_equal(tvar); if (t_target < 0.0) error->one(FLERR,"Fix langevin variable returned negative temperature"); tsqrt = sqrt(t_target); } else { if (atom->nmax > maxatom2) { maxatom2 = atom->nmax; memoryKK->destroy_kokkos(k_tforce,tforce); memoryKK->create_kokkos(k_tforce,tforce,maxatom2,"langevin:tforce"); d_tforce = k_tforce.template view<DeviceType>(); h_tforce = k_tforce.template view<LMPHostType>(); } input->variable->compute_atom(tvar,igroup,tforce,1,0); // tforce is modified on host k_tforce.template modify<LMPHostType>(); for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) if (h_tforce[i] < 0.0) error->one(FLERR, "Fix langevin variable returned negative temperature"); } modify->addstep_compute(update->ntimestep + 1); } } /* ---------------------------------------------------------------------- */ template<class DeviceType> void FixLangevinKokkos<DeviceType>::reset_dt() { if (atomKK->mass) { for (int i = 1; i <= atomKK->ntypes; i++) { h_gfactor2[i] = sqrt(atomKK->mass[i]) * sqrt(24.0*force->boltz/t_period/update->dt/force->mvv2e) / force->ftm2v; h_gfactor2[i] *= 1.0/sqrt(h_ratio[i]); } k_gfactor2.template modify<LMPHostType>(); } } /* ---------------------------------------------------------------------- */ template<class DeviceType> double FixLangevinKokkos<DeviceType>::compute_scalar() { if (!tallyflag || flangevin == NULL) return 0.0; v = atomKK->k_v.template view<DeviceType>(); mask = atomKK->k_mask.template view<DeviceType>(); // capture the very first energy transfer to thermal reservoir if (update->ntimestep == update->beginstep) { energy_onestep = 0.0; atomKK->sync(execution_space,V_MASK | MASK_MASK); int nlocal = atomKK->nlocal; k_flangevin.template sync<DeviceType>(); FixLangevinKokkosTallyEnergyFunctor<DeviceType> scalar_functor(this); Kokkos::parallel_reduce(nlocal,scalar_functor,energy_onestep); energy = 0.5*energy_onestep*update->dt; } // convert midstep energy back to previous fullstep energy double energy_me = energy - 0.5*energy_onestep*update->dt; double energy_all; MPI_Allreduce(&energy_me,&energy_all,1,MPI_DOUBLE,MPI_SUM,world); return -energy_all; } /* ---------------------------------------------------------------------- */ template<class DeviceType> KOKKOS_INLINE_FUNCTION double FixLangevinKokkos<DeviceType>::compute_energy_item(int i) const { double energy; if (mask[i] & groupbit) energy = d_flangevin(i,0)*v(i,0) + d_flangevin(i,1)*v(i,1) + d_flangevin(i,2)*v(i,2); return energy; } /* ---------------------------------------------------------------------- tally energy transfer to thermal reservoir ------------------------------------------------------------------------- */ template<class DeviceType> void FixLangevinKokkos<DeviceType>::end_of_step() { if (!tallyflag) return; v = atomKK->k_v.template view<DeviceType>(); mask = atomKK->k_mask.template view<DeviceType>(); atomKK->sync(execution_space,V_MASK | MASK_MASK); int nlocal = atomKK->nlocal; energy_onestep = 0.0; k_flangevin.template sync<DeviceType>(); FixLangevinKokkosTallyEnergyFunctor<DeviceType> tally_functor(this); Kokkos::parallel_reduce(nlocal,tally_functor,energy_onestep); energy += energy_onestep*update->dt; } /* ---------------------------------------------------------------------- copy values within local atom-based array ------------------------------------------------------------------------- */ template<class DeviceType> void FixLangevinKokkos<DeviceType>::copy_arrays(int i, int j, int delflag) { for (int m = 0; m < nvalues; m++) h_franprev(j,m) = h_franprev(i,m); k_franprev.template modify<LMPHostType>(); } /* ---------------------------------------------------------------------- */ template<class DeviceType> void FixLangevinKokkos<DeviceType>::cleanup_copy() { random = NULL; tstr = NULL; gfactor1 = NULL; gfactor2 = NULL; ratio = NULL; id_temp = NULL; flangevin = NULL; tforce = NULL; gjfflag = 0; franprev = NULL; id = style = NULL; vatom = NULL; } namespace LAMMPS_NS { template class FixLangevinKokkos<LMPDeviceType>; #ifdef KOKKOS_ENABLE_CUDA template class FixLangevinKokkos<LMPHostType>; #endif }
28,786
10,730
#pragma once #ifndef BE_GFX_TEX_DDS_READER_HPP_ #define BE_GFX_TEX_DDS_READER_HPP_ #include "default_texture_reader.hpp" #include "betx_payload_compression_mode.hpp" #include <be/core/logging.hpp> namespace be::gfx::tex { /////////////////////////////////////////////////////////////////////////////// bool is_dds(const Buf<const UC>& buf) noexcept; /////////////////////////////////////////////////////////////////////////////// class DdsReader final : public detail::DefaultTextureReader { public: DdsReader(bool strict = false, Log& log = default_log()); private: TextureFileFormat format_impl_() noexcept final; TextureFileInfo info_impl_(std::error_code& ec) noexcept final; Texture texture_(std::error_code& ec) noexcept final; Image image_(std::error_code& ec, std::size_t layer, std::size_t face, std::size_t level) noexcept final; }; } // be::gfx::tex #endif
890
286
#include "lab3.h" #include "config.h" #include "cube.h" #include "graphics_node.h" #include "mesh.h" #include "monochrome_material.h" #include "types.h" #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <iostream> using namespace Display; Lab3::Lab3() {} Lab3::~Lab3() {} const float32 movingDistance = 0.05f; const float32 rotationAngle = 5.0f; unsigned int currentObject = 0; bool Lab3::Open() { App::Open(); this->window = new Display::Window; window->SetKeyPressFunction([this](int32 keyCode, int32, int32 action, int32) { switch (keyCode) { case GLFW_KEY_1: case GLFW_KEY_2: case GLFW_KEY_3: currentObject = keyCode - GLFW_KEY_1; break; case GLFW_KEY_W: this->objects[currentObject].translate(glm::vec3(0, 0, -movingDistance)); break; case GLFW_KEY_A: this->objects[currentObject].translate(glm::vec3(-movingDistance, 0, 0)); break; case GLFW_KEY_S: this->objects[currentObject].translate(glm::vec3(0, 0, movingDistance)); break; case GLFW_KEY_D: this->objects[currentObject].translate(glm::vec3(movingDistance, 0, 0)); break; case GLFW_KEY_E: this->objects[currentObject].translate(glm::vec3(0, movingDistance, 0)); break; case GLFW_KEY_Q: this->objects[currentObject].translate(glm::vec3(0, -movingDistance, 0)); break; case GLFW_KEY_I: this->objects[currentObject].rotate(-rotationAngle, glm::vec3(1, 0, 0)); break; case GLFW_KEY_J: this->objects[currentObject].rotate(-rotationAngle, glm::vec3(0, 1, 0)); break; case GLFW_KEY_K: this->objects[currentObject].rotate(rotationAngle, glm::vec3(1, 0, 0)); break; case GLFW_KEY_L: this->objects[currentObject].rotate(rotationAngle, glm::vec3(0, 1, 0)); break; case GLFW_KEY_U: this->objects[currentObject].rotate(rotationAngle, glm::vec3(0, 0, 1)); break; case GLFW_KEY_O: this->objects[currentObject].rotate(-rotationAngle, glm::vec3(0, 0, 1)); break; case GLFW_KEY_ESCAPE: this->window->Close(); default: break; } }); if (this->window->Open()) { // set clear color to gray glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glEnable(GL_DEPTH_TEST); this->objects = std::vector<GraphicsNode>{ createCube(glm::vec3(0), RGBA(1, 0, 0, 1)), createCube(glm::vec3(1.0f, -1.0f, -2.0f), RGBA(0, 1, 0, 1)), createCube(glm::vec3(-4.0f, 2.0f, -8.0f), RGBA(0, 0, 1, 1))}; return true; } return false; } void Lab3::Run() { while (this->window->IsOpen()) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); this->window->Update(); for (const auto &object : objects) { object.draw(); } this->window->SwapBuffers(); } }
2,834
1,136
#include <MainWindow.h> #include <FDCore/FileUtils.h> #include <FDQUI/GUI/OpenGLApplication.h> #include <FDQUI/GUI/View/TransformDelegate.h> #include <FDQUI/GUI/Widget/VectorWidget.h> #include <FDQUI/Model/TransformModel.h> #include <QOpenGLTexture> #include <QDockWidget> #include <QTimer> #include <QTreeView> #include <QVBoxLayout> #include <QHBoxLayout> #include <qlogging.h> /* void FDQUI::OpenGLWidget::paintGL() { m_timeMgr.start(); m_program = createShaderProgram(); m_tex = loadTexture("../../FDGL/test/resources/wall.jpg"); m_program.bind(); FD3D::Projection &proj = m_cam.projection; proj.setFov(glm::radians(45.0f)); proj.setWidth(getWidth()); proj.setHeight(getHeight()); proj.setNear(0.1f); proj.setFar(100.0f); proj.setType(FD3D::ProjectionType::Perspective); glClear(getClearMask()); if(m_renderStrategy) m_renderStrategy(*this); FD3D::Transform m_transform; std::vector<FD3D::Mesh*> meshes = m_scene.getComponentsAs<FD3D::Mesh>(); FD3D::Projection &proj = m_cam.projection; // bind textures on corresponding texture units m_tex.activateTexture(0); m_tex.bind(FDGL::TextureTarget::Texture2D); double t2 = 0; float radius = 10.0f; float camX = sin(t2) * radius; float camZ = cos(t2) * radius; m_cam.setPosition(glm::vec3(camX, 0.0f, camZ)); m_cam.setRotation(glm::vec3(0.0f, t2, 0.0f)); // activate shader m_program.bind(); m_program.setUniform("texture", 0); m_program.setUniform(1, m_cam.getMatrix()); m_program.setUniform(2, proj.getMatrix()); m_program.setUniform(0, m_transform.getMatrix()); m_vao.bind(); FDGL::drawElements<uint32_t>(FDGL::DrawMode::Triangles, meshes[0]->getNumberOfIndices(), nullptr); if (!qApp->loadOpenGLFunctions(qApp->getProcAddressFunc())) { qFatal("failed to load OpenGl functions"); qApp->exit(-1); } qApp->enableDepth(); qApp->enableFaceCulling(); qApp->enable(GL_DEBUG_OUTPUT); glDebugMessageCallback(MessageCallback, nullptr); setClearColor(glm::vec4(0.2f, 0.3f, 0.3f, 1.0f)); setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_timeMgr.start(); FD3D::SceneLoader loader; loader.setTextureLoader([](const std::string &path){ return loadTexture(path); }); loader.setEmbeddedTextureLoader([](const aiTexture *texture){ return loadTexture(texture); }); assert(loader.loadScene(m_scene, "../../FDGL/test/resources/crate/CrateModel.obj", aiProcess_Triangulate )); std::vector<FD3D::Mesh*> meshes = m_scene.getComponentsAs<FD3D::Mesh>(); std::vector<FD3D::Material*> mat = m_scene.getComponentsAs<FD3D::Material>(); m_program = createShaderProgram(); m_tex = loadTexture("../../FDGL/test/resources/wall.jpg"); m_vbo.create(); m_vbo.bind(FDGL::BufferTarget::VertexAttribute); m_vbo.allocate(sizeof(float) * meshes[0]->getNumberOfVertices() * meshes[0]->getVertexSize(), FDGL::BufferUsage::StaticDraw, meshes[0]->getVertices()); m_ebo.create(); m_ebo.bind(FDGL::BufferTarget::VertexIndex); m_ebo.allocate(sizeof(uint32_t) * meshes[0]->getNumberOfIndices(), FDGL::BufferUsage::StaticDraw, meshes[0]->getIndices()); m_vao.create(); m_vao.setFunction([](FDGL::OpenGLBuffer &vbo, FDGL::OpenGLBuffer &ebo, FD3D::AbstractMesh &m) { vbo.bind(FDGL::BufferTarget::VertexAttribute); ebo.bind(FDGL::BufferTarget::VertexIndex); size_t s = m.getStride() * sizeof(float); FDGL::setAttribFromBuffer<GL_FLOAT, 3, false>(0, s, static_cast<size_t>(m.getComponentOffset(FD3D::VertexComponentType::Position)) * sizeof(float)); FDGL::enableAttrib(0); FDGL::setAttribFromBuffer<GL_FLOAT, 3, false>(1, s, static_cast<size_t>(m.getComponentOffset(FD3D::VertexComponentType::Normal)) * sizeof(float)); FDGL::enableAttrib(1); FDGL::setAttribFromBuffer<GL_FLOAT, 2, false>(2, s, static_cast<size_t>(m.getComponentOffset(FD3D::VertexComponentType::Texture)) * sizeof(float)); FDGL::enableAttrib(2); }, std::ref(m_vbo), std::ref(m_ebo), std::ref(*meshes.front())); m_program.bind(); FD3D::Projection &proj = m_cam.projection; proj.setFov(glm::radians(45.0f)); proj.setWidth(getWidth()); proj.setHeight(getHeight()); proj.setNear(0.1f); proj.setFar(100.0f); proj.setType(FD3D::ProjectionType::Perspective); }*/ using namespace std; /*static FDGL::OpenGLShaderProgramWrapper createShaderProgram() { FDGL::OpenGLShaderProgramWrapper program; FDGL::OpenGLShader v_shad; v_shad.create(FDGL::ShaderType::Vertex); v_shad.setSource(std::string(FDCore::readFile("../../FDGL/test/resources/vertex.vert").get())); if(!v_shad.compile()) { std::string msg = "Cannot compile vertex shader: "; msg += v_shad.getCompileErrors(); cerr << msg << endl; return FDGL::OpenGLShaderProgramWrapper(); } FDGL::OpenGLShader f_shad; f_shad.create(FDGL::ShaderType::Fragment); f_shad.setSource(std::string(FDCore::readFile("../../FDGL/test/resources/frag.frag").get())); if(!f_shad.compile()) { std::string msg = "Cannot compile fragment shader: "; msg += f_shad.getCompileErrors(); cerr << msg << endl; return FDGL::OpenGLShaderProgramWrapper(); } // link shaders program.create(); program.attach(v_shad); program.attach(f_shad); if(!program.link()) { std::string msg = "Cannot link shader program: "; msg += program.getLinkErrors(); cerr << msg << endl; return FDGL::OpenGLShaderProgramWrapper(); } return program; }*/ class Renderer { protected: FD3D::Camera m_cam; QTimer m_rendertimer; QOpenGLTexture *m_tex; FD3D::Scene m_scene; FDGL::OpenGLBuffer m_vbo; FDGL::OpenGLBuffer m_ebo; FDGL::OpenGLVertexArray m_vao; public: Renderer(); void onInit(FDGL::BaseOpenGLWindow &w); void onQuit(FDGL::BaseOpenGLWindow &w); void onRender(FDGL::BaseOpenGLWindow &w); void onResize(FDGL::BaseOpenGLWindow &w, int width, int height); void onError(FDGL::ErrorSoure source, FDGL::ErrorType type, uint32_t id, FDGL::ErrorSeverity level, const std::string &msg) const; private: static void debugCallbackHelper(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); }; static Renderer renderer; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { prepareGLWidget(); prepareLeftDock(); } MainWindow::~MainWindow() { } void MainWindow::prepareGLWidget() { m_glWindow = new FDQUI::OpenGLWidget(); if(!m_glWindow->create(800, 600, "Test window")) { qFatal("failed to create window"); qApp->exit(-1); } setCentralWidget(m_glWindow); /*m_glWindow->setInitializeStrategy(&Renderer::onInit, &renderer); m_glWindow->setQuitStrategy(&Renderer::onQuit, &renderer); m_glWindow->setRenderStrategy(&Renderer::onRender, &renderer); m_glWindow->setResizeStrategy(&Renderer::onResize, &renderer);*/ } void MainWindow::prepareLeftDock() { QDockWidget *leftDock = new QDockWidget(); QWidget *wid = new QWidget(); QVBoxLayout *vlay = new QVBoxLayout(); QTreeView *view = new QTreeView(); FDQUI::VectorWidget *vectorWid = new FDQUI::VectorWidget(); FDQUI::TransformModel *model = new FDQUI::TransformModel(view); model->setTranfsorm(&m_transform); vectorWid->setVector(m_transform.getPosition()); view->setHeaderHidden(true); view->setModel(model); view->setItemDelegate(new FDQUI::TransformDelegate(view)); vlay->addWidget(view); vlay->addWidget(vectorWid); wid->setLayout(vlay); leftDock->setWidget(wid); addDockWidget(Qt::LeftDockWidgetArea, leftDock); } Renderer::Renderer() : m_tex(nullptr) { FD3D::Projection &proj = m_cam.projection; proj.setFov(glm::radians(45.0f)); proj.setNear(0.1f); proj.setFar(100.0f); proj.setType(FD3D::ProjectionType::Perspective); } void Renderer::onInit(FDGL::BaseOpenGLWindow &w) { if (!qApp->loadOpenGLFunctions(qApp->getProcAddressFunc())) { qFatal("failed to load OpenGl functions"); qApp->exit(-1); } w.setClearColor(glm::vec4(0.2f, 0.3f, 0.3f, 1.0f)); w.setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_rendertimer.connect(&m_rendertimer, &QTimer::timeout, static_cast<FDQUI::OpenGLWidget*>(&w), QOverload<>::of(&FDQUI::OpenGLWidget::update)); qApp->enableDepth(); qApp->enableFaceCulling(); qApp->enable(GL_DEBUG_OUTPUT); glDebugMessageCallback(&Renderer::debugCallbackHelper, this); m_rendertimer.start(1000/60); m_tex = new QOpenGLTexture(QOpenGLTexture::Target2D); m_tex->create(); m_tex->setData(QImage("../../FDGL/test/resources/wall.jpg").mirrored()); FD3D::SceneLoader loader; loader.setTextureLoader([](const std::string &path){ return QOpenGLTexture(QImage(path.c_str()).mirrored()).textureId(); }); loader.setEmbeddedTextureLoader([](const aiTexture *texture){ QImage img; QOpenGLTexture tex(QOpenGLTexture::Target2D); if(texture->mHeight == 0) { if(!img.loadFromData(reinterpret_cast<uint8_t*>(texture->pcData), static_cast<int>(texture->mWidth), QString(texture->achFormatHint).toUpper().toStdString().c_str())) return 0u; tex.setData(img); } else { /*QOpenGLTexture::PixelType type = QOpenGLTexture::NoPixelType; if(QString(texture->achFormatHint) == "rgba8888" || QString(texture->achFormatHint) == "argb8888") type = QOpenGLTexture::UInt32_RGBA8; else if(QString(texture->achFormatHint) == "rgba5650") type = QOpenGLTexture::UInt16_R5G6B5; else qCritical("Unsupported texture format: %s for texture %s", texture->achFormatHint, texture->mFilename.C_Str());*/ //tex.setData(0, 0, QOpenGLTexture::RGBA, type, reinterpret_cast<void*>(texture->pcData)); } return tex.textureId(); }); assert(loader.loadScene(m_scene, "../../FDGL/test/resources/crate/CrateModel.obj", aiProcess_Triangulate )); } void Renderer::onQuit(FDGL::BaseOpenGLWindow &) { delete m_tex; } void Renderer::onRender(FDGL::BaseOpenGLWindow &w) { w.clear(); } void Renderer::onResize(FDGL::BaseOpenGLWindow &, int width, int height) { m_cam.projection.setWidth(width); m_cam.projection.setHeight(height); } void Renderer::onError(FDGL::ErrorSoure source, FDGL::ErrorType type, uint32_t id, FDGL::ErrorSeverity level, const std::string &msg) const { constexpr const char *format = "GL_DEBUG_MESSAGE:" "\n{" "\n source: %s," "\n type: %s," "\n severity: %s," "\n id: %u" "\n message: %s" "\n}"; switch(level) { case FDGL::ErrorSeverity::Low: qWarning(format, FDGL::errorSourceToString(source).c_str(), FDGL::errorTypeToString(type).c_str(), FDGL::errorSeverityToString(level).c_str(), id, msg.data()); break; case FDGL::ErrorSeverity::Medium: qCritical(format, FDGL::errorSourceToString(source).c_str(), FDGL::errorTypeToString(type).c_str(), FDGL::errorSeverityToString(level).c_str(), id, msg.data()); break; case FDGL::ErrorSeverity::High: qFatal(format, FDGL::errorSourceToString(source).c_str(), FDGL::errorTypeToString(type).c_str(), FDGL::errorSeverityToString(level).c_str(), id, msg.data()); break; default: qDebug(format, FDGL::errorSourceToString(source).c_str(), FDGL::errorTypeToString(type).c_str(), FDGL::errorSeverityToString(level).c_str(), id, msg.data()); break; } } void Renderer::debugCallbackHelper(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { const Renderer *r = reinterpret_cast<const Renderer *>(userParam); r->onError(static_cast<FDGL::ErrorSoure>(source), static_cast<FDGL::ErrorType>(type), id, static_cast<FDGL::ErrorSeverity>(severity), std::string(message, static_cast<size_t>(length))); }
13,564
4,671
#ifndef DEEPSORT_HPP #define DEEPSORT_HPP #include <memory> #include <vector> #include <opencv2/opencv.hpp> namespace DeepSORT { struct Box{ float left, top, right, bottom; cv::Mat feature; Box() = default; Box(float left, float top, float right, float bottom):left(left), top(top), right(right), bottom(bottom){} const float width() const{return right - left;} const float height() const{return bottom - top;} const cv::Point2f center() const{return cv::Point2f((left+right)/2, (top+bottom)/2);} }; template<typename _T> inline Box convert_to_box(const _T& b){ return Box(b.left, b.top, b.right, b.bottom); } template<typename _T> inline cv::Rect convert_box_to_rect(const _T& b){ return cv::Rect(b.left, b.top, b.right-b.left, b.bottom-b.top); } enum class State : int{ Tentative = 1, Confirmed = 2, Deleted = 3 }; struct TrackerConfig{ int max_age = 150; int nhit = 3; float distance_threshold = 100; int nbuckets = 0; bool has_feature = false; // kalman // /** 初始状态 **/ float initiate_state[8]; // /** 每一侦的运动量协方差,下一侦 = 当前帧 + 运动量 **/ float per_frame_motion[8]; // /** 测量噪声,把输入映射到测量空间中后的噪声 **/ float noise[4]; void set_initiate_state(const std::vector<float>& values); void set_per_frame_motion(const std::vector<float>& values); void set_noise(const std::vector<float>& values); TrackerConfig(); }; typedef std::vector<Box> BBoxes; class TrackObject{ public: virtual int id() const = 0; virtual State state() const = 0; virtual Box predict_box() const = 0; virtual Box last_position() const = 0; virtual bool is_confirmed() const = 0; virtual int time_since_update() const = 0; virtual std::vector<cv::Point> trace_line() const = 0; virtual int trace_size() const = 0; virtual Box& location(int time_since_update=0) = 0; virtual const cv::Mat& feature_bucket() const = 0; }; class Tracker{ public: virtual std::vector<TrackObject *> get_objects() = 0; virtual void update(const BBoxes& boxes) = 0; }; std::shared_ptr<Tracker> create_tracker( const TrackerConfig& config = TrackerConfig() ); } #endif // DEEPSORT_HPP
2,198
851
#pragma once #include "exmath.h" #include "exfrac.h" int RoundToINT(double e) { return (int)(e + 0.5); } double Math::Multiply(std::initializer_list<double> e) { double a = 1; std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { a *= *it; } return a; } double Math::add_Array(double e[]) { double a = 0; for (int i = 0; i != sizeof(e); i++) { a += e[i]; } return a; } double Math::minus_Array(double e[]) { double a = 0; for (int i = 0; i != sizeof(e); i++) { a -= e[i]; } return a; } double Math::Add(std::initializer_list<double> e) { double a = 0; std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { a += *it; } return a; } Fraction Math::Add(std::initializer_list<Fraction> e) { Fraction a(0, 0); std::initializer_list<Fraction>::iterator it; for (it = e.begin(); it != e.end(); ++it) { a = a.Add(*it); } return a; } Fraction Math::Add(Fraction fx, Fraction fy) { fx = fx.Add(fy); return fx; } double Math::Minus(std::initializer_list<double> e) { double a = 0; std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { a -= *it; } return a; } void Math::Restart() { _x.clear(); } void Math::Append(std::initializer_list<double> e) { std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { _x.push_back(*it); } } Math::Math(std::initializer_list<double> e) { std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { _x.push_back(*it); } } Math::Math(std::vector<double> e) { _x = e; } Math& operator+=(Math &obj, double p) { obj._x.push_back(p); return obj; } std::vector<double> Math::anti_diff(std::vector<double> e) { double s = e.size() - 1; for (std::vector<double>::iterator i = e.begin(); i != e.end(); ++i) { (*i) /= s; (*i) *= s; s--; } return e; } double Math::diff(double x1, double c) { return x1; } std::vector<double> Math::diff(std::vector<double> e) { double s = e.size() - 1; for (std::vector<double>::iterator i = e.begin(); i != e.end(); ++i) { (*i) /= s; s--; } return e; } std::vector<double> Math::diff(double x2, double x1, double c) { std::vector<double> a(0); a.push_back(x2 / 2); a.push_back(x1 / 1); return a; } std::vector<double> Math::diff(double x3, double x2, double x1, double c) { std::vector<double> a(0); a.push_back(x3 / 3); a.push_back(x2 / 2); a.push_back(x1 / 1); return a; } template<typename T> std::ostream& operator<< (std::ostream& out, const std::vector<T>& v) { out << "["; size_t last = v.size() - 1; for (size_t i = 0; i < v.size(); ++i) { out << v[i]; if (i != last) out << ", "; } out << "]"; return out; } std::vector<double> sqrt_all(std::vector<double> e) { double s = e.size() - 1; for (std::vector<double>::iterator i = e.begin(); i != e.end(); ++i) { *i = sqrt(*i); } return e; } double square(double e) { return e*e; } std::vector<double> square_all(std::vector<double> e) { double s = e.size() - 1; for (std::vector<double>::iterator i = e.begin(); i != e.end(); ++i) { (*i) *= (*i); } return e; } double cubert(double e) { return pow(e, 1 / 3.); } double xroot(double e, double n) { return pow(e, 1 / n); } Fraction cubert(Fraction a) { return Fraction(cubert(a.numerator), cubert(a.denominator)); } Fraction xroot(Fraction e, double n) { return Fraction(xroot(e.numerator, n), xroot(e.denominator, n)); }
3,619
1,556
/* * cpu.cpp * CPU Management Unit implementation */ // includes #include <cstring> #include <cstdlib> #include <ctime> #include "constants.h" #include "except.h" #include "cpu.h" // constants constexpr int NUM_REGISTERS = 16; enum Register { V0 = 0x00, VF = 0x0F }; // class structure struct CPU::OpaqueData { MMU *pMMU {nullptr}; // screen data byte_t *pScreen {nullptr}; word_t screenWidth {0}; // CPU registers byte_t V[NUM_REGISTERS] {}; word_t I {}; word_t PC {}; word_t SP {}; void create(); void destroy(); void reset(); bool putPixel(int x, int y); void clearScreen(); }; // Initialize the structure void CPU::OpaqueData::create() { // set the screen pointer pScreen = pMMU->getPointer(MemoryZone::SCREEN_BEGIN); screenWidth = pMMU->readW(MemoryRegister::SCREEN_WIDTH); // reset the CPU reset(); } // De-initialize the structure void CPU::OpaqueData::destroy() { } // Reset the CPU void CPU::OpaqueData::reset() { I = MemoryZone::ROM_BEGIN; PC = MemoryZone::CODE_BEGIN; SP = MemoryZone::STACK_END; ::memset(&V[0], 0x00, NUM_REGISTERS); ::srand(::time(NULL)); } /* Draw a pixel on the screen * Returns: * True if a collision occurred */ bool CPU::OpaqueData::putPixel(int x, int y) { int offset = y * screenWidth + x; bool isCollision {false}; if( pScreen[offset] == 1 ) isCollision = true; pScreen[offset] ^= 1; return isCollision; } // Clear the screen memory void CPU::OpaqueData::clearScreen() { ::memset(pScreen, 0x00, MemoryZone::SCREEN_SIZE); } /* Constructor * Args: * pMMU: the pointer to the MMU * pDisplay: the pointer to the Display */ CPU::CPU(MMU *pMMU) : data_(new (std::nothrow) OpaqueData) { if( data_ == nullptr ) { throw CPUError("Unable to allocate CPU data."); } data_->pMMU = pMMU; data_->create(); } // Destructor CPU::~CPU() { data_->destroy(); } // Reset the CPU to it's initial state void CPU::reset() { data_->reset(); data_->clearScreen(); } // Performs a Fetch/Decode/Execute cycle bool CPU::update() { // read the next instruction auto opcode = data_->pMMU->readW(data_->PC); // retrieve values from the opcode auto addr = (opcode & 0x0FFF); auto x = (opcode & 0x0F00) >> 8; auto y = (opcode & 0x00F0) >> 4; auto value = (opcode & 0x00FF); // incrememt PC to next instruction data_->PC += 2; switch(opcode & 0xF000) { case 0x0000: switch(opcode) { case 0x00E0: // CLS data_->clearScreen(); break; case 0x00EE: // RET data_->PC = data_->pMMU->readW(data_->SP); data_->SP += 2; break; } break; case 0x1000: // JP addr data_->PC = addr; break; case 0x2000: // CALL addr data_->SP -= 2; data_->pMMU->writeW(data_->SP, data_->PC); data_->PC = addr; break; case 0x3000: // SE Vx, byte if( data_->V[x] == value) data_->PC += 2; break; case 0x4000: // SNE Vx, byte if( data_->V[x] != value) data_->PC += 2; break; case 0x5000: // SE Vx, Vy if( data_->V[x] == data_->V[y] ) data_->PC += 2; break; case 0x6000: // LD Vx, byte data_->V[x] = value; break; case 0x7000: // ADD Vx, byte data_->V[x] += value; break; case 0x8000: switch(opcode & 0x000F) { case 0x0000: // LD Vx, Vy data_->V[x] = data_->V[y]; break; case 0x0001: // OR Vx, Vy data_->V[x] |= data_->V[y]; break; case 0x0002: // AND Vx, Vy data_->V[x] &= data_->V[y]; break; case 0x0003: // XOR Vx, Vy data_->V[x] ^= data_->V[y]; break; case 0x0004: // ADC Vx, Vy { int sum = data_->V[x] + data_->V[y]; data_->V[Register::VF] = (sum > 0x00FF) ? 1 : 0; data_->V[x] = (sum & 0xFF); } break; case 0x0005: // SBC Vx, Vy data_->V[Register::VF] = (data_->V[x] > data_->V[y]) ? 1 : 0; data_->V[x] -= data_->V[y]; break; case 0x0006: // SHR Vx, 1 data_->V[Register::VF] = (data_->V[x] & 0x01); data_->V[x] >>= 1; break; case 0x0007: // SUBN Vx, Vy data_->V[Register::VF] = (data_->V[y] > data_->V[x]) ? 1 : 0; data_->V[x] = data_->V[y] - data_->V[x]; break; case 0x000E: // SHL Vx, 1 data_->V[Register::VF] = (data_->V[x] & 0x80) ? 1 : 0; data_->V[x] <<= 1; break; } break; case 0x9000: // SNE Vx, Vy if( data_->V[x] != data_->V[y] ) data_->PC += 2; break; case 0xA000: // LD I, addr data_->I = addr; break; case 0xB000: // JP V0, addr data_->PC = addr + data_->V[Register::V0]; break; case 0xC000: // RND Vx, byte data_->V[x] = (::rand() % (0xFF + 1)) & value; break; case 0xD000: // DRW Vx, Vy, n { byte_t height = opcode & 0x000F; data_->V[Register::VF] = 0; for (int row = 0; row < height; row++) { byte_t sprite = data_->pMMU->readB(data_->I + row); for(int col = 0; col < Constants::SPRITE_WIDTH; col++) { // check the upper bit only if( (sprite & 0x80) > 0 ) { // if this is true then a collision occurred if( data_->putPixel(data_->V[x] + col, data_->V[y] + row) ) data_->V[Register::VF] = 1; } // next bit sprite <<= 1; } } } break; case 0xE000: switch(opcode & 0x00FF) { case 0x009E: // SKP Vx { int key = (int)data_->pMMU->readW(MemoryRegister::KEYBOARD_STATUS); int vx = 1 << data_->V[x]; if( (key & vx) == vx ) data_->PC += 2; } break; case 0x00A1: // SKNP Vx { int key = (int)data_->pMMU->readW(MemoryRegister::KEYBOARD_STATUS); int vx = 1 << data_->V[x]; if( (key & vx) != vx ) data_->PC += 2; } break; } break; case 0xF000: switch(opcode & 0x00FF) { case 0x0007: // LD Vx, DT data_->V[x] = data_->pMMU->readB(MemoryRegister::DELAY_TIMER); break; case 0x000A: // LD Vx, K { int key = (data_->pMMU->readW(MemoryRegister::KEYBOARD_STATUS)); if( key == 0 ) data_->PC -= 2; else { int vx = 1; int mask = vx; while( (key & mask) != mask) { vx += 1; mask = 1 << vx; } data_->V[x] = vx; } } break; case 0x0015: // LD DT, Vx data_->pMMU->writeB(MemoryRegister::DELAY_TIMER, data_->V[x]); break; case 0x0018: // LD ST, Vx data_->pMMU->writeB(MemoryRegister::SOUND_TIMER, data_->V[x]); break; case 0x001E: // ADD I, VX data_->V[Register::VF] = ( (data_->I + data_->V[x]) > 0x0FFF ) ? 1 : 0; data_->I += data_->V[x]; break; case 0x0029: // LD F, Vx data_->I = MemoryZone::ROM_BEGIN + (int)(data_->V[x]) * Constants::FONT_SIZE; break; case 0x0033: // LD B, Vx data_->pMMU->writeB(data_->I, (data_->V[x] / 100)); data_->pMMU->writeB(data_->I + 1, (data_->V[x] / 10) % 10); data_->pMMU->writeB(data_->I + 2, (data_->V[x] % 10)); break; case 0x0055: // LD [I], Vx switch(x) { case 0x0F: data_->pMMU->writeB(data_->I + 0x0F, data_->V[0x0F]); case 0x0E: data_->pMMU->writeB(data_->I + 0x0E, data_->V[0x0E]); case 0x0D: data_->pMMU->writeB(data_->I + 0x0D, data_->V[0x0D]); case 0x0C: data_->pMMU->writeB(data_->I + 0x0C, data_->V[0x0C]); case 0x0B: data_->pMMU->writeB(data_->I + 0x0B, data_->V[0x0B]); case 0x0A: data_->pMMU->writeB(data_->I + 0x0A, data_->V[0x0A]); case 0x09: data_->pMMU->writeB(data_->I + 0x09, data_->V[0x09]); case 0x08: data_->pMMU->writeB(data_->I + 0x08, data_->V[0x08]); case 0x07: data_->pMMU->writeB(data_->I + 0x07, data_->V[0x07]); case 0x06: data_->pMMU->writeB(data_->I + 0x06, data_->V[0x06]); case 0x05: data_->pMMU->writeB(data_->I + 0x05, data_->V[0x05]); case 0x04: data_->pMMU->writeB(data_->I + 0x04, data_->V[0x04]); case 0x03: data_->pMMU->writeB(data_->I + 0x03, data_->V[0x03]); case 0x02: data_->pMMU->writeB(data_->I + 0x02, data_->V[0x02]); case 0x01: data_->pMMU->writeB(data_->I + 0x01, data_->V[0x01]); case 0x00: data_->pMMU->writeB(data_->I + 0x00, data_->V[0x00]); } data_->I += x + 1; break; case 0x0065: // LD Vx, [I] switch(x) { case 0x0F: data_->V[0x0F] = data_->pMMU->readB(data_->I + 0x0F); case 0x0E: data_->V[0x0E] = data_->pMMU->readB(data_->I + 0x0E); case 0x0D: data_->V[0x0D] = data_->pMMU->readB(data_->I + 0x0D); case 0x0C: data_->V[0x0C] = data_->pMMU->readB(data_->I + 0x0C); case 0x0B: data_->V[0x0B] = data_->pMMU->readB(data_->I + 0x0B); case 0x0A: data_->V[0x0A] = data_->pMMU->readB(data_->I + 0x0A); case 0x09: data_->V[0x09] = data_->pMMU->readB(data_->I + 0x09); case 0x08: data_->V[0x08] = data_->pMMU->readB(data_->I + 0x08); case 0x07: data_->V[0x07] = data_->pMMU->readB(data_->I + 0x07); case 0x06: data_->V[0x06] = data_->pMMU->readB(data_->I + 0x06); case 0x05: data_->V[0x05] = data_->pMMU->readB(data_->I + 0x05); case 0x04: data_->V[0x04] = data_->pMMU->readB(data_->I + 0x04); case 0x03: data_->V[0x03] = data_->pMMU->readB(data_->I + 0x03); case 0x02: data_->V[0x02] = data_->pMMU->readB(data_->I + 0x02); case 0x01: data_->V[0x01] = data_->pMMU->readB(data_->I + 0x01); case 0x00: data_->V[0x00] = data_->pMMU->readB(data_->I + 0x00); } data_->I += x + 1; break; } break; } return true; }
12,688
4,770
/////////////////////////////////////////////////////////////////////////////// // Dem Bones - Skinning Decomposition Library // // Copyright (c) 2019, Electronic Arts. All rights reserved. // /////////////////////////////////////////////////////////////////////////////// #include "FbxWriter.h" #include "FbxShared.h" #include "LogMsg.h" #include <sstream> #include <Eigen/Dense> #include <DemBones/MatBlocks.h> #include <set> using namespace std; using namespace Eigen; #define err(msgStr) {msg(1, msgStr); return false;} class FbxSceneExporter: public FbxSceneShared { public: FbxSceneExporter(bool embedMedia=true): FbxSceneShared(false) { (*(lSdkManager->GetIOSettings())).SetBoolProp(EXP_FBX_EMBEDDED, embedMedia); } //https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref__export_scene01_2main_8cxx_example_html //https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref__switch_binding_2main_8cxx_example_html bool save(const string& fileName) { // Create an exporter. FbxExporter* lExporter=FbxExporter::Create(lSdkManager, ""); // Get the appropriate file format. int lFileFormat=lSdkManager->GetIOPluginRegistry()->GetNativeWriterFormat(); // Initialize the exporter. if (!lExporter->Initialize(fileName.c_str(), lFileFormat, lSdkManager->GetIOSettings())) err("Call to FbxExporter::Initialize() failed.\n"); // Export the scene to the file. lExporter->Export(lScene); lExporter->Destroy(); return true; } void createJoints(const vector<string>& name, const ArrayXi& parent, double radius) { FbxNode* lRoot=NULL; for (int j=0; j!=name.size(); j++) if (parent(j)==-1) { FbxSkeleton* lSkeletonAttribute=FbxSkeleton::Create(lScene, name[j].c_str()); lSkeletonAttribute->SetSkeletonType(((parent==j).count()>0)?FbxSkeleton::eRoot:FbxSkeleton::eLimb); lSkeletonAttribute->Size.Set(radius); FbxNode* lSkeleton=FbxNode::Create(lScene, name[j].c_str()); lSkeleton->SetNodeAttribute(lSkeletonAttribute); lSkeleton->SetRotationOrder(FbxNode::eSourcePivot, eEulerXYZ); lScene->GetRootNode()->AddChild(lSkeleton); lRoot=lSkeleton; } for (int j=0; j!=name.size(); j++) if (parent(j)!=-1) { FbxSkeleton* lSkeletonAttribute=FbxSkeleton::Create(lScene, name[j].c_str()); lSkeletonAttribute->SetSkeletonType(FbxSkeleton::eLimb); lSkeletonAttribute->Size.Set(radius); FbxNode* lSkeleton=FbxNode::Create(lScene, name[j].c_str()); lSkeleton->SetNodeAttribute(lSkeletonAttribute); lSkeleton->SetRotationOrder(FbxNode::eSourcePivot, eEulerXYZ); lRoot->AddChild(lSkeleton); } } void addToCurve(const VectorXd& val, const VectorXd& fTime, FbxAnimCurve* lCurve) { lCurve->KeyModifyBegin(); int idx=0; int nFr=(int)fTime.size(); FbxTime lTime; for (int k=0; k<nFr; k++) { lTime.SetSecondDouble(fTime(k)); idx=lCurve->KeyAdd(lTime); lCurve->KeySetValue(idx, (float)val(k)); lCurve->KeySetInterpolation(idx, FbxAnimCurveDef::eInterpolationCubic); lCurve->KeySetTangentMode(idx, FbxAnimCurveDef::eTangentAuto); } lCurve->KeyModifyEnd(); } void setJoints(const vector<string>& name, const VectorXd& fTime, const MatrixXd& lr, const MatrixXd& lt, const MatrixXd& lbr, const MatrixXd& lbt) { // Animation stack & layer. FbxString lAnimStackName="demBones"; FbxAnimStack* lAnimStack=FbxAnimStack::Create(lScene, lAnimStackName); FbxAnimLayer* lAnimLayer=FbxAnimLayer::Create(lScene, "Base Layer"); lAnimStack->AddMember(lAnimLayer); VectorXd val; for (int j=0; j!=name.size(); j++) { FbxNode* lSkeleton=lScene->FindNodeByName(FbxString(name[j].c_str())); lSkeleton->LclRotation.Set(FbxDouble3(lbr(0, j), lbr(1, j), lbr(2, j))); lSkeleton->LclTranslation.Set(FbxDouble3(lbt(0, j), lbt(1, j), lbt(2, j))); val=lr.col(j); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data(), val.size()/3), fTime, lSkeleton->LclRotation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X, true)); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data()+1, val.size()/3), fTime, lSkeleton->LclRotation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y, true)); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data()+2, val.size()/3), fTime, lSkeleton->LclRotation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z, true)); val=lt.col(j); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data(), val.size()/3), fTime, lSkeleton->LclTranslation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X, true)); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data()+1, val.size()/3), fTime, lSkeleton->LclTranslation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y, true)); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data()+2, val.size()/3), fTime, lSkeleton->LclTranslation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z, true)); } } void setSkinCluster(const vector<string>& name, const SparseMatrix<double>& w, const MatrixXd& gb) { FbxMesh* lMesh=firstMesh(lScene->GetRootNode()); FbxSkin* lSkin=firstSkin(lMesh); if (lSkin==NULL) { lSkin=FbxSkin::Create(lScene, "demSkinCluster"); lMesh->AddDeformer(lSkin); lSkin->SetSkinningType(FbxSkin::eLinear); } //Clear all clusters while (lSkin->GetClusterCount()) { FbxCluster* lCluster=lSkin->GetCluster(lSkin->GetClusterCount()-1); lSkin->RemoveCluster(lCluster); } //Clear all poses while (lScene->GetPoseCount()) lScene->RemovePose(lScene->GetPoseCount()-1); //Create a new bind pose FbxPose* lPose=FbxPose::Create(lScene, "demBindPose"); lPose->SetIsBindPose(true); FbxAMatrix gMat=lMesh->GetNode()->EvaluateGlobalTransform(); lPose->Add(lMesh->GetNode(), gMat); SparseMatrix<double> wT=w.transpose(); int nB=(int)name.size(); set<FbxNode*> added; for (int j=0; j<nB; j++) { ostringstream s; s<<"demCluster"<<j; FbxCluster* lCluster=FbxCluster::Create(lScene, s.str().c_str()); FbxNode* lNode=lScene->FindNodeByName(FbxString(name[j].c_str())); lCluster->SetLink(lNode); lCluster->SetLinkMode(FbxCluster::eTotalOne); for (SparseMatrix<double>::InnerIterator it(wT, j); it; ++it) lCluster->AddControlPointIndex((int)it.row(), it.value()); lCluster->SetTransformMatrix(gMat); //Equaivalent to jointMat=lJoint->EvaluateGlobalTransform(), but with better accuracy FbxAMatrix jointMat; Map<Matrix4d> mm(&jointMat.mData[0][0], 4, 4); mm=gb.blk4(0, j); lCluster->SetTransformLinkMatrix(jointMat); lSkin->AddCluster(lCluster); //Add to bind pose while ((lNode)&&(added.find(lNode)==added.end())) { added.insert(lNode); lPose->Add(lNode, lNode->EvaluateGlobalTransform()); lNode=lNode->GetParent(); } } lScene->AddPose(lPose); } }; bool writeFBXs(const vector<string>& fileNames, const vector<string>& inputFileNames, DemBonesExt<double, float>& model, bool embedMedia) { msg(1, "Writing outputs:\n"); if ((int)fileNames.size()!=model.nS) err("Wrong number of FBX files.\n"); FbxSceneExporter exporter(embedMedia); bool needCreateJoints=(model.boneName.size()==0); double radius; if (needCreateJoints) { model.boneName.resize(model.nB); for (int j=0; j<model.nB; j++) { ostringstream s; s<<"joint"<<j; model.boneName[j]=s.str(); } radius=sqrt((model.u-(model.u.rowwise().sum()/model.nV).replicate(1, model.nV)).cwiseAbs().rowwise().maxCoeff().squaredNorm()/model.nS); } for (int s=0; s<model.nS; s++) { msg(1, " \""<<inputFileNames[s]<<"\" "); if (!exporter.open(inputFileNames[s])) err("Error on opening file.\n"); msg(1, "--> \""<<fileNames[s]<<"\" "); MatrixXd lr, lt, gb, lbr, lbt; model.computeRTB(s, lr, lt, gb, lbr, lbt); if (needCreateJoints) exporter.createJoints(model.boneName, model.parent, radius); exporter.setJoints(model.boneName, model.fTime.segment(model.fStart(s), model.fStart(s+1)-model.fStart(s)), lr, lt, lbr, lbt); exporter.setSkinCluster(model.boneName, model.w, gb); if (!exporter.save(fileNames[s])) err("Error on exporting file.\n"); msg(1, "("<<model.fStart(s+1)-model.fStart(s)<<" frames)\n"); } return true; }
8,106
3,535
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2015 Wu Lin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <gtest/gtest.h> #include <shogun/lib/config.h> #include <shogun/lib/common.h> #include <shogun/lib/SGVector.h> #include <shogun/lib/SGMatrix.h> #include <shogun/features/DenseFeatures.h> #include <shogun/kernel/GaussianARDKernel.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/mathematics/Math.h> using namespace shogun; TEST(GaussianARDKernel_scalar,get_kernel_matrix) { index_t n=6; index_t dim=2; index_t m=3; float64_t rel_tolerance=1e-10; float64_t abs_tolerance; SGMatrix<float64_t> feat_train(dim, n); SGMatrix<float64_t> lat_feat_train(dim, m); feat_train(0,0)=-0.81263; feat_train(0,1)=-0.99976; feat_train(0,2)=1.17037; feat_train(0,3)=-1.51752; feat_train(0,4)=8.57765; feat_train(0,5)=3.89440; feat_train(1,0)=-0.5; feat_train(1,1)=5.4576; feat_train(1,2)=7.17637; feat_train(1,3)=-2.56752; feat_train(1,4)=4.57765; feat_train(1,5)=2.89440; lat_feat_train(0,0)=1.00000; lat_feat_train(0,1)=23.00000; lat_feat_train(0,2)=4.00000; lat_feat_train(1,0)=3.00000; lat_feat_train(1,1)=2.00000; lat_feat_train(1,2)=-5.00000; auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto latent_features_train=std::make_shared<DenseFeatures<float64_t>>(lat_feat_train); float64_t ell=2.0; auto kernel=std::make_shared<GaussianARDKernel>(10); float64_t weight=0.5; kernel->set_scalar_weights(weight/ell); float64_t ell2=ell/weight; auto kernel2=std::make_shared<GaussianKernel>(10, 2*ell2*ell2); kernel->init(features_train, latent_features_train); kernel2->init(features_train, latent_features_train); SGMatrix<float64_t> mat=kernel->get_kernel_matrix(); SGMatrix<float64_t> mat2=kernel2->get_kernel_matrix(); for(int32_t i=0;i<mat.num_rows;i++) { for(int32_t j=0;j<mat.num_cols;j++) { abs_tolerance=Math::get_abs_tolerance(mat2(i,j),rel_tolerance); EXPECT_NEAR(mat(i,j),mat2(i,j),abs_tolerance); } } kernel->init(features_train, features_train); kernel2->init(features_train, features_train); mat=kernel->get_kernel_matrix(); mat2=kernel2->get_kernel_matrix(); for(int32_t i=0;i<mat.num_rows;i++) { for(int32_t j=0;j<mat.num_cols;j++) { abs_tolerance=Math::get_abs_tolerance(mat2(i,j),rel_tolerance); EXPECT_NEAR(mat(i,j),mat2(i,j),abs_tolerance); } } // cleanup } TEST(GaussianARDKernel_scalar,get_parameter_gradient) { index_t n=6; index_t dim=2; index_t m=3; float64_t rel_tolerance=1e-10; float64_t abs_tolerance; SGMatrix<float64_t> feat_train(dim, n); SGMatrix<float64_t> lat_feat_train(dim, m); feat_train(0,0)=-0.81263; feat_train(0,1)=-0.99976; feat_train(0,2)=1.17037; feat_train(0,3)=-1.51752; feat_train(0,4)=8.57765; feat_train(0,5)=3.89440; feat_train(1,0)=-0.5; feat_train(1,1)=5.4576; feat_train(1,2)=7.17637; feat_train(1,3)=-2.56752; feat_train(1,4)=4.57765; feat_train(1,5)=2.89440; lat_feat_train(0,0)=1.00000; lat_feat_train(0,1)=23.00000; lat_feat_train(0,2)=4.00000; lat_feat_train(1,0)=3.00000; lat_feat_train(1,1)=2.00000; lat_feat_train(1,2)=-5.00000; auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto latent_features_train=std::make_shared<DenseFeatures<float64_t>>(lat_feat_train); float64_t ell=4.0; auto kernel=std::make_shared<GaussianARDKernel>(10); float64_t weight=1.0; kernel->set_scalar_weights(weight/ell); float64_t ell2=ell/weight; auto kernel2=std::make_shared<GaussianKernel>(10, 2*ell2*ell2); kernel->init(features_train, latent_features_train); kernel2->init(features_train, latent_features_train); auto params1 = kernel->get_params(); auto params2 = kernel2->get_params(); auto width_param=params1.find("log_weights"); auto width_param2=params2.find("log_width"); SGMatrix<float64_t> mat=kernel->get_parameter_gradient(*width_param); SGMatrix<float64_t> mat2=kernel2->get_parameter_gradient(*width_param2); for(int32_t i=0;i<mat.num_rows;i++) { for(int32_t j=0;j<mat.num_cols;j++) { abs_tolerance=Math::get_abs_tolerance(-mat2(i,j),rel_tolerance); EXPECT_NEAR(mat(i,j),-mat2(i,j),abs_tolerance); } } kernel->init(features_train, features_train); kernel2->init(features_train, features_train); mat=kernel->get_parameter_gradient(*width_param); mat2=kernel2->get_parameter_gradient(*width_param2); for(int32_t i=0;i<mat.num_rows;i++) { for(int32_t j=0;j<mat.num_cols;j++) { abs_tolerance=Math::get_abs_tolerance(-mat2(i,j),rel_tolerance); EXPECT_NEAR(mat(i,j),-mat2(i,j),abs_tolerance); } } // cleanup } TEST(GaussianARDKernel_vector,get_kernel_matrix) { index_t n=6; index_t dim=2; index_t m=3; float64_t rel_tolerance=1e-10; float64_t abs_tolerance; SGMatrix<float64_t> feat_train(dim, n); SGMatrix<float64_t> lat_feat_train(dim, m); feat_train(0,0)=-0.81263; feat_train(0,1)=-0.99976; feat_train(0,2)=1.17037; feat_train(0,3)=-1.51752; feat_train(0,4)=8.57765; feat_train(0,5)=3.89440; feat_train(1,0)=-0.5; feat_train(1,1)=5.4576; feat_train(1,2)=7.17637; feat_train(1,3)=-2.56752; feat_train(1,4)=4.57765; feat_train(1,5)=2.89440; lat_feat_train(0,0)=1; lat_feat_train(0,1)=23; lat_feat_train(0,2)=4; lat_feat_train(1,0)=3; lat_feat_train(1,1)=2; lat_feat_train(1,2)=-5; auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto latent_features_train=std::make_shared<DenseFeatures<float64_t>>(lat_feat_train); auto kernel=std::make_shared<GaussianARDKernel>(10); float64_t weight1=6.0; float64_t weight2=3.0; SGVector<float64_t> weights(dim); weights[0]=1.0/weight1; weights[1]=1.0/weight2; kernel->set_vector_weights(weights); kernel->init(features_train, latent_features_train); //result from GPML 3.5 //0.483748918128241 0.000268463258484 0.235348892827356 //0.676321622589282 0.000172691024978 0.001624066485753 //0.379307967154712 0.000301388413582 0.000236847574321 //0.163638175047594 0.000074274235677 0.471639781078544 //0.392276838870544 0.038462421551295 0.004574637837373 //0.889607966835858 0.006010671270288 0.031352436711192 SGMatrix<float64_t> mat=kernel->get_kernel_matrix(); abs_tolerance = Math::get_abs_tolerance(0.483748918128241, rel_tolerance); EXPECT_NEAR(mat(0,0), 0.483748918128241, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000268463258484, rel_tolerance); EXPECT_NEAR(mat(0,1), 0.000268463258484, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.235348892827356, rel_tolerance); EXPECT_NEAR(mat(0,2), 0.235348892827356, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.676321622589282, rel_tolerance); EXPECT_NEAR(mat(1,0), 0.676321622589282, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000172691024978, rel_tolerance); EXPECT_NEAR(mat(1,1), 0.000172691024978, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.001624066485753, rel_tolerance); EXPECT_NEAR(mat(1,2), 0.001624066485753, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.379307967154712, rel_tolerance); EXPECT_NEAR(mat(2,0), 0.379307967154712, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000301388413582, rel_tolerance); EXPECT_NEAR(mat(2,1), 0.000301388413582, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000236847574321, rel_tolerance); EXPECT_NEAR(mat(2,2), 0.000236847574321, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.163638175047594, rel_tolerance); EXPECT_NEAR(mat(3,0), 0.163638175047594, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000074274235677, rel_tolerance); EXPECT_NEAR(mat(3,1), 0.000074274235677, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.471639781078544, rel_tolerance); EXPECT_NEAR(mat(3,2), 0.471639781078544, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.392276838870544, rel_tolerance); EXPECT_NEAR(mat(4,0), 0.392276838870544, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.038462421551295, rel_tolerance); EXPECT_NEAR(mat(4,1), 0.038462421551295, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.004574637837373, rel_tolerance); EXPECT_NEAR(mat(4,2), 0.004574637837373, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.889607966835858, rel_tolerance); EXPECT_NEAR(mat(5,0), 0.889607966835858, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.006010671270288, rel_tolerance); EXPECT_NEAR(mat(5,1), 0.006010671270288, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.031352436711192, rel_tolerance); EXPECT_NEAR(mat(5,2), 0.031352436711192, abs_tolerance); kernel->init(latent_features_train, latent_features_train); //result from GPML 3.5 //1.000000000000000 0.001138802761346 0.025208965963144 //0.001138802761346 1.000000000000000 0.000436766814255 //0.025208965963144 0.000436766814255 1.000000000000000 mat=kernel->get_kernel_matrix(); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(0,0), 1.000000000000000, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.001138802761346, rel_tolerance); EXPECT_NEAR(mat(0,1), 0.001138802761346, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.025208965963144, rel_tolerance); EXPECT_NEAR(mat(0,2), 0.025208965963144, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.001138802761346, rel_tolerance); EXPECT_NEAR(mat(1,0), 0.001138802761346, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(1,1), 1.000000000000000, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000436766814255, rel_tolerance); EXPECT_NEAR(mat(1,2), 0.000436766814255, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.025208965963144, rel_tolerance); EXPECT_NEAR(mat(2,0), 0.025208965963144, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000436766814255, rel_tolerance); EXPECT_NEAR(mat(2,1), 0.000436766814255, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(2,2), 1.000000000000000, abs_tolerance); // cleanup } TEST(GaussianARDKernel_matrix,get_kernel_matrix1) { index_t dim=2; index_t m=3; float64_t rel_tolerance=1e-10; float64_t abs_tolerance; SGMatrix<float64_t> lat_feat_train(dim, m); SGMatrix<float64_t> lat_feat_train2(dim, m); lat_feat_train(0,0)=1; lat_feat_train(0,1)=23; lat_feat_train(0,2)=4; lat_feat_train(1,0)=3; lat_feat_train(1,1)=2; lat_feat_train(1,2)=-5; lat_feat_train2(0,0)=1; lat_feat_train2(0,1)=23; lat_feat_train2(0,2)=4; lat_feat_train2(1,0)=3; lat_feat_train2(1,1)=2; lat_feat_train2(1,2)=-5; auto latent_features_train=std::make_shared<DenseFeatures<float64_t>>(lat_feat_train); auto latent_features_train2=std::make_shared<DenseFeatures<float64_t>>(lat_feat_train2); auto kernel=std::make_shared<GaussianARDKernel>(10); int32_t t_dim=2; SGMatrix<float64_t> weights(t_dim,dim); //the weights is a lower triangular matrix float64_t weight1=0.02; float64_t weight2=-0.4; float64_t weight3=0; float64_t weight4=0.01; weights(0,0)=weight1; weights(1,0)=weight2; weights(0,1)=weight3; weights(1,1)=weight4; kernel->set_matrix_weights(weights); kernel->init(latent_features_train, latent_features_train2); //result from GPML 3.5 //1.000000000000000 0.702682587860637 0.004907454025841 //0.702682587860637 1.000000000000000 0.053362341348083 //0.004907454025841 0.053362341348083 1.000000000000000 SGMatrix<float64_t> mat=kernel->get_kernel_matrix(); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(0,0), 1.000000000000000, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.702682587860637, rel_tolerance); EXPECT_NEAR(mat(0,1), 0.702682587860637, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.004907454025841, rel_tolerance); EXPECT_NEAR(mat(0,2), 0.004907454025841, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.702682587860637, rel_tolerance); EXPECT_NEAR(mat(1,0), 0.702682587860637, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(1,1), 1.000000000000000, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.053362341348083, rel_tolerance); EXPECT_NEAR(mat(1,2), 0.053362341348083, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.004907454025841, rel_tolerance); EXPECT_NEAR(mat(2,0), 0.004907454025841, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.053362341348083, rel_tolerance); EXPECT_NEAR(mat(2,1), 0.053362341348083, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(2,2), 1.000000000000000, abs_tolerance); // cleanup } TEST(GaussianARDKernel_matrix,get_kernel_matrix2) { index_t n=6; index_t dim=2; index_t m=3; float64_t rel_tolerance=1e-10; float64_t abs_tolerance; SGMatrix<float64_t> feat_train(dim, n); SGMatrix<float64_t> lat_feat_train(dim, m); feat_train(0,0)=-0.81263; feat_train(0,1)=-0.99976; feat_train(0,2)=1.17037; feat_train(0,3)=-1.51752; feat_train(0,4)=8.57765; feat_train(0,5)=3.89440; feat_train(1,0)=-0.5; feat_train(1,1)=5.4576; feat_train(1,2)=7.17637; feat_train(1,3)=-2.56752; feat_train(1,4)=4.57765; feat_train(1,5)=2.89440; lat_feat_train(0,0)=1; lat_feat_train(0,1)=23; lat_feat_train(0,2)=4; lat_feat_train(1,0)=3; lat_feat_train(1,1)=2; lat_feat_train(1,2)=-5; auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto latent_features_train=std::make_shared<DenseFeatures<float64_t>>(lat_feat_train); auto kernel=std::make_shared<GaussianARDKernel>(10); int32_t t_dim=2; SGMatrix<float64_t> weights(t_dim,dim); //the weights is a lower triangular matrix float64_t weight1=0.02; float64_t weight2=-0.4; float64_t weight3=0; float64_t weight4=0.01; weights(0,0)=weight1; weights(1,0)=weight2; weights(0,1)=weight3; weights(1,1)=weight4; kernel->set_matrix_weights(weights); kernel->init(features_train, latent_features_train); //result from GPML 3.5 //0.394350178890907 0.871562091809855 0.165480906152021 //0.592382640849672 0.176215460003241 0.000103321679752 //0.248938103583867 0.043100670101141 0.000005310787411 //0.093436892436847 0.408865150874797 0.555930926275610 //0.891287769081377 0.418582374577455 0.000915039915173 //0.994999180183564 0.760525767334597 0.006768257533514 SGMatrix<float64_t> mat=kernel->get_kernel_matrix(); abs_tolerance = Math::get_abs_tolerance(0.394350178890907, rel_tolerance); EXPECT_NEAR(mat(0,0), 0.394350178890907, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.871562091809855, rel_tolerance); EXPECT_NEAR(mat(0,1), 0.871562091809855, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.165480906152021, rel_tolerance); EXPECT_NEAR(mat(0,2), 0.165480906152021, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.592382640849672, rel_tolerance); EXPECT_NEAR(mat(1,0), 0.592382640849672, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.176215460003241, rel_tolerance); EXPECT_NEAR(mat(1,1), 0.176215460003241, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000103321679752, rel_tolerance); EXPECT_NEAR(mat(1,2), 0.000103321679752, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.248938103583867, rel_tolerance); EXPECT_NEAR(mat(2,0), 0.248938103583867, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.043100670101141, rel_tolerance); EXPECT_NEAR(mat(2,1), 0.043100670101141, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000005310787411, rel_tolerance); EXPECT_NEAR(mat(2,2), 0.000005310787411, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.093436892436847, rel_tolerance); EXPECT_NEAR(mat(3,0), 0.093436892436847, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.408865150874797, rel_tolerance); EXPECT_NEAR(mat(3,1), 0.408865150874797, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.555930926275610, rel_tolerance); EXPECT_NEAR(mat(3,2), 0.555930926275610, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.891287769081377, rel_tolerance); EXPECT_NEAR(mat(4,0), 0.891287769081377, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.418582374577455, rel_tolerance); EXPECT_NEAR(mat(4,1), 0.418582374577455, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.000915039915173, rel_tolerance); EXPECT_NEAR(mat(4,2), 0.000915039915173, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.994999180183564, rel_tolerance); EXPECT_NEAR(mat(5,0), 0.994999180183564, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.760525767334597, rel_tolerance); EXPECT_NEAR(mat(5,1), 0.760525767334597, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.006768257533514, rel_tolerance); EXPECT_NEAR(mat(5,2), 0.006768257533514, abs_tolerance); kernel->init(latent_features_train, latent_features_train); //result from GPML 3.5 //1.000000000000000 0.702682587860637 0.004907454025841 //0.702682587860637 1.000000000000000 0.053362341348083 //0.004907454025841 0.053362341348083 1.000000000000000 mat=kernel->get_kernel_matrix(); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(0,0), 1.000000000000000, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.702682587860637, rel_tolerance); EXPECT_NEAR(mat(0,1), 0.702682587860637, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.004907454025841, rel_tolerance); EXPECT_NEAR(mat(0,2), 0.004907454025841, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.702682587860637, rel_tolerance); EXPECT_NEAR(mat(1,0), 0.702682587860637, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(1,1), 1.000000000000000, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.053362341348083, rel_tolerance); EXPECT_NEAR(mat(1,2), 0.053362341348083, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.004907454025841, rel_tolerance); EXPECT_NEAR(mat(2,0), 0.004907454025841, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(0.053362341348083, rel_tolerance); EXPECT_NEAR(mat(2,1), 0.053362341348083, abs_tolerance); abs_tolerance = Math::get_abs_tolerance(1.000000000000000, rel_tolerance); EXPECT_NEAR(mat(2,2), 1.000000000000000, abs_tolerance); // cleanup } TEST(GaussianARDKernel,get_kernel_diagonal) { index_t n=6; index_t dim=2; index_t m=3; float64_t rel_tolerance=1e-10; float64_t abs_tolerance; SGMatrix<float64_t> feat_train(dim, n); SGMatrix<float64_t> lat_feat_train(dim, m); feat_train(0,0)=-0.81263; feat_train(0,1)=-0.99976; feat_train(0,2)=1.17037; feat_train(0,3)=-1.51752; feat_train(0,4)=8.57765; feat_train(0,5)=3.89440; feat_train(1,0)=-0.5; feat_train(1,1)=5.4576; feat_train(1,2)=7.17637; feat_train(1,3)=-2.56752; feat_train(1,4)=4.57765; feat_train(1,5)=2.89440; lat_feat_train(0,0)=1.00000; lat_feat_train(0,1)=23.00000; lat_feat_train(0,2)=4.00000; lat_feat_train(1,0)=3.00000; lat_feat_train(1,1)=2.00000; lat_feat_train(1,2)=-5.00000; auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto latent_features_train=std::make_shared<DenseFeatures<float64_t>>(lat_feat_train); auto kernel=std::make_shared<GaussianARDKernel>(10); int32_t t_dim=2; SGMatrix<float64_t> weights(t_dim,dim); //the weights is a upper triangular matrix since GPML 3.5 only supports this type float64_t weight1=0.02; float64_t weight2=-0.4; float64_t weight3=0; float64_t weight4=0.01; weights(0,0)=weight1; weights(0,1)=weight2; weights(1,0)=weight3; weights(1,1)=weight4; kernel->set_matrix_weights(weights); kernel->init(features_train, latent_features_train); SGVector<float64_t> vec=kernel->get_kernel_diagonal(); SGMatrix<float64_t> mat2=kernel->get_kernel_matrix(); SGVector<float64_t> vec2=mat2.get_diagonal_vector(); for(int32_t i=0;i<vec.vlen;i++) { abs_tolerance=Math::get_abs_tolerance(vec2[i],rel_tolerance); EXPECT_NEAR(vec[i],vec2[i],abs_tolerance); } kernel->init(features_train, features_train); vec=kernel->get_kernel_diagonal(); mat2=kernel->get_kernel_matrix(); vec2=mat2.get_diagonal_vector(); for(int32_t i=0;i<vec.vlen;i++) { abs_tolerance=Math::get_abs_tolerance(vec2[i],rel_tolerance); EXPECT_NEAR(vec[i],vec2[i],abs_tolerance); } // cleanup } TEST(GaussianARDKernel,get_parameter_gradient_diagonal) { index_t n=6; index_t dim=2; index_t m=3; float64_t rel_tolerance=1e-10; float64_t abs_tolerance; SGMatrix<float64_t> feat_train(dim, n); SGMatrix<float64_t> lat_feat_train(dim, m); feat_train(0,0)=-0.81263; feat_train(0,1)=-0.99976; feat_train(0,2)=1.17037; feat_train(0,3)=-1.51752; feat_train(0,4)=8.57765; feat_train(0,5)=3.89440; feat_train(1,0)=-0.5; feat_train(1,1)=5.4576; feat_train(1,2)=7.17637; feat_train(1,3)=-2.56752; feat_train(1,4)=4.57765; feat_train(1,5)=2.89440; lat_feat_train(0,0)=1.00000; lat_feat_train(0,1)=23.00000; lat_feat_train(0,2)=4.00000; lat_feat_train(1,0)=3.00000; lat_feat_train(1,1)=2.00000; lat_feat_train(1,2)=-5.00000; auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto latent_features_train=std::make_shared<DenseFeatures<float64_t>>(lat_feat_train); float64_t ell=4.0; auto kernel=std::make_shared<GaussianARDKernel>(10); float64_t weight=1.0; kernel->set_scalar_weights(weight/ell); float64_t ell2=ell/weight; auto kernel2=std::make_shared<GaussianKernel>(10, 2*ell2*ell2); kernel->init(features_train, latent_features_train); kernel2->init(features_train, latent_features_train); auto params1 = kernel->get_params(); auto params2 = kernel2->get_params(); auto width_param=params1.find("log_weights"); auto width_param2=params2.find("log_width"); SGVector<float64_t> vec=kernel->get_parameter_gradient_diagonal(*width_param); SGVector<float64_t> vec2=kernel2->get_parameter_gradient_diagonal(*width_param2); for(int32_t j=0;j<vec.vlen;j++) { abs_tolerance=Math::get_abs_tolerance(-vec2[j],rel_tolerance); EXPECT_NEAR(vec[j],-vec2[j],abs_tolerance); } kernel->init(features_train, features_train); kernel2->init(features_train, features_train); vec=kernel->get_parameter_gradient_diagonal(*width_param); vec2=kernel2->get_parameter_gradient_diagonal(*width_param2); for(int32_t j=0;j<vec.vlen;j++) { abs_tolerance=Math::get_abs_tolerance(-vec2[j],rel_tolerance); EXPECT_NEAR(vec[j],-vec2[j],abs_tolerance); } // cleanup }
24,345
13,627
// Copyright 2004-2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== #include "omaha/base/thread_pool.h" #include <memory> #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/utils.h" namespace omaha { namespace { // Context keeps track the information necessary to execute a work item // inside a thread pool thread. class Context { public: Context(ThreadPool* pool, UserWorkItem* work_item, DWORD coinit_flags) : pool_(pool), work_item_(work_item), coinit_flags_(coinit_flags) { ASSERT1(pool); ASSERT1(work_item); } ThreadPool* pool() const { return pool_; } UserWorkItem* work_item() const { return work_item_; } DWORD coinit_flags() const { return coinit_flags_; } private: ThreadPool* pool_; UserWorkItem* work_item_; const DWORD coinit_flags_; DISALLOW_COPY_AND_ASSIGN(Context); }; } // namespace DWORD WINAPI ThreadPool::ThreadProc(void* param) { UTIL_LOG(L4, (_T("[ThreadPool::ThreadProc]"))); ASSERT1(param); Context* context = static_cast<Context*>(param); scoped_co_init init_com_apt(context->coinit_flags()); ASSERT1(SUCCEEDED(init_com_apt.hresult())); context->pool()->ProcessWorkItem(context->work_item()); delete context; return 0; } ThreadPool::ThreadPool() : work_item_count_(0), shutdown_delay_(0) { UTIL_LOG(L2, (_T("[ThreadPool::ThreadPool]"))); } ThreadPool::~ThreadPool() { UTIL_LOG(L2, (_T("[ThreadPool::~ThreadPool]"))); if (!shutdown_event_) { return; } DWORD baseline_tick_count = ::GetTickCount(); if (::SetEvent(get(shutdown_event_))) { while (work_item_count_ != 0) { ::Sleep(1); if (TimeHasElapsed(baseline_tick_count, shutdown_delay_)) { UTIL_LOG(LE, (_T("[ThreadPool::~ThreadPool][timeout elapsed]"))); // Exiting a thread pool that has active work items can result in a // race condition and undefined behavior during shutdown. ::RaiseException(EXCEPTION_ACCESS_VIOLATION, EXCEPTION_NONCONTINUABLE, 0, NULL); break; } } } } HRESULT ThreadPool::Initialize(int shutdown_delay) { shutdown_delay_ = shutdown_delay; reset(shutdown_event_, ::CreateEvent(NULL, true, false, NULL)); return shutdown_event_ ? S_OK : HRESULTFromLastError(); } void ThreadPool::ProcessWorkItem(UserWorkItem* work_item) { ASSERT1(work_item); work_item->Process(); delete work_item; ::InterlockedDecrement(&work_item_count_); } HRESULT ThreadPool::QueueUserWorkItem(UserWorkItem* work_item, DWORD coinit_flags, uint32 flags) { UTIL_LOG(L4, (_T("[ThreadPool::QueueUserWorkItem]"))); ASSERT1(work_item); auto context = std::make_unique<Context>(this, work_item, coinit_flags); work_item->set_shutdown_event(get(shutdown_event_)); ::InterlockedIncrement(&work_item_count_); if (!::QueueUserWorkItem(&ThreadPool::ThreadProc, context.get(), flags)) { ::InterlockedDecrement(&work_item_count_); return HRESULTFromLastError(); } // The thread pool has the ownership of the work item thereon. context.release(); return S_OK; } } // namespace omaha
3,895
1,290
#include <iostream> #include <unordered_map> #include <stdio.h> int main() { int letters_count, code_length; std::cin >> letters_count >> code_length; std::unordered_map<std::string,char> letters_map; std::string character; std::string code; for (int i = 0; i < letters_count; i++){ std::cin >> character >> code; letters_map[code] = character[0]; } std::string codedString; std::cin >> codedString; int i = 0; std::string current = ""; std::string decodedString = ""; while (i < codedString.length()){ current += codedString[i]; auto found = letters_map.find(current); if (found != letters_map.end()){ decodedString += found->second; current = ""; } i++; } std::cout << decodedString; return 0; }
843
269
//===-- Qt Widgets ----------------------------------------------*- C++ -*-===// //! //! \version 2021-10-18 //! \since 2021-09-15 //! \authors zhengrr //! \copyright Unlicense //! //===----------------------------------------------------------------------===// #include <QtWidgets/QApplication> #include "MainWindow.h" int main(int argc, char *argv[]) { QApplication app {argc, argv}; MainWindow wnd; wnd.show(); return app.exec(); }
456
163
#include <stdio.h> #include <stdlib.h> #include <fstream> #include <iostream> using namespace std; int main() { ofstream arquivo; arquivo.open("Fabiano.txt", std::ios_base::app); arquivo << "Olá, mundo!\n\nAqui quem fala é o fabiano."; arquivo.close(); return 0; }
278
113
#ifndef LATTE_CORE_HOOK_H #define LATTE_CORE_HOOK_H #include "latte_core_state.hpp" #include "latte_type.hpp" #include <iostream> #include <string> #include <unordered_map> #include <vector> namespace latte { namespace core { // Base class for before(), after(), before_each(), and after_each() struct latte_test_hook { latte_test_hook(): latte_test_hook("latte_test_hook") {} latte_test_hook(const std::string& name) { name_ = name; } protected: virtual void operator()(const std::string& description, const type::latte_callback& hook) { description_ = description; this->operator()(hook); } virtual void operator()(const type::latte_callback& hook) { // Find the hook's call stack associated with the current describe() auto current_call_stack = call_stack.find(parent_depth()); // We found the stack if (current_call_stack != call_stack.end()) { auto stack = current_call_stack->second; // Add the hook to the local stack stack.push_back(hook); // Update the local stack call_stack[parent_depth()] = stack; } else { // Create the local stack std::vector<type::latte_callback> stack { hook }; // Add the local stack call_stack[parent_depth()] = stack; } }; virtual void operator() (int depth) { auto current_call_stack = call_stack.find(depth); if (current_call_stack != call_stack.end()) { std::vector<type::latte_callback> stack = current_call_stack->second; try { if (!stack.empty()) { // The function call is located at the end. auto function = stack.back(); function(); } } catch(const std::exception& e) { // debug("[latte error::core::hook]: " + std::string(e.what())); } } else { // debug("---: couldn't find hook: " + name_); } } void clear(int depth) { auto current_call_stack = call_stack.find(depth); if (current_call_stack != call_stack.end()) { // Remove the function from the call stack if (!current_call_stack->second.empty()) { current_call_stack->second.pop_back(); } } } std::string name_ = ""; std::string description_ = ""; private: std::unordered_map<int, std::vector<type::latte_callback>> call_stack; int parent_depth () { return _latte_state.depth(); } }; struct latte_before : public latte_test_hook { latte_before(): latte_test_hook("before()") {}; virtual void operator()(const std::string& description, type::latte_callback&& hook) { latte_test_hook::operator()(description, hook); } virtual void operator()(type::latte_callback&& hook) { latte_test_hook::operator()(hook); }; private: friend struct latte_describe; friend struct latte_it; virtual void operator() (int depth) { latte_test_hook::operator()(depth); } }; struct latte_before_each : public latte_test_hook { latte_before_each(): latte_test_hook("before_each()") {}; virtual void operator()(const std::string& description, type::latte_callback&& hook) { latte_test_hook::operator()(description, hook); } virtual void operator()(type::latte_callback&& hook) { latte_test_hook::operator()(hook); }; private: friend struct latte_describe; friend struct latte_it; virtual void operator() (int depth) { latte_test_hook::operator()(depth); } }; struct latte_after : public latte_test_hook { latte_after(): latte_test_hook("after()") {}; virtual void operator()(const std::string& description, type::latte_callback&& hook) { latte_test_hook::operator()(description, hook); } virtual void operator()(type::latte_callback&& hook) { latte_test_hook::operator()(hook); }; private: friend struct latte_describe; friend struct latte_it; virtual void operator() (int depth) { latte_test_hook::operator()(depth); } }; struct latte_after_each: public latte_test_hook { latte_after_each(): latte_test_hook("after_each()") {}; virtual void operator()(const std::string& description, type::latte_callback&& hook) { latte_test_hook::operator()(description, hook); } virtual void operator()(type::latte_callback&& hook) { latte_test_hook::operator()(hook); }; private: friend struct latte_describe; friend struct latte_it; virtual void operator() (int depth) { latte_test_hook::operator()(depth); } }; } // core } // latte #endif
4,456
1,467
//////////////////////////////////////////////////////////////// // Header #include "Gugu/Common.h" #include "Gugu/Editor/Modal/OpenProjectDialog.h" //////////////////////////////////////////////////////////////// // Includes #include "Gugu/Editor/Editor.h" #include <imgui.h> #include <imgui_stdlib.h> //////////////////////////////////////////////////////////////// // File Implementation namespace gugu { OpenProjectDialog::OpenProjectDialog(const std::string& projectPath) : BaseModalDialog("Open Project") , m_projectPath(projectPath) { } OpenProjectDialog::~OpenProjectDialog() { } void OpenProjectDialog::UpdateModalImpl(const DeltaTime& dt) { if (ImGui::InputText("Project Path File", &m_projectPath, ImGuiInputTextFlags_EnterReturnsTrue)) { } ImGui::Spacing(); if (ImGui::Button("Cancel")) { CloseModalImpl(); } ImGui::SameLine(); if (ImGui::Button("Validate")) { GetEditor()->OpenProject(m_projectPath); CloseModalImpl(); } } } //namespace gugu
1,097
338
#include <bits/stdc++.h> #define fi first #define se second #define LIMIT 1000000007 #define dbg(x) cout << "variable '" << #x << << "' -> " << x << '\n'; #define oi() cout << "oi" << endl; #define fr(a, b, c) for(int a = b, _ = c; a < _; ++a) typedef unsigned long long ull; using namespace std; map<int, bool> visited; map<int, vector<int> > adj; void ie(int x, int y){ adj[x].push_back(y); adj[y].push_back(x); } void dfs(int v){ visited[v] = true; vector<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i){ if(!visited[*i]){ dfs(*i); } } } int compconex(){ int k = 0; map<int, bool>::iterator i; for(i = visited.begin(); i != visited.end(); ++i){ if(!i->second){ dfs(i->first); k++; } } return k; } int main() { ios::sync_with_stdio(0); cin.tie(NULL); int n, m; cin >> n >> m; set<int> p; //retorna ptr inserido + bool pair<set<int>::iterator, bool> c; //verif set insert fr(i, 0, m){ int x, y; cin >> x >> y; //x--; y--; ie(x, y); c = p.insert(x); if(c.second) visited[x] = false; c = p.insert(y); if(c.second) visited[y] = false; } cout << compconex() + n - p.size() << endl; cerr << endl << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << "s.\n"; return 0; }
1,278
614
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * 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 <modules/space/rendering/renderablestars.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/util/updatestructures.h> #include <openspace/util/distanceconstants.h> #include <openspace/engine/openspaceengine.h> #include <openspace/engine/globals.h> #include <openspace/rendering/renderengine.h> #include <ghoul/filesystem/cachemanager.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ghoul/misc/templatefactory.h> #include <ghoul/io/texture/texturereader.h> #include <ghoul/opengl/openglstatecache.h> #include <ghoul/opengl/programobject.h> #include <ghoul/opengl/texture.h> #include <ghoul/opengl/textureunit.h> #include <array> #include <cstdint> #include <filesystem> #include <fstream> #include <iostream> #include <limits> #include <type_traits> namespace { constexpr const char* _loggerCat = "RenderableStars"; constexpr const char* KeyFile = "File"; constexpr const char* KeyStaticFilterValue = "StaticFilter"; constexpr const char* KeyStaticFilterReplacement = "StaticFilterReplacement"; constexpr const std::array<const char*, 17> UniformNames = { "modelMatrix", "cameraUp", "cameraViewProjectionMatrix", "colorOption", "magnitudeExponent", "eyePosition", "psfParamConf", "lumCent", "radiusCent", "brightnessCent", "colorTexture", "alphaValue", "psfTexture", "otherDataTexture", "otherDataRange", "filterOutOfRange", "fixedColor" }; constexpr int8_t CurrentCacheVersion = 3; constexpr const int RenderOptionPointSpreadFunction = 0; constexpr const int RenderOptionTexture = 1; constexpr const int PsfMethodSpencer = 0; constexpr const int PsfMethodMoffat = 1; constexpr double PARSEC = 0.308567756E17; struct ColorVBOLayout { std::array<float, 3> position; float value; float luminance; float absoluteMagnitude; float apparentMagnitude; }; struct VelocityVBOLayout { std::array<float, 3> position; float value; float luminance; float absoluteMagnitude; float apparentMagnitude; float vx; // v_x float vy; // v_y float vz; // v_z }; struct SpeedVBOLayout { std::array<float, 3> position; float value; float luminance; float absoluteMagnitude; float apparentMagnitude; float speed; }; struct OtherDataLayout { std::array<float, 3> position; float value; float luminance; float absoluteMagnitude; float apparentMagnitude; }; constexpr openspace::properties::Property::PropertyInfo SpeckFileInfo = { "SpeckFile", "Speck File", "The speck file that is loaded to get the data for rendering these stars." }; static const openspace::properties::Property::PropertyInfo ColorTextureInfo = { "ColorMap", "ColorBV Texture", "The path to the texture that is used to convert from the B-V value of the star " "to its color. The texture is used as a one dimensional lookup function." }; constexpr openspace::properties::Property::PropertyInfo ColorOptionInfo = { "ColorOption", "Color Option", "This value determines which quantity is used for determining the color of the " "stars." }; constexpr openspace::properties::Property::PropertyInfo OtherDataOptionInfo = { "OtherData", "Other Data Column", "The index of the speck file data column that is used as the color input" }; constexpr openspace::properties::Property::PropertyInfo OtherDataValueRangeInfo = { "OtherDataValueRange", "Range of the other data values", "This value is the min/max value range that is used to normalize the other data " "values so they can be used by the specified color map." }; constexpr openspace::properties::Property::PropertyInfo FixedColorInfo = { "FixedColorValue", "Color used for fixed star colors", "The color that should be used if the 'Fixed Color' value is used." }; constexpr openspace::properties::Property::PropertyInfo OtherDataColorMapInfo = { "OtherDataColorMap", "Other Data Color Map", "The color map that is used if the 'Other Data' rendering method is selected" }; constexpr openspace::properties::Property::PropertyInfo FilterOutOfRangeInfo = { "FilterOutOfRange", "Filter Out of Range", "Determines whether other data values outside the value range should be visible " "or filtered away" }; constexpr openspace::properties::Property::PropertyInfo EnableTestGridInfo = { "EnableTestGrid", "Enable Test Grid", "Set it to true for rendering the test grid." }; // Old Method constexpr openspace::properties::Property::PropertyInfo PsfTextureInfo = { "Texture", "Point Spread Function Texture", "The path to the texture that should be used as a point spread function for the " "stars." }; /*constexpr openspace::properties::Property::PropertyInfo ShapeTextureInfo = { "ShapeTexture", "Shape Texture to be convolved", "The path to the texture that should be used as the base shape for the stars." };*/ // PSF constexpr openspace::properties::Property::PropertyInfo MagnitudeExponentInfo = { "MagnitudeExponent", "Magnitude Exponent", "Adjust star magnitude by 10^MagnitudeExponent. " "Stars closer than this distance are given full opacity. " "Farther away, stars dim proportionally to the logarithm of their distance." }; constexpr openspace::properties::Property::PropertyInfo RenderMethodOptionInfo = { "RenderMethod", "Render Method", "Render method for the stars." }; openspace::properties::PropertyOwner::PropertyOwnerInfo UserProvidedTextureOptionInfo = { "UserProvidedTexture", "User Provided Texture", "" }; openspace::properties::PropertyOwner::PropertyOwnerInfo ParametersOwnerOptionInfo = { "ParametersOwner", "Parameters Options", "" }; openspace::properties::PropertyOwner::PropertyOwnerInfo MoffatMethodOptionInfo = { "MoffatMethodOption", "Moffat Method", "" }; constexpr openspace::properties::Property::PropertyInfo PSFMethodOptionInfo = { "PSFMethodOptionInfo", "PSF Method Option", "Debug option for PSF main function: Spencer or Moffat." }; constexpr openspace::properties::Property::PropertyInfo SizeCompositionOptionInfo = { "SizeComposition", "Size Composition Option", "Base multiplyer for the final stars' sizes." }; constexpr openspace::properties::Property::PropertyInfo LumPercentInfo = { "LumPercent", "Luminosity Contribution", "Luminosity Contribution." }; constexpr openspace::properties::Property::PropertyInfo RadiusPercentInfo = { "RadiusPercent", "Radius Contribution", "Radius Contribution." }; constexpr openspace::properties::Property::PropertyInfo BrightnessPercentInfo = { "BrightnessPercen", "App Brightness Contribution", "App Brightness Contribution." }; openspace::properties::PropertyOwner::PropertyOwnerInfo SpencerPSFParamOwnerInfo = { "SpencerPSFParamOwner", "Spencer PSF Paramameters", "PSF parameters for Spencer" }; constexpr openspace::properties::Property::PropertyInfo P0ParamInfo = { "P0Param", "P0", "P0 parameter contribution." }; constexpr openspace::properties::Property::PropertyInfo P1ParamInfo = { "P1Param", "P1", "P1 parameter contribution." }; constexpr openspace::properties::Property::PropertyInfo P2ParamInfo = { "P2Param", "P2", "P2 parameter contribution." }; constexpr openspace::properties::Property::PropertyInfo AlphaConstInfo = { "AlphaConst", "Alpha", "Empirical Alpha Constant." }; openspace::properties::PropertyOwner::PropertyOwnerInfo MoffatPSFParamOwnerInfo = { "MoffatPSFParam", "Moffat PSF Parameters", "PSF parameters for Moffat" }; constexpr openspace::properties::Property::PropertyInfo FWHMInfo = { "FWHM", "FWHM", "Moffat's FWHM" }; constexpr openspace::properties::Property::PropertyInfo BetaInfo = { "Beta", "Beta", "Moffat's Beta Constant." }; constexpr openspace::properties::Property::PropertyInfo FadeInDistancesInfo = { "FadeInDistances", "Fade-In Start and End Distances", "These values determine the initial and final distances from the center of " "our galaxy from which the astronomical object will start and end " "fading-in." }; constexpr openspace::properties::Property::PropertyInfo DisableFadeInInfo = { "DisableFadeIn", "Disable Fade-in effect", "Enables/Disables the Fade-in effect." }; } // namespace namespace openspace { documentation::Documentation RenderableStars::Documentation() { using namespace documentation; return { "RenderableStars", "space_renderablestars", { { "Type", new StringEqualVerifier("RenderableStars"), Optional::No }, { KeyFile, new StringVerifier, Optional::No, "The path to the SPECK file that contains information about the stars " "being rendered." }, { ColorTextureInfo.identifier, new StringVerifier, Optional::No, ColorTextureInfo.description }, /*{ ShapeTextureInfo.identifier, new StringVerifier, Optional::No, ShapeTextureInfo.description },*/ { ColorOptionInfo.identifier, new StringInListVerifier({ "Color", "Velocity", "Speed", "Other Data", "Fixed Color" }), Optional::Yes, ColorOptionInfo.description }, { OtherDataOptionInfo.identifier, new StringVerifier, Optional::Yes, OtherDataOptionInfo.description }, { OtherDataColorMapInfo.identifier, new StringVerifier, Optional::Yes, OtherDataColorMapInfo.description }, { FilterOutOfRangeInfo.identifier, new BoolVerifier, Optional::Yes, FilterOutOfRangeInfo.description }, { KeyStaticFilterValue, new DoubleVerifier, Optional::Yes, "This value specifies a value that is always filtered out of the value " "ranges on loading. This can be used to trim the dataset's automatic " "value range." }, { KeyStaticFilterReplacement, new DoubleVerifier, Optional::Yes, "This is the value that is used to replace statically filtered values. " "Setting this value only makes sense if 'StaticFilter' is 'true', as " "well." }, { MagnitudeExponentInfo.identifier, new DoubleVerifier, Optional::Yes, MagnitudeExponentInfo.description }, { EnableTestGridInfo.identifier, new BoolVerifier, Optional::Yes, EnableTestGridInfo.description }, { RenderMethodOptionInfo.identifier, new StringVerifier, Optional::No, RenderMethodOptionInfo.description }, { SizeCompositionOptionInfo.identifier, new StringVerifier, Optional::No, SizeCompositionOptionInfo.description }, { FadeInDistancesInfo.identifier, new Vector2Verifier<double>, Optional::Yes, FadeInDistancesInfo.description }, { DisableFadeInInfo.identifier, new BoolVerifier, Optional::Yes, DisableFadeInInfo.description }, } }; } RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _speckFile(SpeckFileInfo) , _colorTexturePath(ColorTextureInfo) //, _shapeTexturePath(ShapeTextureInfo) , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) , _otherDataOption( OtherDataOptionInfo, properties::OptionProperty::DisplayType::Dropdown ) , _otherDataColorMapPath(OtherDataColorMapInfo) , _otherDataRange( OtherDataValueRangeInfo, glm::vec2(0.f, 1.f), glm::vec2(-10.f, -10.f), glm::vec2(10.f, 10.f) ) , _fixedColor(FixedColorInfo, glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) , _filterOutOfRange(FilterOutOfRangeInfo, false) , _pointSpreadFunctionTexturePath(PsfTextureInfo) , _psfMethodOption( PSFMethodOptionInfo, properties::OptionProperty::DisplayType::Dropdown ) , _psfMultiplyOption( SizeCompositionOptionInfo, properties::OptionProperty::DisplayType::Dropdown ) , _lumCent(LumPercentInfo, 0.5f, 0.f, 3.f) , _radiusCent(RadiusPercentInfo, 0.5f, 0.f, 3.f) , _brightnessCent(BrightnessPercentInfo, 0.5f, 0.f, 3.f) , _magnitudeExponent(MagnitudeExponentInfo, 4.f, 0.f, 8.f) , _spencerPSFParamOwner(SpencerPSFParamOwnerInfo) , _p0Param(P0ParamInfo, 0.384f, 0.f, 1.f) , _p1Param(P1ParamInfo, 0.478f, 0.f, 1.f) , _p2Param(P2ParamInfo, 0.138f, 0.f, 1.f) , _spencerAlphaConst(AlphaConstInfo, 0.02f, 0.000001f, 5.f) , _moffatPSFParamOwner(MoffatPSFParamOwnerInfo) , _FWHMConst(FWHMInfo, 10.4f, -100.f, 1000.f) , _moffatBetaConst(BetaInfo, 4.765f, 0.f, 100.f) , _renderingMethodOption( RenderMethodOptionInfo, properties::OptionProperty::DisplayType::Dropdown ) , _userProvidedTextureOwner(UserProvidedTextureOptionInfo) , _parametersOwner(ParametersOwnerOptionInfo) , _moffatMethodOwner(MoffatMethodOptionInfo) , _fadeInDistance( FadeInDistancesInfo, glm::vec2(0.f), glm::vec2(0.f), glm::vec2(100.f) ) , _disableFadeInDistance(DisableFadeInInfo, true) { using File = ghoul::filesystem::File; documentation::testSpecificationAndThrow( Documentation(), dictionary, "RenderableStars" ); addProperty(_opacity); registerUpdateRenderBinFromOpacity(); _speckFile = absPath(dictionary.value<std::string>(KeyFile)); _speckFile.onChange([&]() { _speckFileIsDirty = true; }); addProperty(_speckFile); _colorTexturePath = absPath( dictionary.value<std::string>(ColorTextureInfo.identifier) ); _colorTextureFile = std::make_unique<File>(_colorTexturePath); /*_shapeTexturePath = absPath(dictionary.value<std::string>( ShapeTextureInfo.identifier )); _shapeTextureFile = std::make_unique<File>(_shapeTexturePath);*/ if (dictionary.hasKey(OtherDataColorMapInfo.identifier)) { _otherDataColorMapPath = absPath( dictionary.value<std::string>(OtherDataColorMapInfo.identifier) ); } _fixedColor.setViewOption(properties::Property::ViewOptions::Color, true); addProperty(_fixedColor); _colorOption.addOptions({ { ColorOption::Color, "Color" }, { ColorOption::Velocity, "Velocity" }, { ColorOption::Speed, "Speed" }, { ColorOption::OtherData, "Other Data" }, { ColorOption::FixedColor, "Fixed Color" } }); if (dictionary.hasKey(ColorOptionInfo.identifier)) { const std::string colorOption = dictionary.value<std::string>( ColorOptionInfo.identifier ); if (colorOption == "Color") { _colorOption = ColorOption::Color; } else if (colorOption == "Velocity") { _colorOption = ColorOption::Velocity; } else if (colorOption == "Speed") { _colorOption = ColorOption::Speed; } else if (colorOption == "OtherData") { _colorOption = ColorOption::OtherData; } else { _colorOption = ColorOption::FixedColor; } } _colorOption.onChange([&] { _dataIsDirty = true; }); addProperty(_colorOption); _colorTexturePath.onChange([&] { _colorTextureIsDirty = true; }); _colorTextureFile->setCallback([&](const File&) { _colorTextureIsDirty = true; }); addProperty(_colorTexturePath); /*_shapeTexturePath.onChange([&] { _shapeTextureIsDirty = true; }); _shapeTextureFile->setCallback([&](const File&) { _shapeTextureIsDirty = true; }); addProperty(_shapeTexturePath);*/ if (dictionary.hasKey(EnableTestGridInfo.identifier)) { _enableTestGrid = dictionary.value<bool>(EnableTestGridInfo.identifier); } if (dictionary.hasKey(OtherDataOptionInfo.identifier)) { _queuedOtherData = dictionary.value<std::string>(OtherDataOptionInfo.identifier); } _otherDataOption.onChange([&]() { _dataIsDirty = true; }); addProperty(_otherDataOption); addProperty(_otherDataRange); addProperty(_otherDataColorMapPath); _otherDataColorMapPath.onChange([&]() { _otherDataColorMapIsDirty = true; }); if (dictionary.hasKey(KeyStaticFilterValue)) { _staticFilterValue = static_cast<float>( dictionary.value<double>(KeyStaticFilterValue) ); } if (dictionary.hasKey(KeyStaticFilterReplacement)) { _staticFilterReplacementValue = static_cast<float>( dictionary.value<double>(KeyStaticFilterReplacement) ); } addProperty(_filterOutOfRange); _renderingMethodOption.addOption( RenderOptionPointSpreadFunction, "Point Spread Function Based" ); _renderingMethodOption.addOption(RenderOptionTexture, "Textured Based"); addProperty(_renderingMethodOption); if (dictionary.hasKey(RenderMethodOptionInfo.identifier)) { std::string renderingMethod = dictionary.value<std::string>(RenderMethodOptionInfo.identifier); if (renderingMethod == "PSF") { _renderingMethodOption = RenderOptionPointSpreadFunction; } else if (renderingMethod == "Texture Based") { _renderingMethodOption = RenderOptionTexture; } } else { _renderingMethodOption = RenderOptionTexture; } _pointSpreadFunctionTexturePath = absPath(dictionary.value<std::string>( PsfTextureInfo.identifier )); _pointSpreadFunctionFile = std::make_unique<File>(_pointSpreadFunctionTexturePath); _pointSpreadFunctionTexturePath.onChange([&]() { _pointSpreadFunctionTextureIsDirty = true; }); _pointSpreadFunctionFile->setCallback([&](const File&) { _pointSpreadFunctionTextureIsDirty = true; }); _userProvidedTextureOwner.addProperty(_pointSpreadFunctionTexturePath); _psfMethodOption.addOption(PsfMethodSpencer, "Spencer's Function"); _psfMethodOption.addOption(PsfMethodMoffat, "Moffat's Function"); _psfMethodOption = PsfMethodSpencer; _psfMethodOption.onChange([&]() { renderPSFToTexture(); }); _parametersOwner.addProperty(_psfMethodOption); _psfMultiplyOption.addOption(0, "Use Star's Apparent Brightness"); _psfMultiplyOption.addOption(1, "Use Star's Luminosity and Size"); _psfMultiplyOption.addOption(2, "Luminosity, Size, App Brightness"); _psfMultiplyOption.addOption(3, "Absolute Magnitude"); _psfMultiplyOption.addOption(4, "Apparent Magnitude"); _psfMultiplyOption.addOption(5, "Distance Modulus"); if (dictionary.hasKey(MagnitudeExponentInfo.identifier)) { std::string sizeCompositionOption = dictionary.value<std::string>(SizeCompositionOptionInfo.identifier); if (sizeCompositionOption == "App Brightness") { _psfMultiplyOption = 0; } else if (sizeCompositionOption == "Lum and Size") { _psfMultiplyOption = 1; } else if (sizeCompositionOption == "Lum, Size and App Brightness") { _psfMultiplyOption = 2; } else if (sizeCompositionOption == "Abs Magnitude") { _psfMultiplyOption = 3; } else if (sizeCompositionOption == "App Maginitude") { _psfMultiplyOption = 4; } else if (sizeCompositionOption == "Distance Modulus") { _psfMultiplyOption = 5; } } else { _psfMultiplyOption = 5; } _parametersOwner.addProperty(_psfMultiplyOption); _parametersOwner.addProperty(_lumCent); _parametersOwner.addProperty(_radiusCent); _parametersOwner.addProperty(_brightnessCent); if (dictionary.hasKey(MagnitudeExponentInfo.identifier)) { _magnitudeExponent = static_cast<float>( dictionary.value<double>(MagnitudeExponentInfo.identifier) ); } _parametersOwner.addProperty(_magnitudeExponent); auto renderPsf = [&]() { renderPSFToTexture(); }; _spencerPSFParamOwner.addProperty(_p0Param); _p0Param.onChange(renderPsf); _spencerPSFParamOwner.addProperty(_p1Param); _p1Param.onChange(renderPsf); _spencerPSFParamOwner.addProperty(_p2Param); _p2Param.onChange(renderPsf); _spencerPSFParamOwner.addProperty(_spencerAlphaConst); _spencerAlphaConst.onChange(renderPsf); _moffatPSFParamOwner.addProperty(_FWHMConst); _FWHMConst.onChange(renderPsf); _moffatPSFParamOwner.addProperty(_moffatBetaConst); _moffatBetaConst.onChange(renderPsf); _parametersOwner.addPropertySubOwner(_spencerPSFParamOwner); _parametersOwner.addPropertySubOwner(_moffatPSFParamOwner); addPropertySubOwner(_userProvidedTextureOwner); addPropertySubOwner(_parametersOwner); addPropertySubOwner(_moffatMethodOwner); if (dictionary.hasKey(FadeInDistancesInfo.identifier)) { glm::vec2 v = dictionary.value<glm::dvec2>(FadeInDistancesInfo.identifier); _fadeInDistance = v; _disableFadeInDistance = false; addProperty(_fadeInDistance); addProperty(_disableFadeInDistance); } } RenderableStars::~RenderableStars() {} bool RenderableStars::isReady() const { return _program && _pointSpreadFunctionTexture; } void RenderableStars::initializeGL() { _program = global::renderEngine->buildRenderProgram( "Star", absPath("${MODULE_SPACE}/shaders/star_vs.glsl"), absPath("${MODULE_SPACE}/shaders/star_fs.glsl"), absPath("${MODULE_SPACE}/shaders/star_ge.glsl") ); ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); loadData(); if (!_queuedOtherData.empty()) { auto it = std::find(_dataNames.begin(), _dataNames.end(), _queuedOtherData); if (it == _dataNames.end()) { LERROR(fmt::format("Could not find other data column {}", _queuedOtherData)); } else { _otherDataOption = static_cast<int>(std::distance(_dataNames.begin(), it)); _queuedOtherData.clear(); } } _speckFileIsDirty = false; LDEBUG("Creating Polygon Texture"); glGenVertexArrays(1, &_psfVao); glGenBuffers(1, &_psfVbo); glBindVertexArray(_psfVao); glBindBuffer(GL_ARRAY_BUFFER, _psfVbo); const GLfloat vertexData[] = { //x y s t -1.f, -1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, -1.f, 1.f, 0.f, 1.f, -1.f, -1.f, 0.f, 0.f, 1.f, -1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glVertexAttribPointer( 0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, nullptr ); glEnableVertexAttribArray(0); glBindVertexArray(0); glGenTextures(1, &_psfTexture); glBindTexture(GL_TEXTURE_2D, _psfTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, _psfTextureSize, _psfTextureSize, 0, GL_RGBA, GL_BYTE, nullptr ); LDEBUG("Creating Convolution Texture"); glGenTextures(1, &_convolvedTexture); glBindTexture(GL_TEXTURE_2D, _convolvedTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, _convolvedfTextureSize, _convolvedfTextureSize, 0, GL_RGBA, GL_BYTE, nullptr ); //loadShapeTexture(); loadPSFTexture(); renderPSFToTexture(); } void RenderableStars::deinitializeGL() { glDeleteBuffers(1, &_vbo); _vbo = 0; glDeleteVertexArrays(1, &_vao); _vao = 0; _colorTexture = nullptr; //_shapeTexture = nullptr; if (_program) { global::renderEngine->removeRenderProgram(_program.get()); _program = nullptr; } } void RenderableStars::loadPSFTexture() { _pointSpreadFunctionTexture = nullptr; if (!_pointSpreadFunctionTexturePath.value().empty() && std::filesystem::exists(_pointSpreadFunctionTexturePath.value())) { _pointSpreadFunctionTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_pointSpreadFunctionTexturePath) ); if (_pointSpreadFunctionTexture) { LDEBUG(fmt::format( "Loaded texture from '{}'", absPath(_pointSpreadFunctionTexturePath) )); _pointSpreadFunctionTexture->uploadTexture(); } _pointSpreadFunctionTexture->setFilter( ghoul::opengl::Texture::FilterMode::AnisotropicMipMap ); _pointSpreadFunctionFile = std::make_unique<ghoul::filesystem::File>( _pointSpreadFunctionTexturePath ); _pointSpreadFunctionFile->setCallback( [&](const ghoul::filesystem::File&) { _pointSpreadFunctionTextureIsDirty = true; } ); } _pointSpreadFunctionTextureIsDirty = false; } void RenderableStars::renderPSFToTexture() { // Saves current FBO first GLint defaultFBO; defaultFBO = global::renderEngine->openglStateCache().defaultFramebuffer(); // GLint m_viewport[4]; // global::renderEngine.openglStateCache().viewPort(m_viewport); // Creates the FBO for the calculations GLuint psfFBO; glGenFramebuffers(1, &psfFBO); glBindFramebuffer(GL_FRAMEBUFFER, psfFBO); GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, drawBuffers); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _psfTexture, 0); glViewport(0, 0, _psfTextureSize, _psfTextureSize); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); std::unique_ptr<ghoul::opengl::ProgramObject> program = ghoul::opengl::ProgramObject::Build( "RenderStarPSFToTexture", absPath("${MODULE_SPACE}/shaders/psfToTexture_vs.glsl"), absPath("${MODULE_SPACE}/shaders/psfToTexture_fs.glsl") ); program->activate(); constexpr const float black[] = { 0.f, 0.f, 0.f, 0.f }; glClearBufferfv(GL_COLOR, 0, black); program->setUniform("psfMethod", _psfMethodOption.value()); program->setUniform("p0Param", _p0Param); program->setUniform("p1Param", _p1Param); program->setUniform("p2Param", _p2Param); program->setUniform("alphaConst", _spencerAlphaConst); program->setUniform("FWHM", _FWHMConst); program->setUniform("betaConstant", _moffatBetaConst); // Draws psf to texture glBindVertexArray(_psfVao); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); program->deactivate(); // JCC: Convolution is disabled while FFT is not enabled //// Now convolves with a disc shape for final shape //GLuint convolveFBO; //glGenFramebuffers(1, &convolveFBO); //glBindFramebuffer(GL_FRAMEBUFFER, convolveFBO); //glDrawBuffers(1, drawBuffers); //glFramebufferTexture( // GL_FRAMEBUFFER, // GL_COLOR_ATTACHMENT0, // _convolvedTexture, // 0 //); //glViewport(0, 0, _convolvedfTextureSize, _convolvedfTextureSize); //std::unique_ptr<ghoul::opengl::ProgramObject> programConvolve = // ghoul::opengl::ProgramObject::Build("ConvolvePSFandStarShape", // absPath("${MODULE_SPACE}/shaders/convolution_vs.glsl"), // absPath("${MODULE_SPACE}/shaders/convolution_fs.glsl") // ); //programConvolve->activate(); //glClearBufferfv(GL_COLOR, 0, black); //ghoul::opengl::TextureUnit psfTextureUnit; //psfTextureUnit.activate(); //glBindTexture(GL_TEXTURE_2D, _psfTexture); //programConvolve->setUniform("psfTexture", psfTextureUnit); // //ghoul::opengl::TextureUnit shapeTextureUnit; //shapeTextureUnit.activate(); //_shapeTexture->bind(); //programConvolve->setUniform("shapeTexture", shapeTextureUnit); //programConvolve->setUniform("psfTextureSize", _psfTextureSize); //programConvolve->setUniform( // "convolvedfTextureSize", // _convolvedfTextureSize //); //// Convolves to texture //glBindVertexArray(_psfVao); //glDrawArrays(GL_TRIANGLES, 0, 6); //glBindVertexArray(0); //programConvolve->deactivate(); //// Restores system state //glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); //glViewport( // m_viewport[0], // m_viewport[1], // m_viewport[2], // m_viewport[3] //); //glDeleteFramebuffers(1, &psfFBO); //glDeleteFramebuffers(1, &convolveFBO); // Restores OpenGL blending state global::renderEngine->openglStateCache().resetBlendState(); } void RenderableStars::render(const RenderData& data, RendererTasks&) { if (_fullData.empty()) { return; } glBlendFunc(GL_SRC_ALPHA, GL_ONE); glDepthMask(false); _program->activate(); glm::dvec3 eyePosition = glm::dvec3( glm::inverse(data.camera.combinedViewMatrix()) * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); _program->setUniform(_uniformCache.eyePosition, eyePosition); glm::dvec3 cameraUp = data.camera.lookUpVectorWorldSpace(); _program->setUniform(_uniformCache.cameraUp, cameraUp); glm::dmat4 modelMatrix = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * glm::dmat4(data.modelTransform.rotation) * glm::scale(glm::dmat4(1.0), data.modelTransform.scale); glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); glm::dmat4 cameraViewProjectionMatrix = projectionMatrix * data.camera.combinedViewMatrix(); _program->setUniform(_uniformCache.modelMatrix, modelMatrix); _program->setUniform( _uniformCache.cameraViewProjectionMatrix, cameraViewProjectionMatrix ); _program->setUniform(_uniformCache.colorOption, _colorOption); _program->setUniform(_uniformCache.magnitudeExponent, _magnitudeExponent); _program->setUniform(_uniformCache.psfParamConf, _psfMultiplyOption.value()); _program->setUniform(_uniformCache.lumCent, _lumCent); _program->setUniform(_uniformCache.radiusCent, _radiusCent); _program->setUniform(_uniformCache.brightnessCent, _brightnessCent); if (_colorOption == ColorOption::FixedColor) { if (_uniformCache.fixedColor == -1) { _uniformCache.fixedColor = _program->uniformLocation("fixedColor"); } _program->setUniform(_uniformCache.fixedColor, _fixedColor); } float fadeInVariable = 1.f; if (!_disableFadeInDistance) { float distCamera = static_cast<float>(glm::length(data.camera.positionVec3())); const glm::vec2 fadeRange = _fadeInDistance; const double a = 1.f / ((fadeRange.y - fadeRange.x) * PARSEC); const double b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); const double funcValue = a * distCamera + b; fadeInVariable *= static_cast<float>(funcValue > 1.f ? 1.f : funcValue); _program->setUniform(_uniformCache.alphaValue, _opacity * fadeInVariable); } else { _program->setUniform(_uniformCache.alphaValue, _opacity); } ghoul::opengl::TextureUnit psfUnit; psfUnit.activate(); if (_renderingMethodOption.value() == 0) { // PSF Based Methods glBindTexture(GL_TEXTURE_2D, _psfTexture);\ // Convolutioned texture //glBindTexture(GL_TEXTURE_2D, _convolvedTexture); } else if (_renderingMethodOption.value() == 1) { // Textured based Method _pointSpreadFunctionTexture->bind(); } _program->setUniform(_uniformCache.psfTexture, psfUnit); ghoul::opengl::TextureUnit colorUnit; if (_colorTexture) { colorUnit.activate(); _colorTexture->bind(); _program->setUniform(_uniformCache.colorTexture, colorUnit); } ghoul::opengl::TextureUnit otherDataUnit; if (_colorOption == ColorOption::OtherData && _otherDataColorMapTexture) { otherDataUnit.activate(); _otherDataColorMapTexture->bind(); _program->setUniform(_uniformCache.otherDataTexture, otherDataUnit); } else { // We need to set the uniform to something, or the shader doesn't work _program->setUniform(_uniformCache.otherDataTexture, colorUnit); } // Same here, if we don't set this value, the rendering disappears even if we don't // use this color mode --- abock 2018-11-19 _program->setUniform(_uniformCache.otherDataRange, _otherDataRange); _program->setUniform(_uniformCache.filterOutOfRange, _filterOutOfRange); glBindVertexArray(_vao); const GLsizei nStars = static_cast<GLsizei>(_fullData.size() / _nValuesPerStar); glDrawArrays(GL_POINTS, 0, nStars); glBindVertexArray(0); _program->deactivate(); // Restores OpenGL blending state global::renderEngine->openglStateCache().resetBlendState(); global::renderEngine->openglStateCache().resetDepthState(); } void RenderableStars::update(const UpdateData&) { if (_speckFileIsDirty) { loadData(); _speckFileIsDirty = false; _dataIsDirty = true; } if (_fullData.empty()) { return; } if (_dataIsDirty) { const int value = _colorOption; LDEBUG("Regenerating data"); createDataSlice(ColorOption(value)); int size = static_cast<int>(_slicedData.size()); if (_vao == 0) { glGenVertexArrays(1, &_vao); } if (_vbo == 0) { glGenBuffers(1, &_vbo); } glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData( GL_ARRAY_BUFFER, size * sizeof(GLfloat), _slicedData.data(), GL_STATIC_DRAW ); GLint positionAttrib = _program->attributeLocation("in_position"); // bvLumAbsMagAppMag = bv color, luminosity, abs magnitude and app magnitude GLint bvLumAbsMagAppMagAttrib = _program->attributeLocation( "in_bvLumAbsMagAppMag" ); const size_t nStars = _fullData.size() / _nValuesPerStar; const size_t nValues = _slicedData.size() / nStars; GLsizei stride = static_cast<GLsizei>(sizeof(GLfloat) * nValues); glEnableVertexAttribArray(positionAttrib); glEnableVertexAttribArray(bvLumAbsMagAppMagAttrib); const int colorOption = _colorOption; switch (colorOption) { case ColorOption::Color: case ColorOption::FixedColor: glVertexAttribPointer( positionAttrib, 3, GL_FLOAT, GL_FALSE, stride, nullptr // = offsetof(ColorVBOLayout, position) ); glVertexAttribPointer( bvLumAbsMagAppMagAttrib, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(ColorVBOLayout, value)) ); break; case ColorOption::Velocity: { glVertexAttribPointer( positionAttrib, 3, GL_FLOAT, GL_FALSE, stride, nullptr // = offsetof(VelocityVBOLayout, position) ); glVertexAttribPointer( bvLumAbsMagAppMagAttrib, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(VelocityVBOLayout, value)) ); GLint velocityAttrib = _program->attributeLocation("in_velocity"); glEnableVertexAttribArray(velocityAttrib); glVertexAttribPointer( velocityAttrib, 3, GL_FLOAT, GL_TRUE, stride, reinterpret_cast<void*>(offsetof(VelocityVBOLayout, vx)) // NOLINT ); break; } case ColorOption::Speed: { glVertexAttribPointer( positionAttrib, 3, GL_FLOAT, GL_FALSE, stride, nullptr // = offsetof(SpeedVBOLayout, position) ); glVertexAttribPointer( bvLumAbsMagAppMagAttrib, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(SpeedVBOLayout, value)) ); GLint speedAttrib = _program->attributeLocation("in_speed"); glEnableVertexAttribArray(speedAttrib); glVertexAttribPointer( speedAttrib, 1, GL_FLOAT, GL_TRUE, stride, reinterpret_cast<void*>(offsetof(SpeedVBOLayout, speed)) ); break; } case ColorOption::OtherData: { glVertexAttribPointer( positionAttrib, 3, GL_FLOAT, GL_FALSE, stride, nullptr // = offsetof(OtherDataLayout, position) ); glVertexAttribPointer( bvLumAbsMagAppMagAttrib, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(OtherDataLayout, value)) // NOLINT ); } } glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); _dataIsDirty = false; } if (_pointSpreadFunctionTextureIsDirty) { LDEBUG("Reloading Point Spread Function texture"); loadPSFTexture(); } if (_colorTextureIsDirty) { LDEBUG("Reloading Color Texture"); _colorTexture = nullptr; if (_colorTexturePath.value() != "") { _colorTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_colorTexturePath) ); if (_colorTexture) { LDEBUG(fmt::format( "Loaded texture from '{}'", absPath(_colorTexturePath) )); _colorTexture->uploadTexture(); } _colorTextureFile = std::make_unique<ghoul::filesystem::File>( _colorTexturePath ); _colorTextureFile->setCallback( [&](const ghoul::filesystem::File&) { _colorTextureIsDirty = true; } ); } _colorTextureIsDirty = false; } //loadShapeTexture(); if (_otherDataColorMapIsDirty) { LDEBUG("Reloading Color Texture"); _otherDataColorMapTexture = nullptr; if (!_otherDataColorMapPath.value().empty()) { _otherDataColorMapTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_otherDataColorMapPath) ); if (_otherDataColorMapTexture) { LDEBUG(fmt::format( "Loaded texture from '{}'", absPath(_otherDataColorMapPath) )); _otherDataColorMapTexture->uploadTexture(); } } _otherDataColorMapIsDirty = false; } if (_program->isDirty()) { _program->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); } } /* void RenderableStars::loadShapeTexture() { if (_shapeTextureIsDirty) { LDEBUG("Reloading Shape Texture"); _shapeTexture = nullptr; if (_shapeTexturePath.value() != "") { _shapeTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_shapeTexturePath) ); if (_shapeTexture) { LDEBUG(fmt::format( "Loaded texture from '{}'", absPath(_shapeTexturePath) )); _shapeTexture->uploadTexture(); } _shapeTextureFile = std::make_unique<ghoul::filesystem::File>( _shapeTexturePath ); _shapeTextureFile->setCallback( [&](const ghoul::filesystem::File&) { _shapeTextureIsDirty = true; } ); } _shapeTextureIsDirty = false; } } */ void RenderableStars::loadData() { std::string _file = _speckFile; if (!FileSys.fileExists(absPath(_file))) { return; } std::string cachedFile = FileSys.cacheManager()->cachedFilename( _file, ghoul::filesystem::CacheManager::Persistent::Yes ); _nValuesPerStar = 0; _slicedData.clear(); _fullData.clear(); _dataNames.clear(); bool hasCachedFile = FileSys.fileExists(cachedFile); if (hasCachedFile) { LINFO(fmt::format("Cached file '{}' used for Speck file '{}'", cachedFile, _file )); bool success = loadCachedFile(cachedFile); if (success) { return; } else { FileSys.cacheManager()->removeCacheFile(_file); // Intentional fall-through to the 'else' computation to generate the cache // file for the next run } } else { LINFO(fmt::format("Cache for Speck file '{}' not found", _file)); } LINFO(fmt::format("Loading Speck file '{}'", _file)); readSpeckFile(); LINFO("Saving cache"); saveCachedFile(cachedFile); } void RenderableStars::readSpeckFile() { std::string _file = _speckFile; std::ifstream file(_file); if (!file.good()) { LERROR(fmt::format("Failed to open Speck file '{}'", _file)); return; } // The beginning of the speck file has a header that either contains comments // (signaled by a preceding '#') or information about the structure of the file // (signaled by the keywords 'datavar', 'texturevar', and 'texture') std::string line; while (true) { std::streampos position = file.tellg(); std::getline(file, line, '\n'); if (line[0] == '#' || line.empty()) { continue; } if (line.substr(0, 7) != "datavar" && line.substr(0, 10) != "texturevar" && line.substr(0, 7) != "texture") { // we read a line that doesn't belong to the header, so we have to jump back // before the beginning of the current line if (_enableTestGrid) { file.seekg(position - std::streamoff(8)); } break; } if (line.substr(0, 7) == "datavar") { // datavar lines are structured as follows: // datavar # description // where # is the index of the data variable; so if we repeatedly overwrite // the 'nValues' variable with the latest index, we will end up with the total // number of values (+3 since X Y Z are not counted in the Speck file index) std::stringstream str(line); std::string dummy; str >> dummy; str >> _nValuesPerStar; std::string name; str >> name; _dataNames.push_back(name); // +3 because the position x, y, z if (name == "lum") { _lumArrayPos = _nValuesPerStar + 3; } else if (name == "absmag") { _absMagArrayPos = _nValuesPerStar + 3; } else if (name == "appmag") { _appMagArrayPos = _nValuesPerStar + 3; } else if (name == "colorb_v") { _bvColorArrayPos = _nValuesPerStar + 3; } else if (name == "vx") { _velocityArrayPos = _nValuesPerStar + 3; } else if (name == "speed") { _speedArrayPos = _nValuesPerStar + 3; } _nValuesPerStar += 1; // We want the number, but the index is 0 based } } _nValuesPerStar += 3; // X Y Z are not counted in the Speck file indices _otherDataOption.addOptions(_dataNames); float minLumValue = std::numeric_limits<float>::max(); float maxLumValue = std::numeric_limits<float>::min(); do { std::vector<float> values(_nValuesPerStar); std::stringstream str(line); for (int i = 0; i < _nValuesPerStar; ++i) { str >> values[i]; } bool nullArray = true; for (float v : values) { if (v != 0.0) { nullArray = false; break; } } minLumValue = values[_lumArrayPos] < minLumValue ? values[_lumArrayPos] : minLumValue; maxLumValue = values[_lumArrayPos] > maxLumValue ? values[_lumArrayPos] : maxLumValue; if (!nullArray) { _fullData.insert(_fullData.end(), values.begin(), values.end()); } std::getline(file, line, '\n'); } while (!file.eof()); // Normalize Luminosity: for (size_t i = 0; i < _fullData.size(); i += _nValuesPerStar) { _fullData[i + _lumArrayPos] = (_fullData[i + _lumArrayPos] - minLumValue) / (maxLumValue - minLumValue); } } bool RenderableStars::loadCachedFile(const std::string& file) { std::ifstream fileStream(file, std::ifstream::binary); if (fileStream.good()) { int8_t version = 0; fileStream.read(reinterpret_cast<char*>(&version), sizeof(int8_t)); if (version != CurrentCacheVersion) { LINFO("The format of the cached file has changed: deleting old cache"); fileStream.close(); FileSys.deleteFile(file); return false; } int32_t nValues = 0; fileStream.read(reinterpret_cast<char*>(&nValues), sizeof(int32_t)); fileStream.read(reinterpret_cast<char*>(&_nValuesPerStar), sizeof(int32_t)); fileStream.read(reinterpret_cast<char*>(&_lumArrayPos), sizeof(int32_t)); fileStream.read(reinterpret_cast<char*>(&_absMagArrayPos), sizeof(int32_t)); fileStream.read(reinterpret_cast<char*>(&_appMagArrayPos), sizeof(int32_t)); fileStream.read(reinterpret_cast<char*>(&_bvColorArrayPos), sizeof(int32_t)); fileStream.read(reinterpret_cast<char*>(&_velocityArrayPos), sizeof(int32_t)); fileStream.read(reinterpret_cast<char*>(&_speedArrayPos), sizeof(int32_t)); for (int i = 0; i < _nValuesPerStar - 3; ++i) { uint16_t len; fileStream.read(reinterpret_cast<char*>(&len), sizeof(uint16_t)); std::vector<char> buffer(len); fileStream.read(buffer.data(), len); std::string value(buffer.begin(), buffer.end()); _dataNames.push_back(value); } _otherDataOption.addOptions(_dataNames); _fullData.resize(nValues); fileStream.read(reinterpret_cast<char*>( _fullData.data()), nValues * sizeof(_fullData[0]) ); bool success = fileStream.good(); return success; } else { LERROR(fmt::format("Error opening file '{}' for loading cache file", file)); return false; } } void RenderableStars::saveCachedFile(const std::string& file) const { std::ofstream fileStream(file, std::ofstream::binary); if (!fileStream.good()) { LERROR(fmt::format("Error opening file '{}' for save cache file", file)); return; } fileStream.write( reinterpret_cast<const char*>(&CurrentCacheVersion), sizeof(int8_t) ); int32_t nValues = static_cast<int32_t>(_fullData.size()); if (nValues == 0) { throw ghoul::RuntimeError("Error writing cache: No values were loaded"); } fileStream.write(reinterpret_cast<const char*>(&nValues), sizeof(int32_t)); int32_t nValuesPerStar = static_cast<int32_t>(_nValuesPerStar); fileStream.write(reinterpret_cast<const char*>(&nValuesPerStar), sizeof(int32_t)); fileStream.write(reinterpret_cast<const char*>(&_lumArrayPos), sizeof(int32_t)); fileStream.write(reinterpret_cast<const char*>(&_absMagArrayPos), sizeof(int32_t)); fileStream.write(reinterpret_cast<const char*>(&_appMagArrayPos), sizeof(int32_t)); fileStream.write(reinterpret_cast<const char*>(&_bvColorArrayPos), sizeof(int32_t)); fileStream.write(reinterpret_cast<const char*>(&_velocityArrayPos), sizeof(int32_t)); fileStream.write(reinterpret_cast<const char*>(&_speedArrayPos), sizeof(int32_t)); // -3 as we don't want to save the xyz values that are in the beginning of the file for (int i = 0; i < _nValuesPerStar - 3; ++i) { uint16_t len = static_cast<uint16_t>(_dataNames[i].size()); fileStream.write(reinterpret_cast<const char*>(&len), sizeof(uint16_t)); fileStream.write(_dataNames[i].c_str(), len); } size_t nBytes = nValues * sizeof(_fullData[0]); fileStream.write(reinterpret_cast<const char*>(_fullData.data()), nBytes); } void RenderableStars::createDataSlice(ColorOption option) { _slicedData.clear(); _otherDataRange = glm::vec2( std::numeric_limits<float>::max(), -std::numeric_limits<float>::max() ); for (size_t i = 0; i < _fullData.size(); i += _nValuesPerStar) { glm::vec3 position = glm::vec3( _fullData[i + 0], _fullData[i + 1], _fullData[i + 2] ); position *= openspace::distanceconstants::Parsec; switch (option) { case ColorOption::Color: case ColorOption::FixedColor: { union { ColorVBOLayout value; std::array<float, sizeof(ColorVBOLayout) / sizeof(float)> data; } layout; layout.value.position = { { position[0], position[1], position[2] } }; if (_enableTestGrid) { float sunColor = 0.650f; layout.value.value = sunColor;// _fullData[i + 3]; } else { layout.value.value = _fullData[i + _bvColorArrayPos]; } layout.value.luminance = _fullData[i + _lumArrayPos]; layout.value.absoluteMagnitude = _fullData[i + _absMagArrayPos]; layout.value.apparentMagnitude = _fullData[i + _appMagArrayPos]; _slicedData.insert( _slicedData.end(), layout.data.begin(), layout.data.end()); break; } case ColorOption::Velocity: { union { VelocityVBOLayout value; std::array<float, sizeof(VelocityVBOLayout) / sizeof(float)> data; } layout; layout.value.position = { { position[0], position[1], position[2] } }; layout.value.value = _fullData[i + _bvColorArrayPos]; layout.value.luminance = _fullData[i + _lumArrayPos]; layout.value.absoluteMagnitude = _fullData[i + _absMagArrayPos]; layout.value.apparentMagnitude = _fullData[i + _appMagArrayPos]; layout.value.vx = _fullData[i + _velocityArrayPos]; layout.value.vy = _fullData[i + _velocityArrayPos + 1]; layout.value.vz = _fullData[i + _velocityArrayPos + 2]; _slicedData.insert( _slicedData.end(), layout.data.begin(), layout.data.end() ); break; } case ColorOption::Speed: { union { SpeedVBOLayout value; std::array<float, sizeof(SpeedVBOLayout) / sizeof(float)> data; } layout; layout.value.position = { { position[0], position[1], position[2] } }; layout.value.value = _fullData[i + _bvColorArrayPos]; layout.value.luminance = _fullData[i + _lumArrayPos]; layout.value.absoluteMagnitude = _fullData[i + _absMagArrayPos]; layout.value.apparentMagnitude = _fullData[i + _appMagArrayPos]; layout.value.speed = _fullData[i + _speedArrayPos]; _slicedData.insert( _slicedData.end(), layout.data.begin(), layout.data.end() ); break; } case ColorOption::OtherData: { union { OtherDataLayout value; std::array<float, sizeof(OtherDataLayout)> data; } layout = {}; layout.value.position = { { position[0], position[1], position[2] } }; int index = _otherDataOption.value(); // plus 3 because of the position layout.value.value = _fullData[i + index + 3]; if (_staticFilterValue.has_value() && layout.value.value == _staticFilterValue) { layout.value.value = _staticFilterReplacementValue; } glm::vec2 range = _otherDataRange.value(); range.x = std::min(range.x, layout.value.value); range.y = std::max(range.y, layout.value.value); _otherDataRange = range; _otherDataRange.setMinValue(glm::vec2(range.x)); _otherDataRange.setMaxValue(glm::vec2(range.y)); layout.value.luminance = _fullData[i + _lumArrayPos]; layout.value.absoluteMagnitude = _fullData[i + _absMagArrayPos]; layout.value.apparentMagnitude = _fullData[i + _appMagArrayPos]; _slicedData.insert( _slicedData.end(), layout.data.begin(), layout.data.end() ); break; } } } } } // namespace openspace
59,480
17,728
#include <iostream> #include <tuple> #include <vector> #include <sstream> #include "fmt/format.h" #include "graph/graph.hpp" #include "Data.hpp" #include "celero/Celero.h" constexpr int NumberOfSamples = 200000; constexpr int NumberOfIterations = 10; const auto graph_int = simpleDirectedGraph<int>(); const auto graph_unsigned_int = simpleDirectedGraph<unsigned int>(); const auto graph_size_t = simpleDirectedGraph<size_t>(); namespace { template<typename index_type> auto dfs_preordering() { auto data = simpleDirectedGraph<index_type>(); auto edges = std::get<0>(data); auto labels = std::get<1>(data); auto N = std::get<2>(data); std::stringstream output; graph::SparseGraph<index_type, typename decltype(edges)::value_type> g(edges, N, true); index_type rootVid = 0; return graph::dfs_preordering<std::vector<index_type>>(g, {rootVid}); } template <typename index_type> auto dfs_postordering() { auto data = simpleDirectedGraph<index_type>(); auto edges = std::get<0>(data); auto labels = std::get<1>(data); auto N = std::get<2>(data); std::stringstream output; graph::SparseGraph<index_type, typename decltype(edges)::value_type> g(edges, N, true); index_type rootVid = 0; return graph::dfs_postordering<std::vector<index_type>>(g, {rootVid}); } } CELERO_MAIN BASELINE(dfs_preordering, int, NumberOfSamples, NumberOfIterations) { celero::DoNotOptimizeAway(dfs_preordering<int>()); } BENCHMARK(dfs_preordering, unsigned_int, NumberOfSamples, NumberOfIterations) { celero::DoNotOptimizeAway(dfs_preordering<unsigned int>()); } BENCHMARK(dfs_preordering, size_t, NumberOfSamples, NumberOfIterations) { celero::DoNotOptimizeAway(dfs_preordering<size_t>()); } BASELINE(dfs_postordering, int, NumberOfSamples, NumberOfIterations) { celero::DoNotOptimizeAway(dfs_postordering<int>()); } BENCHMARK(dfs_postordering, unsigned_int, NumberOfSamples, NumberOfIterations) { celero::DoNotOptimizeAway(dfs_postordering<unsigned int>()); } BENCHMARK(dfs_postordering, size_t, NumberOfSamples, NumberOfIterations) { celero::DoNotOptimizeAway(dfs_postordering<size_t>()); }
2,245
794
// Copyright (c) 2020 The Orbit 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 "OrbitAccessibility/AccessibleInterface.h" #include "OrbitAccessibility/AccessibleInterfaceRegistry.h" orbit_accessibility::AccessibleInterface::AccessibleInterface() { AccessibleInterfaceRegistry::Get().Register(this); } orbit_accessibility::AccessibleInterface::~AccessibleInterface() { AccessibleInterfaceRegistry::Get().Unregister(this); }
527
153
//===- lib/Util/Printing.cpp ----------------------------------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #include "seec/Util/Fallthrough.hpp" #include "seec/Util/Printing.hpp" #include "llvm/Support/DataTypes.h" #include "llvm/Support/raw_ostream.h" namespace seec { namespace util { void writeJSONStringLiteral(llvm::StringRef S, llvm::raw_ostream &Out) { Out.write('"'); auto const End = S.data() + S.size(); for (auto It = S.data(); It != End; ++It) { switch (*It) { case '"': Out << "\\\""; break; case '\\': Out << "\\\\"; break; case '/': Out << "\\/"; break; case '\b': Out << "\\b"; break; case '\f': Out << "\\f"; break; case '\n': Out << "\\n"; break; case '\r': Out << "\\r"; break; case '\t': Out << "\\t"; break; default: Out.write(*It); break; } } Out.write('"'); } } // namespace util } // namespace seec
1,224
402
// Copyright (c) 2009-2016 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // this include is necessary to get MPI included before anything else to support intel MPI #include "hoomd/ExecutionConfiguration.h" #include <iostream> #include <functional> #include "hoomd/md/AllBondPotentials.h" #include "hoomd/ConstForceCompute.h" #include "hoomd/Initializers.h" #include "hoomd/SnapshotSystemData.h" using namespace std; using namespace std::placeholders; /*! \file fenebond_force_test.cc \brief Implements unit tests for BondForceCompute and child classes \ingroup unit_tests */ #include "hoomd/test/upp11_config.h" HOOMD_UP_MAIN(); //! Typedef to make using the std::function factory easier typedef std::function<std::shared_ptr<PotentialBondFENE> (std::shared_ptr<SystemDefinition> sysdef)> bondforce_creator; //! Perform some simple functionality tests of any BondForceCompute void bond_force_basic_tests(bondforce_creator bf_creator, std::shared_ptr<ExecutionConfiguration> exec_conf) { ///////////////////////////////////////////////////////// // start with the simplest possible test: 2 particles in a huge box with only one bond type std::shared_ptr<SystemDefinition> sysdef_2(new SystemDefinition(2, BoxDim(1000.0), 1, 1, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_2 = sysdef_2->getParticleData(); pdata_2->setFlags(~PDataFlags(0)); pdata_2->setPosition(0,make_scalar3(0.0,0.0,0.0)); pdata_2->setPosition(1,make_scalar3(0.9,0.0,0.0)); // create the bond force compute to check std::shared_ptr<PotentialBondFENE> fc_2 = bf_creator(sysdef_2); fc_2->setParams(0, make_scalar4(Scalar(1.5), Scalar(1.1), Scalar(1.0), Scalar(1.0))); // compute the force and check the results fc_2->compute(0); { GPUArray<Scalar4>& force_array_1 = fc_2->getForceArray(); GPUArray<Scalar>& virial_array_1 = fc_2->getVirialArray(); unsigned int pitch = virial_array_1.getPitch(); ArrayHandle<Scalar4> h_force_1(force_array_1,access_location::host,access_mode::read); ArrayHandle<Scalar> h_virial_1(virial_array_1,access_location::host,access_mode::read); // check that the force is correct, it should be 0 since we haven't created any bonds yet MY_CHECK_SMALL(h_force_1.data[0].x, tol_small); MY_CHECK_SMALL(h_force_1.data[0].y, tol_small); MY_CHECK_SMALL(h_force_1.data[0].z, tol_small); MY_CHECK_SMALL(h_force_1.data[0].w, tol_small); MY_CHECK_SMALL(h_virial_1.data[0*pitch+0], tol_small); MY_CHECK_SMALL(h_virial_1.data[1*pitch+0], tol_small); MY_CHECK_SMALL(h_virial_1.data[2*pitch+0], tol_small); MY_CHECK_SMALL(h_virial_1.data[3*pitch+0], tol_small); MY_CHECK_SMALL(h_virial_1.data[4*pitch+0], tol_small); MY_CHECK_SMALL(h_virial_1.data[5*pitch+0], tol_small); } // add a bond and check again sysdef_2->getBondData()->addBondedGroup(Bond(0, 0, 1)); fc_2->compute(1); { // this time there should be a force GPUArray<Scalar4>& force_array_2 = fc_2->getForceArray(); GPUArray<Scalar>& virial_array_2 = fc_2->getVirialArray(); unsigned int pitch = virial_array_2.getPitch(); ArrayHandle<Scalar4> h_force_2(force_array_2,access_location::host,access_mode::read); ArrayHandle<Scalar> h_virial_2(virial_array_2,access_location::host,access_mode::read); MY_CHECK_CLOSE(h_force_2.data[0].x, -30.581156, tol); MY_CHECK_SMALL(h_force_2.data[0].y, tol_small); MY_CHECK_SMALL(h_force_2.data[0].z, tol_small); MY_CHECK_CLOSE(h_force_2.data[0].w, 1.33177578 + 0.25/2, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_2.data[0*pitch+0] +h_virial_2.data[3*pitch+0] +h_virial_2.data[5*pitch+0]), 4.58717, tol); // check that the two forces are negatives of each other MY_CHECK_CLOSE(h_force_2.data[0].x, -h_force_2.data[1].x, tol); MY_CHECK_CLOSE(h_force_2.data[0].y, -h_force_2.data[1].y, tol); MY_CHECK_CLOSE(h_force_2.data[0].z, -h_force_2.data[1].z, tol); MY_CHECK_CLOSE(h_force_2.data[0].w, h_force_2.data[1].w, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_2.data[0*pitch+1] +h_virial_2.data[3*pitch+1] +h_virial_2.data[5*pitch+1]), 4.58717, tol); } // rearrange the two particles in memory and see if they are properly updated { ArrayHandle<Scalar4> h_pos(pdata_2->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_tag(pdata_2->getTags(), access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_rtag(pdata_2->getRTags(), access_location::host, access_mode::readwrite); h_pos.data[0].x = Scalar(0.9); h_pos.data[1].x = Scalar(0.0); h_tag.data[0] = 1; h_tag.data[1] = 0; h_rtag.data[0] = 1; h_rtag.data[1] = 0; } // notify that we made the sort pdata_2->notifyParticleSort(); // recompute at the same timestep, the forces should still be updated fc_2->compute(1); { // this time there should be a force GPUArray<Scalar4>& force_array_3 = fc_2->getForceArray(); GPUArray<Scalar>& virial_array_3 = fc_2->getVirialArray(); ArrayHandle<Scalar4> h_force_3(force_array_3,access_location::host,access_mode::read); ArrayHandle<Scalar> h_virial_3(virial_array_3,access_location::host,access_mode::read); MY_CHECK_CLOSE(h_force_3.data[0].x, 30.581156, tol); MY_CHECK_CLOSE(h_force_3.data[1].x, -30.581156, tol); } //////////////////////////////////////////////////////////////////// // now, lets do a more thorough test and include boundary conditions // there are way too many permutations to test here, so I will simply // test +x, -x, +y, -y, +z, and -z independantly // build a 6 particle system with particles across each boundary // also test more than one type of bond std::shared_ptr<SystemDefinition> sysdef_6(new SystemDefinition(6, BoxDim(20.0, 40.0, 60.0), 1, 3, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_6 = sysdef_6->getParticleData(); pdata_6->setFlags(~PDataFlags(0)); pdata_6->setPosition(0, make_scalar3(-9.6,0.0,0.0)); pdata_6->setPosition(1, make_scalar3(9.6, 0.0,0.0)); pdata_6->setPosition(2, make_scalar3(0.0,-19.6,0.0)); pdata_6->setPosition(3, make_scalar3(0.0,19.6,0.0)); pdata_6->setPosition(4, make_scalar3(0.0,0.0,-29.6)); pdata_6->setPosition(5, make_scalar3(0.0,0.0,29.6)); std::shared_ptr<PotentialBondFENE> fc_6 = bf_creator(sysdef_6); fc_6->setParams(0, make_scalar4(Scalar(1.5), Scalar(1.1), Scalar(1.0), Scalar(1.0))); fc_6->setParams(1, make_scalar4(Scalar(2.0*1.5), Scalar(1.1), Scalar(1.0), Scalar(1.0))); fc_6->setParams(2, make_scalar4(Scalar(1.5), Scalar(1.0), Scalar(1.0), Scalar(1.0))); sysdef_6->getBondData()->addBondedGroup(Bond(0, 0,1)); sysdef_6->getBondData()->addBondedGroup(Bond(1, 2,3)); sysdef_6->getBondData()->addBondedGroup(Bond(2, 4,5)); fc_6->compute(0); { // check that the forces are correctly computed GPUArray<Scalar4>& force_array_4 = fc_6->getForceArray(); GPUArray<Scalar>& virial_array_4 = fc_6->getVirialArray(); unsigned int pitch = virial_array_4.getPitch(); ArrayHandle<Scalar4> h_force_4(force_array_4,access_location::host,access_mode::read); ArrayHandle<Scalar> h_virial_4(virial_array_4,access_location::host,access_mode::read); MY_CHECK_CLOSE(h_force_4.data[0].x, 187.121131, tol); MY_CHECK_SMALL(h_force_4.data[0].y, tol_small); MY_CHECK_SMALL(h_force_4.data[0].z, tol_small); MY_CHECK_CLOSE(h_force_4.data[0].w, 5.71016443 + 0.25/2, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_4.data[0*pitch+0] +h_virial_4.data[3*pitch+0] +h_virial_4.data[5*pitch+0]), 24.9495, tol); MY_CHECK_CLOSE(h_force_4.data[1].x, -187.121131, tol); MY_CHECK_SMALL(h_force_4.data[1].y, tol_small); MY_CHECK_SMALL(h_force_4.data[1].z, tol_small); MY_CHECK_CLOSE(h_force_4.data[1].w, 5.71016443 + 0.25/2, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_4.data[0*pitch+1] +h_virial_4.data[3*pitch+1] +h_virial_4.data[5*pitch+1]), 24.9495, tol); MY_CHECK_SMALL(h_force_4.data[2].x, tol_small); MY_CHECK_CLOSE(h_force_4.data[2].y, 184.573762, tol); MY_CHECK_SMALL(h_force_4.data[2].z, tol_small); MY_CHECK_CLOSE(h_force_4.data[2].w, 6.05171988 + 0.25/2, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_4.data[0*pitch+2] +h_virial_4.data[3*pitch+2] +h_virial_4.data[5*pitch+2]), 24.6098, tol); MY_CHECK_SMALL(h_force_4.data[3].x, tol_small); MY_CHECK_CLOSE(h_force_4.data[3].y, -184.573762, tol); MY_CHECK_SMALL(h_force_4.data[3].z, tol_small); MY_CHECK_CLOSE(h_force_4.data[3].w, 6.05171988 + 0.25/2, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_4.data[0*pitch+3] +h_virial_4.data[3*pitch+3] +h_virial_4.data[5*pitch+3]), 24.6098, tol); MY_CHECK_SMALL(h_force_4.data[4].x, tol_small); MY_CHECK_SMALL(h_force_4.data[4].y, tol_small); MY_CHECK_CLOSE(h_force_4.data[4].z, 186.335166, tol); MY_CHECK_CLOSE(h_force_4.data[4].w, 5.7517282 + 0.25/2, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_4.data[0*pitch+4] +h_virial_4.data[3*pitch+4] +h_virial_4.data[5*pitch+4]), 24.8447, tol); MY_CHECK_SMALL(h_force_4.data[5].x, tol_small); MY_CHECK_SMALL(h_force_4.data[5].y, tol_small); MY_CHECK_CLOSE(h_force_4.data[5].z, -186.335166, tol); MY_CHECK_CLOSE(h_force_4.data[5].w, 5.7517282 + 0.25/2, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_4.data[0*pitch+5] +h_virial_4.data[3*pitch+5] +h_virial_4.data[5*pitch+5]), 24.8447, tol); } // one more test: this one will test two things: // 1) That the forces are computed correctly even if the particles are rearranged in memory // and 2) That two forces can add to the same particle std::shared_ptr<SystemDefinition> sysdef_4(new SystemDefinition(4, BoxDim(100.0, 100.0, 100.0), 1, 1, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_4 = sysdef_4->getParticleData(); pdata_4->setFlags(~PDataFlags(0)); { ArrayHandle<Scalar4> h_pos(pdata_4->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_tag(pdata_4->getTags(), access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_rtag(pdata_4->getRTags(), access_location::host, access_mode::readwrite); // make a square of particles h_pos.data[0].x = 0.0; h_pos.data[0].y = 0.0; h_pos.data[0].z = 0.0; h_pos.data[1].x = 1.0; h_pos.data[1].y = 0; h_pos.data[1].z = 0.0; h_pos.data[2].x = 0; h_pos.data[2].y = 1.0; h_pos.data[2].z = 0.0; h_pos.data[3].x = 1.0; h_pos.data[3].y = 1.0; h_pos.data[3].z = 0.0; h_tag.data[0] = 2; h_tag.data[1] = 3; h_tag.data[2] = 0; h_tag.data[3] = 1; h_rtag.data[h_tag.data[0]] = 0; h_rtag.data[h_tag.data[1]] = 1; h_rtag.data[h_tag.data[2]] = 2; h_rtag.data[h_tag.data[3]] = 3; } // build the bond force compute and try it out std::shared_ptr<PotentialBondFENE> fc_4 = bf_creator(sysdef_4); fc_4->setParams(0, make_scalar4(Scalar(1.5), Scalar(1.75), Scalar(pow(1.2,12.0)), Scalar(pow(1.2,6.0)))); // only add bonds on the left, top, and bottom of the square sysdef_4->getBondData()->addBondedGroup(Bond(0, 2,3)); sysdef_4->getBondData()->addBondedGroup(Bond(0, 2,0)); sysdef_4->getBondData()->addBondedGroup(Bond(0, 0,1)); fc_4->compute(0); { GPUArray<Scalar4>& force_array_5 = fc_4->getForceArray(); GPUArray<Scalar>& virial_array_5 = fc_4->getVirialArray(); unsigned int pitch = virial_array_5.getPitch(); ArrayHandle<Scalar4> h_force_5(force_array_5,access_location::host,access_mode::read); ArrayHandle<Scalar> h_virial_5(virial_array_5,access_location::host,access_mode::read); // the right two particles should only have a force pulling them left MY_CHECK_CLOSE(h_force_5.data[1].x, 86.85002865, tol); MY_CHECK_CLOSE(h_force_5.data[1].y, 0, tol); MY_CHECK_CLOSE(h_force_5.data[1].z, 0, tol); MY_CHECK_CLOSE(h_force_5.data[1].w, 7.08810039/2.0, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_5.data[0*pitch+1] +h_virial_5.data[3*pitch+1] +h_virial_5.data[5*pitch+1]), 14.475, tol); MY_CHECK_CLOSE(h_force_5.data[3].x, 86.85002865, tol); MY_CHECK_CLOSE(h_force_5.data[3].y, 0, tol); MY_CHECK_CLOSE(h_force_5.data[3].z, 0, tol); MY_CHECK_CLOSE(h_force_5.data[3].w, 7.08810039/2.0, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_5.data[0*pitch+3] +h_virial_5.data[3*pitch+3] +h_virial_5.data[5*pitch+3]), 14.475, tol); // the bottom left particle should have a force pulling up and to the right MY_CHECK_CLOSE(h_force_5.data[0].x, -86.850028653, tol); MY_CHECK_CLOSE(h_force_5.data[0].y, -86.85002865, tol); MY_CHECK_CLOSE(h_force_5.data[0].z, 0, tol); MY_CHECK_CLOSE(h_force_5.data[0].w, 7.08810039, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_5.data[0*pitch+0] +h_virial_5.data[3*pitch+0] +h_virial_5.data[5*pitch+0]), 2.0*14.475, tol); // and the top left particle should have a force pulling down and to the right MY_CHECK_CLOSE(h_force_5.data[2].x, -86.85002865, tol); MY_CHECK_CLOSE(h_force_5.data[2].y, 86.85002865, tol); MY_CHECK_CLOSE(h_force_5.data[2].z, 0, tol); MY_CHECK_CLOSE(h_force_5.data[2].w, 7.08810039, tol); MY_CHECK_CLOSE(Scalar(1./3.)*(h_virial_5.data[0*pitch+2] +h_virial_5.data[3*pitch+2] +h_virial_5.data[5*pitch+2]), 2.0*14.475, tol); } } //! Compares the output of two PotentialBondFENEs void bond_force_comparison_tests(bondforce_creator bf_creator1, bondforce_creator bf_creator2, std::shared_ptr<ExecutionConfiguration> exec_conf) { const unsigned int M = 10; const unsigned int N = M*M*M; // create a particle system to sum forces on // use a simple cubic array of particles so that random bonds // don't result in huge forces on a random particle arrangement SimpleCubicInitializer sc_init(M, 1.5, "A"); std::shared_ptr< SnapshotSystemData<Scalar> > snap = sc_init.getSnapshot(); snap->bond_data.type_mapping.push_back("A"); std::shared_ptr<SystemDefinition> sysdef(new SystemDefinition(snap, exec_conf)); std::shared_ptr<ParticleData> pdata = sysdef->getParticleData(); pdata->setFlags(~PDataFlags(0)); std::shared_ptr<PotentialBondFENE> fc1 = bf_creator1(sysdef); std::shared_ptr<PotentialBondFENE> fc2 = bf_creator2(sysdef); fc1->setParams(0, make_scalar4(Scalar(300.0), Scalar(1.6), Scalar(1.0), Scalar(1.0))); fc2->setParams(0, make_scalar4(Scalar(300.0), Scalar(1.6), Scalar(1.0), Scalar(1.0))); // displace particles a little so all forces aren't alike { ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite); BoxDim box = pdata->getBox(); for (unsigned int i = 0; i < N; i++) { h_pos.data[i].x += Scalar((rand())/Scalar(RAND_MAX) - 0.5) * Scalar(0.01); h_pos.data[i].y += Scalar((rand())/Scalar(RAND_MAX) - 0.5) * Scalar(0.05); h_pos.data[i].z += Scalar((rand())/Scalar(RAND_MAX) - 0.5) * Scalar(0.001); int3 img; box.wrap(h_pos.data[i], img); } } // add bonds for (unsigned int i = 0; i < M; i++) for (unsigned int j = 0; j < M; j++) for (unsigned int k = 0; k < M-1; k++) { sysdef->getBondData()->addBondedGroup(Bond(0, i*M*M + j*M + k, i*M*M + j*M + k + 1)); } // compute the forces fc1->compute(0); fc2->compute(0); { // verify that the forces are identical (within roundoff errors) GPUArray<Scalar4>& force_array_6 = fc1->getForceArray(); GPUArray<Scalar>& virial_array_6 = fc1->getVirialArray(); unsigned int pitch = virial_array_6.getPitch(); ArrayHandle<Scalar4> h_force_6(force_array_6,access_location::host,access_mode::read); ArrayHandle<Scalar> h_virial_6(virial_array_6,access_location::host,access_mode::read); GPUArray<Scalar4>& force_array_7 = fc2->getForceArray(); GPUArray<Scalar>& virial_array_7 = fc2->getVirialArray(); ArrayHandle<Scalar4> h_force_7(force_array_7,access_location::host,access_mode::read); ArrayHandle<Scalar> h_virial_7(virial_array_7,access_location::host,access_mode::read); // compare average deviation between the two computes double deltaf2 = 0.0; double deltape2 = 0.0; double deltav2[6]; for (unsigned int i = 0; i < 6; i++) deltav2[i] = 0.0; for (unsigned int i = 0; i < N; i++) { deltaf2 += double(h_force_7.data[i].x - h_force_6.data[i].x) * double(h_force_7.data[i].x - h_force_6.data[i].x); deltaf2 += double(h_force_7.data[i].y - h_force_6.data[i].y) * double(h_force_7.data[i].y - h_force_6.data[i].y); deltaf2 += double(h_force_7.data[i].z - h_force_6.data[i].z) * double(h_force_7.data[i].z - h_force_6.data[i].z); deltape2 += double(h_force_7.data[i].w - h_force_6.data[i].w) * double(h_force_7.data[i].w - h_force_6.data[i].w); for (unsigned int j = 0; j < 6; j++) deltav2[j] += double(h_virial_7.data[j*pitch+i] - h_virial_6.data[j*pitch+i]) * double(h_virial_7.data[j*pitch+i] - h_virial_6.data[j*pitch+i]); // also check that each individual calculation is somewhat close } deltaf2 /= double(pdata->getN()); deltape2 /= double(pdata->getN()); for (unsigned int i = 0; i < 6; i++) deltav2[i] /= double(pdata->getN()); CHECK_SMALL(deltaf2, double(tol_small)); CHECK_SMALL(deltape2, double(tol_small)); CHECK_SMALL(deltav2[0], double(tol_small)); CHECK_SMALL(deltav2[1], double(tol_small)); CHECK_SMALL(deltav2[2], double(tol_small)); CHECK_SMALL(deltav2[3], double(tol_small)); CHECK_SMALL(deltav2[4], double(tol_small)); CHECK_SMALL(deltav2[5], double(tol_small)); } } //! PotentialBondFENE creator for bond_force_basic_tests() std::shared_ptr<PotentialBondFENE> base_class_bf_creator(std::shared_ptr<SystemDefinition> sysdef) { return std::shared_ptr<PotentialBondFENE>(new PotentialBondFENE(sysdef)); } #ifdef ENABLE_CUDA //! PotentialBondFENE creator for bond_force_basic_tests() std::shared_ptr<PotentialBondFENE> gpu_bf_creator(std::shared_ptr<SystemDefinition> sysdef) { return std::shared_ptr<PotentialBondFENE>(new PotentialBondFENEGPU(sysdef)); } #endif //! test case for bond forces on the CPU UP_TEST( PotentialBondFENE_basic ) { bondforce_creator bf_creator = bind(base_class_bf_creator, _1); bond_force_basic_tests(bf_creator, std::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::CPU))); } #ifdef ENABLE_CUDA //! test case for bond forces on the GPU UP_TEST( PotentialBondFENEGPU_basic ) { bondforce_creator bf_creator = bind(gpu_bf_creator, _1); bond_force_basic_tests(bf_creator, std::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! test case for comparing bond GPU and CPU BondForceComputes UP_TEST( PotentialBondFENEGPU_compare ) { bondforce_creator bf_creator_gpu = bind(gpu_bf_creator, _1); bondforce_creator bf_creator = bind(base_class_bf_creator, _1); bond_force_comparison_tests(bf_creator, bf_creator_gpu, std::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::GPU))); } #endif
20,441
8,801
// // list_multi_map.cpp // OpenPGP // // Created by Yanfeng Zhang on 1/19/17. // // The MIT License // // Copyright (c) 2019 Proton Technologies AG // // 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 "list_multi_map.hpp" // // //public class ListMultimap<K, V> implements Iterable<Map.Entry<K, List<V>>> { // private final Map<K, List<V>> map; // // /** // * Creates an empty multimap. // */ // public ListMultimap() { // this(new LinkedHashMap<K, List<V>>()); // } // // /** // * Creates an empty multimap. // * @param initialCapacity the initial capacity of the underlying map. // */ // public ListMultimap(int initialCapacity) { // this(new LinkedHashMap<K, List<V>>(initialCapacity)); // } // // /** // * Creates a copy of an existing multimap. // * @param orig the multimap to copy from // */ // public ListMultimap(ListMultimap<K, V> orig) { // this(copy(orig.map)); // } // // private static <K, V> Map<K, List<V>> copy(Map<K, List<V>> orig) { // Map<K, List<V>> map = new LinkedHashMap<K, List<V>>(orig.size()); // for (Map.Entry<K, List<V>> entry : orig.entrySet()) { // List<V> values = new ArrayList<V>(entry.getValue()); // map.put(entry.getKey(), values); // } // return map; // } // // /** // * <p> // * Creates a new multimap backed by the given map. Changes made to the given // * map will effect the multimap and vice versa. // * </p> // * <p> // * To avoid problems, it is highly recommended that the given map NOT be // * modified by anything other than this {@link ListMultimap} class after // * being passed into this constructor. // * </p> // * @param map the backing map // */ // public ListMultimap(Map<K, List<V>> map) { // this.map = map; // } // // /** // * Adds a value to the multimap. // * @param key the key // * @param value the value to add // */ // public void put(K key, V value) { // key = sanitizeKey(key); // List<V> list = map.get(key); // if (list == null) { // list = new ArrayList<V>(); // map.put(key, list); // } // list.add(value); // } // // /** // * Adds multiple values to the multimap. // * @param key the key // * @param values the values to add // */ // public void putAll(K key, Collection<V> values) { // if (values.isEmpty()) { // return; // } // // key = sanitizeKey(key); // List<V> list = map.get(key); // if (list == null) { // list = new ArrayList<V>(); // map.put(key, list); // } // list.addAll(values); // } // // /** // * Gets the values associated with the key. Changes to the returned list // * will update the underlying multimap, and vice versa. // * @param key the key // * @return the list of values or empty list if the key doesn't exist // */ // public List<V> get(K key) { // key = sanitizeKey(key); // List<V> value = map.get(key); // if (value == null) { // value = new ArrayList<V>(0); // } // return new WrappedList(key, value, null); // } // // /** // * Gets the first value that's associated with a key. // * @param key the key // * @return the first value or null if the key doesn't exist // */ // public V first(K key) { // key = sanitizeKey(key); // List<V> values = map.get(key); // // /* // * The list can be null, but never empty. Empty lists are removed from // * the map. // */ // return (values == null) ? null : values.get(0); // } // // /** // * Determines whether the given key exists. // * @param key the key // * @return true if the key exists, false if not // */ // public boolean containsKey(K key) { // key = sanitizeKey(key); // return map.containsKey(key); // } // // /** // * Removes a particular value. // * @param key the key // * @param value the value to remove // * @return true if the multimap contained the value, false if not // */ // public boolean remove(K key, V value) { // key = sanitizeKey(key); // List<V> values = map.get(key); // if (values == null) { // return false; // } // // boolean success = values.remove(value); // if (values.isEmpty()) { // map.remove(key); // } // return success; // } // // /** // * Removes all the values associated with a key // * @param key the key to remove // * @return the removed values or an empty list if the key doesn't exist // * (this list is immutable) // */ // public List<V> removeAll(K key) { // key = sanitizeKey(key); // List<V> removed = map.remove(key); // if (removed == null) { // return Collections.emptyList(); // } // // List<V> unmodifiableCopy = Collections.unmodifiableList(new ArrayList<V>(removed)); // removed.clear(); // return unmodifiableCopy; // } // // /** // * Replaces all values with the given value. // * @param key the key // * @param value the value with which to replace all existing values, or null // * to remove all values // * @return the values that were replaced (this list is immutable) // */ // public List<V> replace(K key, V value) { // List<V> replaced = removeAll(key); // if (value != null) { // put(key, value); // } // return replaced; // } // // /** // * Replaces all values with the given values. // * @param key the key // * @param values the values with which to replace all existing values // * @return the values that were replaced (this list is immutable) // */ // public List<V> replace(K key, Collection<V> values) { // List<V> replaced = removeAll(key); // putAll(key, values); // return replaced; // } // // /** // * Clears all entries from the multimap. // */ // public void clear() { // //clear each collection to make previously returned lists empty // for (List<V> value : map.values()) { // value.clear(); // } // map.clear(); // } // // /** // * Gets all the keys in the multimap. // * @return the keys (this set is immutable) // */ // public Set<K> keySet() { // return Collections.unmodifiableSet(map.keySet()); // } // // /** // * Gets all the values in the multimap. // * @return the values (this list is immutable) // */ // public List<V> values() { // List<V> list = new ArrayList<V>(); // for (List<V> value : map.values()) { // list.addAll(value); // } // return Collections.unmodifiableList(list); // } // // /** // * Determines if the multimap is empty or not. // * @return true if it's empty, false if not // */ // public boolean isEmpty() { // return size() == 0; // } // // /** // * Gets the number of values in the map. // * @return the number of values // */ // public int size() { // int size = 0; // for (List<V> value : map.values()) { // size += value.size(); // } // return size; // } // // /** // * Gets an immutable view of the underlying {@link Map} object. // * @return an immutable map // */ // public Map<K, List<V>> asMap() { // Map<K, List<V>> view = new LinkedHashMap<K, List<V>>(map.size()); // for (Map.Entry<K, List<V>> entry : map.entrySet()) { // K key = entry.getKey(); // List<V> value = entry.getValue(); // view.put(key, Collections.unmodifiableList(value)); // } // return Collections.unmodifiableMap(view); // } // // /** // * Gets the {@link Map} that backs this multimap. This method is here for // * performances reasons. The returned map should NOT be modified by anything // * other than the {@link ListMultimap} object that owns it. // * @return the map // */ // public Map<K, List<V>> getMap() { // return map; // } // // /** // * Modifies a given key before it is used to interact with the internal map. // * This method is meant to be overridden by child classes if necessary. // * @param key the key // * @return the modified key (by default, the key is returned as-is) // */ // protected K sanitizeKey(K key) { // return key; // } // // /** // * Gets an iterator for iterating over the entries in the map. This iterator // * iterates over an immutable view of the map. // * @return the iterator // */ // //@Override // public Iterator<Map.Entry<K, List<V>>> iterator() { // final Iterator<Map.Entry<K, List<V>>> it = map.entrySet().iterator(); // return new Iterator<Map.Entry<K, List<V>>>() { // public boolean hasNext() { // return it.hasNext(); // } // // public Entry<K, List<V>> next() { // final Entry<K, List<V>> next = it.next(); // return new Entry<K, List<V>>() { // public K getKey() { // return next.getKey(); // } // // public List<V> getValue() { // return Collections.unmodifiableList(next.getValue()); // } // // public List<V> setValue(List<V> value) { // throw new UnsupportedOperationException(); // } // }; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // }; // } // // @Override // public String toString() { // return map.toString(); // } // // @Override // public int hashCode() { // return map.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // // ListMultimap<?, ?> other = (ListMultimap<?, ?>) obj; // return map.equals(other.map); // } // // /** // * Note: This class is a modified version of the // * "AbstractMapBasedMultimap.WrappedList" class from the <a // * href="https://github.com/google/guava">Guava</a> library. // * // * <p> // * Collection decorator that stays in sync with the multimap values for a // * key. There are two kinds of wrapped collections: full and subcollections. // * Both have a delegate pointing to the underlying collection class. // * // * <p> // * Full collections, identified by a null ancestor field, contain all // * multimap values for a given key. Its delegate is a value in the // * multimap's underlying {@link Map} whenever the delegate is non-empty. The // * {@code refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} // * methods ensure that the {@code WrappedList} and map remain consistent. // * // * <p> // * A subcollection, such as a sublist, contains some of the values for a // * given key. Its ancestor field points to the full wrapped collection with // * all values for the key. The subcollection {@code refreshIfEmpty}, // * {@code removeIfEmpty}, and {@code addToMap} methods call the // * corresponding methods of the full wrapped collection. // */ // private class WrappedList extends AbstractCollection<V> implements List<V> { // final K key; // List<V> delegate; // final WrappedList ancestor; // final List<V> ancestorDelegate; // // WrappedList(K key, List<V> delegate, WrappedList ancestor) { // this.key = key; // this.delegate = delegate; // this.ancestor = ancestor; // this.ancestorDelegate = (ancestor == null) ? null : ancestor.getDelegate(); // } // // public boolean addAll(int index, Collection<? extends V> collection) { // if (collection.isEmpty()) { // return false; // } // int oldSize = size(); // calls refreshIfEmpty // boolean changed = getDelegate().addAll(index, collection); // if (changed && oldSize == 0) { // addToMap(); // } // return changed; // } // // public V get(int index) { // refreshIfEmpty(); // return getDelegate().get(index); // } // // public V set(int index, V element) { // refreshIfEmpty(); // return getDelegate().set(index, element); // } // // public void add(int index, V element) { // refreshIfEmpty(); // boolean wasEmpty = getDelegate().isEmpty(); // getDelegate().add(index, element); // if (wasEmpty) { // addToMap(); // } // } // // public V remove(int index) { // refreshIfEmpty(); // V value = getDelegate().remove(index); // removeIfEmpty(); // return value; // } // // public int indexOf(Object o) { // refreshIfEmpty(); // return getDelegate().indexOf(o); // } // // public int lastIndexOf(Object o) { // refreshIfEmpty(); // return getDelegate().lastIndexOf(o); // } // // public ListIterator<V> listIterator() { // refreshIfEmpty(); // return new WrappedListIterator(); // } // // public ListIterator<V> listIterator(int index) { // refreshIfEmpty(); // return new WrappedListIterator(index); // } // // public List<V> subList(int fromIndex, int toIndex) { // refreshIfEmpty(); // return new WrappedList(getKey(), getDelegate().subList(fromIndex, toIndex), (getAncestor() == null) ? this : getAncestor()); // } // // /** // * If the delegate collection is empty, but the multimap has values for // * the key, replace the delegate with the new collection for the key. // * // * <p> // * For a subcollection, refresh its ancestor and validate that the // * ancestor delegate hasn't changed. // */ // void refreshIfEmpty() { // if (ancestor != null) { // ancestor.refreshIfEmpty(); // if (ancestor.getDelegate() != ancestorDelegate) { // throw new ConcurrentModificationException(); // } // } else if (delegate.isEmpty()) { // List<V> newDelegate = map.get(key); // if (newDelegate != null) { // delegate = newDelegate; // } // } // } // // /** // * If collection is empty, remove it from // * {@code AbstractMapBasedMultimap.this.map}. For subcollections, check // * whether the ancestor collection is empty. // */ // void removeIfEmpty() { // if (ancestor != null) { // ancestor.removeIfEmpty(); // } else if (delegate.isEmpty()) { // map.remove(key); // } // } // // K getKey() { // return key; // } // // /** // * Add the delegate to the map. Other {@code WrappedCollection} methods // * should call this method after adding elements to a previously empty // * collection. // * // * <p> // * Subcollection add the ancestor's delegate instead. // */ // void addToMap() { // if (ancestor != null) { // ancestor.addToMap(); // } else { // map.put(key, delegate); // } // } // // @Override // public int size() { // refreshIfEmpty(); // return delegate.size(); // } // // @Override // public boolean equals(Object object) { // if (object == this) { // return true; // } // refreshIfEmpty(); // return delegate.equals(object); // } // // @Override // public int hashCode() { // refreshIfEmpty(); // return delegate.hashCode(); // } // // @Override // public String toString() { // refreshIfEmpty(); // return delegate.toString(); // } // // List<V> getDelegate() { // return delegate; // } // // @Override // public Iterator<V> iterator() { // refreshIfEmpty(); // return new WrappedListIterator(); // } // // @Override // public boolean add(V value) { // refreshIfEmpty(); // boolean wasEmpty = delegate.isEmpty(); // boolean changed = delegate.add(value); // if (changed && wasEmpty) { // addToMap(); // } // return changed; // } // // WrappedList getAncestor() { // return ancestor; // } // // // The following methods are provided for better performance. // // @Override // public boolean addAll(Collection<? extends V> collection) { // if (collection.isEmpty()) { // return false; // } // int oldSize = size(); // calls refreshIfEmpty // boolean changed = delegate.addAll(collection); // if (changed && oldSize == 0) { // addToMap(); // } // return changed; // } // // @Override // public boolean contains(Object o) { // refreshIfEmpty(); // return delegate.contains(o); // } // // @Override // public boolean containsAll(Collection<?> c) { // refreshIfEmpty(); // return delegate.containsAll(c); // } // // @Override // public void clear() { // int oldSize = size(); // calls refreshIfEmpty // if (oldSize == 0) { // return; // } // delegate.clear(); // removeIfEmpty(); // maybe shouldn't be removed if this is a sublist // } // // @Override // public boolean remove(Object o) { // refreshIfEmpty(); // boolean changed = delegate.remove(o); // if (changed) { // removeIfEmpty(); // } // return changed; // } // // @Override // public boolean removeAll(Collection<?> collection) { // if (collection.isEmpty()) { // return false; // } // refreshIfEmpty(); // boolean changed = delegate.removeAll(collection); // if (changed) { // removeIfEmpty(); // } // return changed; // } // // @Override // public boolean retainAll(Collection<?> c) { // refreshIfEmpty(); // boolean changed = delegate.retainAll(c); // if (changed) { // removeIfEmpty(); // } // return changed; // } // // /** ListIterator decorator. */ // private class WrappedListIterator implements ListIterator<V> { // final ListIterator<V> delegateIterator; // final List<V> originalDelegate = delegate; // // WrappedListIterator() { // delegateIterator = delegate.listIterator(); // } // // public WrappedListIterator(int index) { // delegateIterator = delegate.listIterator(index); // } // // public boolean hasPrevious() { // return getDelegateIterator().hasPrevious(); // } // // public V previous() { // return getDelegateIterator().previous(); // } // // public int nextIndex() { // return getDelegateIterator().nextIndex(); // } // // public int previousIndex() { // return getDelegateIterator().previousIndex(); // } // // public void set(V value) { // getDelegateIterator().set(value); // } // // public void add(V value) { // boolean wasEmpty = isEmpty(); // getDelegateIterator().add(value); // if (wasEmpty) { // addToMap(); // } // } // // /** // * If the delegate changed since the iterator was created, the // * iterator is no longer valid. // */ // void validateIterator() { // refreshIfEmpty(); // if (delegate != originalDelegate) { // throw new ConcurrentModificationException(); // } // } // // public boolean hasNext() { // validateIterator(); // return delegateIterator.hasNext(); // } // // public V next() { // validateIterator(); // return delegateIterator.next(); // } // // public void remove() { // delegateIterator.remove(); // removeIfEmpty(); // } // // ListIterator<V> getDelegateIterator() { // validateIterator(); // return delegateIterator; // } // } // } //}
23,567
6,554
// // Created by Eben on 05/06/2019. // #include <utility> #include "IrrEntity.hpp" #include <sys/stat.h> #include <string> #include <fstream> inline bool check_file_exists (const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } Irrlicht::IrrEntity::IrrEntity( const std::string &filename, unsigned id, irr::scene::ISceneManager *smgr, irr::video::IVideoDriver *driver, irr::video::SColor defaultColor ) : id(id), anim(Animations::IDLE), _meshPath("./media/models/" + filename + ".md2"), _defaultColor(defaultColor), _texturePath("./media/textures/" + filename + ".png"), _loaded(false), _smgr(smgr), _mesh(nullptr), _node(nullptr), _parent(nullptr) { if (check_file_exists(this->_meshPath)) this->_mesh = smgr->getMesh(this->_meshPath.c_str()); if (!this->_mesh) { this->_meshPath = "./media/models/" + filename + ".dae"; this->_mesh = smgr->getMesh(this->_meshPath.c_str()); if (!this->_mesh) { std::cerr << "Failed to load ./media/models/" << filename << ".md2" << std::endl; std::cerr << "Failed to load ./media/models/" << filename << ".dae" <<std::endl; return; } } this->_node = smgr->addAnimatedMeshSceneNode(this->_mesh); if (this->_node) { this->_node->setMaterialFlag(irr::video::EMF_LIGHTING, false); this->_texture = driver->getTexture(this->_texturePath.c_str()); if (!this->_texture) std::cerr << "Cannot load file " << this->_texturePath << std::endl; this->_node->setMaterialTexture(0, this->_texture); this->_node->setScale(irr::core::vector3df(4, 4, 4)); this->_node->setMD2Animation(static_cast<irr::scene::EMD2_ANIMATION_TYPE>(this->anim)); this->_loaded = true; } } Irrlicht::IrrEntity::~IrrEntity() { if (this->_node && this->_smgr) this->_smgr->addToDeletionQueue(this->_node); } bool Irrlicht::IrrEntity::isEntityLoaded() { return this->_loaded; } void Irrlicht::IrrEntity::setPos(float x, float z) { if (this->_node && (this->_pos.x != x || this->_pos.y != z)) { this->_pos = {x, z}; x = x + this->_size.x / 2; z = z - this->_size.y / 2; this->_node->setPosition(irr::core::vector3df(x, 0, z)); } } void Irrlicht::IrrEntity::setScale(float x, float z, float y) { if (this->_node && (this->_scale.x != x || this->_scale.y != z)) { irr::core::vector3d<irr::f32> factorEscalate( x, y < 0 ? (z > x ? x : z) : 1, z ); this->_node->setScale(factorEscalate); } } ECS::Vector2<float> Irrlicht::IrrEntity::getSize() { irr::core::aabbox3d<float> bounding_box = this->_node->getBoundingBox(); return ECS::Vector2<float>{bounding_box.MaxEdge.X - bounding_box.MinEdge.X, bounding_box.MaxEdge.Z - bounding_box.MinEdge.Z}; } void Irrlicht::IrrEntity::setSize(float x, float z) { if (this->_node && (this->_size.x != x || this->_size.y != z)) { irr::f32 width; irr::f32 depth; if (_size.x == -1 && _size.y == -1) { auto *edges = new irr::core::vector3d<irr::f32>[8]; irr::core::aabbox3d<irr::f32> boundingbox = this->_node->getBoundingBox(); boundingbox.getEdges(edges); width = edges[5].X - edges[1].X; depth = edges[2].Z - edges[0].Z; } else { width = _size.x; depth = _size.y; } irr::f32 factorX = x / width; irr::f32 factorZ = z / depth; irr::core::vector3d<irr::f32> factorEscalate( factorX, factorZ > factorX ? factorX : factorZ, factorZ ); this->_size = {x, z}; this->_scale = {factorX, factorZ}; this->_node->setScale(factorEscalate); } } void Irrlicht::IrrEntity::setRotation(float angleY) { irr::core::vector3df rotY; irr::core::quaternion quaternionY; quaternionY.fromAngleAxis(angleY, irr::core::vector3df(0, 1, 0)); quaternionY.normalize(); quaternionY.toEuler(rotY); if (this->_node) this->_node->setRotation(rotY * irr::core::RADTODEG); } void Irrlicht::IrrEntity::setAnimation(Irrlicht::Animations animation) { if (this->anim == animation) return; this->anim = animation; if (this->_node) this->_node->setMD2Animation(static_cast<irr::scene::EMD2_ANIMATION_TYPE>(this->anim)); }
4,593
1,651
#pragma once #include <protozero/pbf_writer.hpp> #include <protozero/pbf_reader.hpp> #define RAPIDJSON_HAS_STDSTRING 1 #include <rapidjson/writer.h> #include <rapidjson/stringbuffer.h> #include "rapidjson/document.h" #include <osmium/osm/types.hpp> namespace osmwayback { /* PBF Object Encoding =================== These functions encode osmium objects into simplified PBF messages to store in rocksdb Message Keys for Encoding: 1. Timestamp 2. Chnageset 3. version 4. User ID 5. User (String) 6. Visible (bool) 7. Deleted (bool) 10: Tags */ const std::string encode_node(const osmium::Node& node) { std::string data; protozero::pbf_writer encoder(data); encoder.add_fixed64(1, static_cast<int>(node.timestamp().seconds_since_epoch())); encoder.add_uint32(2, node.changeset()); encoder.add_uint32(3, node.version()); encoder.add_uint32(4, node.uid()); encoder.add_string(5, node.user()); encoder.add_bool(6, node.visible()); encoder.add_bool(7, node.deleted()); //Add node coordinates //If deleted, will always throw invalid location exception if( !node.deleted() ){ try{ encoder.add_double(8, node.location().lon()); encoder.add_double(9, node.location().lat()); } catch (const osmium::invalid_location& ex) { //Catch invlid locations, not sure why this would happen... but it could //std::cerr<< ex.what() << std::endl; } } //Add the tags const osmium::TagList& tags = node.tags(); for (const osmium::Tag& tag : tags) { encoder.add_string(10, tag.key()); encoder.add_string(10, tag.value()); } return data; } const std::string encode_way(const osmium::Way& way) { std::string data; protozero::pbf_writer encoder(data); encoder.add_fixed64(1, static_cast<int>(way.timestamp().seconds_since_epoch())); encoder.add_uint32(2, way.changeset()); encoder.add_uint32(3, way.version()); encoder.add_uint32(4, way.uid()); encoder.add_string(5, way.user()); encoder.add_bool(6, way.visible()); encoder.add_bool(7, way.deleted()); //Add node references: TODO: Optimize std::vector<int64_t> noderefs; for (const osmium::NodeRef& nr : way.nodes()) { noderefs.push_back(nr.ref()); } encoder.add_packed_int64(8, noderefs.begin(), noderefs.end()); //Add the tags const osmium::TagList& tags = way.tags(); for (const osmium::Tag& tag : tags) { encoder.add_string(10, tag.key()); encoder.add_string(10, tag.value()); } return data; } /* PBF Object Decoding =================== These functions decode PBF messages from rocksdb INTO json objects //To save space within GeoJSON objects, historical attribute names are shorted; these can be expanded later in a per-tile basis, the entire history object is String Encoded, so it's best to keep it short. @timestamp = t; @changeset = c; @uid = u; (user ID) @user = h; (handle) @version = i; (iteration) @visible = v; @deleted = d; tags = a; //attributes aA = attributes added; aM = attributes modified; aD = attributes deleted; //Object specific attributes: coordinates = p //p for point (only point geoms here) nodes = n; */ // Decode PBF_Node as JSON Object (in place (?) ) void decode_node(std::string data, rapidjson::Document* doc) { protozero::pbf_reader message(data); //Initialize the object (object is defined in add_tags) doc->SetObject(); rapidjson::Document::AllocatorType& a = doc->GetAllocator(); std::string previous_key{}; rapidjson::Value object_tags(rapidjson::kObjectType); rapidjson::Value coordinates(rapidjson::kArrayType); bool deleted; while (message.next()) { switch (message.tag()) { case 1: doc->AddMember("t", message.get_fixed64(), a); break; case 2: doc->AddMember("c", message.get_uint32(), a); break; case 3: doc->AddMember("i", message.get_uint32(), a); break; case 4: doc->AddMember("u", message.get_uint32(), a); break; case 5: doc->AddMember("h", message.get_string(), a); break; case 6: message.get_bool(); // doc->AddMember("v", message.get_bool(), a); break; case 7: deleted = message.get_bool(); if (deleted){ doc->AddMember("d", deleted, a); } break; case 8: coordinates.PushBack(message.get_double(),a); break; case 9: coordinates.PushBack(message.get_double(),a); break; case 10: //Tags if (previous_key.empty()) { previous_key = message.get_string(); } else { rapidjson::Value key(previous_key.c_str(), a); rapidjson::Value value(message.get_string(), a); object_tags.AddMember(key, value, a); previous_key = ""; } break; default: message.skip(); } } if (!coordinates.ObjectEmpty() ){ doc->AddMember("p",coordinates,a); } if ( !object_tags.ObjectEmpty() ){ doc->AddMember("a",object_tags, a); } } // Decode PBF Way as JSON Object (in place (?) ) void decode_way(std::string data, rapidjson::Document* doc) { protozero::pbf_reader message(data); //Initialize the object (object is defined in add_tags) doc->SetObject(); rapidjson::Document::AllocatorType& a = doc->GetAllocator(); rapidjson::Value noderefs(rapidjson::kArrayType); std::string previous_key{}; rapidjson::Value object_tags(rapidjson::kObjectType); protozero::iterator_range<protozero::pbf_reader::const_int64_iterator> nodeIDs; bool deleted; while (message.next()) { switch (message.tag()) { case 1: doc->AddMember("t", message.get_fixed64(), a); break; case 2: doc->AddMember("c", message.get_uint32(), a); break; case 3: doc->AddMember("i", message.get_uint32(), a); break; case 4: doc->AddMember("u", message.get_uint32(), a); break; case 5: doc->AddMember("h", message.get_string(), a); break; case 6: message.get_bool(); // doc->AddMember("v", message.get_bool(), a); break; case 7: deleted = message.get_bool(); if (deleted){ doc->AddMember("d", deleted, a); } break; case 8: //Node refs nodeIDs = message.get_packed_int64(); for (auto nr : nodeIDs) { noderefs.PushBack(nr,a); } break; case 10: //Tags if (previous_key.empty()) { previous_key = message.get_string(); } else { rapidjson::Value key(previous_key.c_str(), a); rapidjson::Value value(message.get_string(), a); object_tags.AddMember(key, value, a); previous_key = ""; } break; default: message.skip(); } } if ( !noderefs.ObjectEmpty() ){ doc->AddMember("n",noderefs, a); } if ( !object_tags.ObjectEmpty() ){ doc->AddMember("a",object_tags, a); } } }
8,816
2,526
// LzfseDecoder.cpp /* This code implements LZFSE data decompressing. The code from "LZFSE compression library" was used. 2018 : Igor Pavlov : BSD 3-clause License : the code in this file 2015-2017 : Apple Inc : BSD 3-clause License : original "LZFSE compression library" code The code in the "LZFSE compression library" is licensed under the "BSD 3-clause License": ---- Copyright (c) 2015-2016, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any 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 "StdAfx.h" // #define SHOW_DEBUG_INFO #ifdef SHOW_DEBUG_INFO #include <stdio.h> #endif #ifdef SHOW_DEBUG_INFO #define PRF(x) x #else #define PRF(x) #endif #include "../../../C/CpuArch.h" #include "LzfseDecoder.h" namespace NCompress { namespace NLzfse { static const Byte kSignature_LZFSE_V1 = 0x31; // '1' static const Byte kSignature_LZFSE_V2 = 0x32; // '2' HRESULT CDecoder::GetUInt32(UInt32 &val) { Byte b[4]; for (unsigned i = 0; i < 4; i++) if (!m_InStream.ReadByte(b[i])) return S_FALSE; val = GetUi32(b); return S_OK; } HRESULT CDecoder::DecodeUncompressed(UInt32 unpackSize) { PRF(printf("\nUncompressed %7u\n", unpackSize)); const unsigned kBufSize = 1 << 8; Byte buf[kBufSize]; for (;;) { if (unpackSize == 0) return S_OK; UInt32 cur = unpackSize; if (cur > kBufSize) cur = kBufSize; UInt32 cur2 = (UInt32)m_InStream.ReadBytes(buf, cur); m_OutWindowStream.PutBytes(buf, cur2); if (cur != cur2) return S_FALSE; } } HRESULT CDecoder::DecodeLzvn(UInt32 unpackSize) { UInt32 packSize; RINOK(GetUInt32(packSize)); PRF(printf("\nLZVN %7u %7u", unpackSize, packSize)); UInt32 D = 0; for (;;) { if (packSize == 0) return S_FALSE; Byte b; if (!m_InStream.ReadByte(b)) return S_FALSE; packSize--; UInt32 M; UInt32 L; if (b >= 0xE0) { /* large L - 11100000 LLLLLLLL <LITERALS> small L - 1110LLLL <LITERALS> large Rep - 11110000 MMMMMMMM small Rep - 1111MMMM */ M = b & 0xF; if (M == 0) { if (packSize == 0) return S_FALSE; Byte b1; if (!m_InStream.ReadByte(b1)) return S_FALSE; packSize--; M = (UInt32)b1 + 16; } L = 0; if ((b & 0x10) == 0) { // Literals only L = M; M = 0; } } // ERROR codes else if ((b & 0xF0) == 0x70) // 0111xxxx return S_FALSE; else if ((b & 0xF0) == 0xD0) // 1101xxxx return S_FALSE; else { if ((b & 0xE0) == 0xA0) { // medium - 101LLMMM DDDDDDMM DDDDDDDD <LITERALS> if (packSize < 2) return S_FALSE; Byte b1; if (!m_InStream.ReadByte(b1)) return S_FALSE; packSize--; Byte b2; if (!m_InStream.ReadByte(b2)) return S_FALSE; packSize--; L = (((UInt32)b >> 3) & 3); M = (((UInt32)b & 7) << 2) + (b1 & 3); D = ((UInt32)b1 >> 2) + ((UInt32)b2 << 6); } else { L = (UInt32)b >> 6; M = ((UInt32)b >> 3) & 7; if ((b & 0x7) == 6) { // REP - LLMMM110 <LITERALS> if (L == 0) { // spec if (M == 0) break; // EOS if (M <= 2) continue; // NOP return S_FALSE; // UNDEFINED } } else { if (packSize == 0) return S_FALSE; Byte b1; if (!m_InStream.ReadByte(b1)) return S_FALSE; packSize--; // large - LLMMM111 DDDDDDDD DDDDDDDD <LITERALS> // small - LLMMMDDD DDDDDDDD <LITERALS> D = ((UInt32)b & 7); if (D == 7) { if (packSize == 0) return S_FALSE; Byte b2; if (!m_InStream.ReadByte(b2)) return S_FALSE; packSize--; D = b2; } D = (D << 8) + b1; } } M += 3; } { for (unsigned i = 0; i < L; i++) { if (packSize == 0 || unpackSize == 0) return S_FALSE; Byte b1; if (!m_InStream.ReadByte(b1)) return S_FALSE; packSize--; m_OutWindowStream.PutByte(b1); unpackSize--; } } if (M != 0) { if (unpackSize == 0 || D == 0) return S_FALSE; unsigned cur = M; if (cur > unpackSize) cur = (unsigned)unpackSize; if (!m_OutWindowStream.CopyBlock(D - 1, cur)) return S_FALSE; unpackSize -= cur; if (cur != M) return S_FALSE; } } if (unpackSize != 0) return S_FALSE; // LZVN encoder writes 7 additional zero bytes if (packSize != 7) return S_FALSE; do { Byte b; if (!m_InStream.ReadByte(b)) return S_FALSE; packSize--; if (b != 0) return S_FALSE; } while (packSize != 0); return S_OK; } // ---------- LZFSE ---------- #define MATCHES_PER_BLOCK 10000 #define LITERALS_PER_BLOCK (4 * MATCHES_PER_BLOCK) #define NUM_L_SYMBOLS 20 #define NUM_M_SYMBOLS 20 #define NUM_D_SYMBOLS 64 #define NUM_LIT_SYMBOLS 256 #define NUM_SYMBOLS ( \ NUM_L_SYMBOLS + \ NUM_M_SYMBOLS + \ NUM_D_SYMBOLS + \ NUM_LIT_SYMBOLS) #define NUM_L_STATES (1 << 6) #define NUM_M_STATES (1 << 6) #define NUM_D_STATES (1 << 8) #define NUM_LIT_STATES (1 << 10) typedef UInt32 CFseState; static UInt32 SumFreqs(const UInt16 *freqs, unsigned num) { UInt32 sum = 0; for (unsigned i = 0; i < num; i++) sum += (UInt32)freqs[i]; return sum; } static MY_FORCE_INLINE unsigned CountZeroBits(UInt32 val, UInt32 mask) { for (unsigned i = 0;;) { if (val & mask) return i; i++; mask >>= 1; } } static MY_FORCE_INLINE void InitLitTable(const UInt16 *freqs, UInt32 *table) { for (unsigned i = 0; i < NUM_LIT_SYMBOLS; i++) { unsigned f = freqs[i]; if (f == 0) continue; // 0 < f <= numStates // 0 <= k <= numStatesLog // numStates <= (f<<k) < numStates * 2 // 0 < j0 <= f // (f + j0) = next_power_of_2 for f unsigned k = CountZeroBits(f, NUM_LIT_STATES); unsigned j0 = (((unsigned)NUM_LIT_STATES * 2) >> k) - f; /* CEntry { Byte k; Byte symbol; UInt16 delta; }; */ UInt32 e = ((UInt32)i << 8) + k; k += 16; UInt32 d = e + ((UInt32)f << k) - ((UInt32)NUM_LIT_STATES << 16); UInt32 step = (UInt32)1 << k; unsigned j = 0; do { *table++ = d; d += step; } while (++j < j0); e--; step >>= 1; for (j = j0; j < f; j++) { *table++ = e; e += step; } } } typedef struct { Byte totalBits; Byte extraBits; UInt16 delta; UInt32 vbase; } CExtraEntry; static void InitExtraDecoderTable(unsigned numStates, unsigned numSymbols, const UInt16 *freqs, const Byte *vbits, CExtraEntry *table) { UInt32 vbase = 0; for (unsigned i = 0; i < numSymbols; i++) { unsigned f = freqs[i]; unsigned extraBits = vbits[i]; if (f != 0) { unsigned k = CountZeroBits(f, numStates); unsigned j0 = ((2 * numStates) >> k) - f; unsigned j = 0; do { CExtraEntry *e = table++; e->totalBits = (Byte)(k + extraBits); e->extraBits = (Byte)extraBits; e->delta = (UInt16)(((f + j) << k) - numStates); e->vbase = vbase; } while (++j < j0); f -= j0; k--; for (j = 0; j < f; j++) { CExtraEntry *e = table++; e->totalBits = (Byte)(k + extraBits); e->extraBits = (Byte)extraBits; e->delta = (UInt16)(j << k); e->vbase = vbase; } } vbase += ((UInt32)1 << extraBits); } } static const Byte k_L_extra[NUM_L_SYMBOLS] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 5, 8 }; static const Byte k_M_extra[NUM_M_SYMBOLS] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 8, 11 }; static const Byte k_D_extra[NUM_D_SYMBOLS] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15 }; // ---------- CBitStream ---------- typedef struct { UInt32 accum; unsigned numBits; // [0, 31] - Number of valid bits in (accum), other bits are 0 } CBitStream; static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s, int n, // [-7, 0], (-n == number_of_unused_bits) in last byte const Byte **pbuf) { *pbuf -= 4; s->accum = GetUi32(*pbuf); if (n) { s->numBits = n + 32; if ((s->accum >> s->numBits) != 0) return -1; // ERROR, encoder should have zeroed the upper bits } else { *pbuf += 1; s->accum >>= 8; s->numBits = 24; } return 0; // OK } // 0 <= numBits < 32 #define mask31(x, numBits) ((x) & (((UInt32)1 << (numBits)) - 1)) #define FseInStream_FLUSH \ { unsigned nbits = (31 - in.numBits) & -8; \ if (nbits) { \ buf -= (nbits >> 3); \ if (buf < buf_check) return S_FALSE; \ UInt32 v = GetUi32(buf); \ in.accum = (in.accum << nbits) | mask31(v, nbits); \ in.numBits += nbits; }} static MY_FORCE_INLINE UInt32 BitStream_Pull(CBitStream *s, unsigned numBits) { s->numBits -= numBits; UInt32 v = s->accum >> s->numBits; s->accum = mask31(s->accum, s->numBits); return v; } #define DECODE_LIT(dest, pstate) { \ UInt32 e = lit_decoder[pstate]; \ pstate = (CFseState)((e >> 16) + BitStream_Pull(&in, e & 0xff)); \ dest = (Byte)(e >> 8); } static MY_FORCE_INLINE UInt32 FseDecodeExtra(CFseState *pstate, const CExtraEntry *table, CBitStream *s) { const CExtraEntry *e = &table[*pstate]; UInt32 v = BitStream_Pull(s, e->totalBits); unsigned extraBits = e->extraBits; *pstate = (CFseState)(e->delta + (v >> extraBits)); return e->vbase + mask31(v, extraBits); } #define freqs_L (freqs) #define freqs_M (freqs_L + NUM_L_SYMBOLS) #define freqs_D (freqs_M + NUM_M_SYMBOLS) #define freqs_LIT (freqs_D + NUM_D_SYMBOLS) #define GET_BITS_64(v, offset, num, dest) dest = (UInt32) ((v >> (offset)) & ((1 << (num)) - 1)); #define GET_BITS_32(v, offset, num, dest) dest = (CFseState)((v >> (offset)) & ((1 << (num)) - 1)); HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version) { PRF(printf("\nLZFSE-%d %7u", version - '0', unpackSize)); UInt32 numLiterals; UInt32 litPayloadSize; Int32 literal_bits; UInt32 lit_state_0; UInt32 lit_state_1; UInt32 lit_state_2; UInt32 lit_state_3; UInt32 numMatches; UInt32 lmdPayloadSize; Int32 lmd_bits; CFseState l_state; CFseState m_state; CFseState d_state; UInt16 freqs[NUM_SYMBOLS]; if (version == kSignature_LZFSE_V1) { return E_NOTIMPL; // we need examples to test LZFSE-V1 code /* const unsigned k_v1_SubHeaderSize = 7 * 4 + 7 * 2; const unsigned k_v1_HeaderSize = k_v1_SubHeaderSize + NUM_SYMBOLS * 2; _buffer.AllocAtLeast(k_v1_HeaderSize); if (m_InStream.ReadBytes(_buffer, k_v1_HeaderSize) != k_v1_HeaderSize) return S_FALSE; const Byte *buf = _buffer; #define GET_32(offs, dest) dest = GetUi32(buf + offs) #define GET_16(offs, dest) dest = GetUi16(buf + offs) UInt32 payload_bytes; GET_32(0, payload_bytes); GET_32(4, numLiterals); GET_32(8, numMatches); GET_32(12, litPayloadSize); GET_32(16, lmdPayloadSize); if (litPayloadSize > (1 << 20) || lmdPayloadSize > (1 << 20)) return S_FALSE; GET_32(20, literal_bits); if (literal_bits < -7 || literal_bits > 0) return S_FALSE; GET_16(24, lit_state_0); GET_16(26, lit_state_1); GET_16(28, lit_state_2); GET_16(30, lit_state_3); GET_32(32, lmd_bits); if (lmd_bits < -7 || lmd_bits > 0) return S_FALSE; GET_16(36, l_state); GET_16(38, m_state); GET_16(40, d_state); for (unsigned i = 0; i < NUM_SYMBOLS; i++) freqs[i] = GetUi16(buf + k_v1_SubHeaderSize + i * 2); */ } else { UInt32 headerSize; { const unsigned kPreHeaderSize = 4 * 2; // signature and upackSize const unsigned kHeaderSize = 8 * 3; Byte temp[kHeaderSize]; if (m_InStream.ReadBytes(temp, kHeaderSize) != kHeaderSize) return S_FALSE; UInt64 v; v = GetUi64(temp); GET_BITS_64(v, 0, 20, numLiterals); GET_BITS_64(v, 20, 20, litPayloadSize); GET_BITS_64(v, 40, 20, numMatches); GET_BITS_64(v, 60, 3 + 1, literal_bits); // (NumberOfUsedBits - 1) literal_bits -= 7; // (-NumberOfUnusedBits) if (literal_bits > 0) return S_FALSE; // GET_BITS_64(v, 63, 1, unused); v = GetUi64(temp + 8); GET_BITS_64(v, 0, 10, lit_state_0); GET_BITS_64(v, 10, 10, lit_state_1); GET_BITS_64(v, 20, 10, lit_state_2); GET_BITS_64(v, 30, 10, lit_state_3); GET_BITS_64(v, 40, 20, lmdPayloadSize); GET_BITS_64(v, 60, 3 + 1, lmd_bits); lmd_bits -= 7; if (lmd_bits > 0) return S_FALSE; // GET_BITS_64(v, 63, 1, unused) UInt32 v32 = GetUi32(temp + 20); // (total header size in bytes; this does not // correspond to a field in the uncompressed header version, // but is required; we wouldn't know the size of the // compresssed header otherwise. GET_BITS_32(v32, 0, 10, l_state); GET_BITS_32(v32, 10, 10, m_state); GET_BITS_32(v32, 20, 10 + 2, d_state); // GET_BITS_64(v, 62, 2, unused); headerSize = GetUi32(temp + 16); if (headerSize <= kPreHeaderSize + kHeaderSize) return S_FALSE; headerSize -= kPreHeaderSize + kHeaderSize; } // no freqs case is not allowed ? // memset(freqs, 0, sizeof(freqs)); // if (headerSize != 0) { static const Byte numBitsTable[32] = { 2, 3, 2, 5, 2, 3, 2, 8, 2, 3, 2, 5, 2, 3, 2, 14, 2, 3, 2, 5, 2, 3, 2, 8, 2, 3, 2, 5, 2, 3, 2, 14 }; static const Byte valueTable[32] = { 0, 2, 1, 4, 0, 3, 1, 8, 0, 2, 1, 5, 0, 3, 1, 24, 0, 2, 1, 6, 0, 3, 1, 8, 0, 2, 1, 7, 0, 3, 1, 24 }; UInt32 accum = 0; unsigned numBits = 0; for (unsigned i = 0; i < NUM_SYMBOLS; i++) { while (numBits <= 14 && headerSize != 0) { Byte b; if (!m_InStream.ReadByte(b)) return S_FALSE; accum |= (UInt32)b << numBits; numBits += 8; headerSize--; } unsigned b = (unsigned)accum & 31; unsigned n = numBitsTable[b]; if (numBits < n) return S_FALSE; numBits -= n; UInt32 f = valueTable[b]; if (n >= 8) f += ((accum >> 4) & (0x3ff >> (14 - n))); accum >>= n; freqs[i] = (UInt16)f; } if (numBits >= 8 || headerSize != 0) return S_FALSE; } } PRF(printf(" Literals=%6u Matches=%6u", numLiterals, numMatches)); if (numLiterals > LITERALS_PER_BLOCK || (numLiterals & 3) != 0 || numMatches > MATCHES_PER_BLOCK || lit_state_0 >= NUM_LIT_STATES || lit_state_1 >= NUM_LIT_STATES || lit_state_2 >= NUM_LIT_STATES || lit_state_3 >= NUM_LIT_STATES || l_state >= NUM_L_STATES || m_state >= NUM_M_STATES || d_state >= NUM_D_STATES) return S_FALSE; // only full table is allowed ? if ( SumFreqs(freqs_L, NUM_L_SYMBOLS) != NUM_L_STATES || SumFreqs(freqs_M, NUM_M_SYMBOLS) != NUM_M_STATES || SumFreqs(freqs_D, NUM_D_SYMBOLS) != NUM_D_STATES || SumFreqs(freqs_LIT, NUM_LIT_SYMBOLS) != NUM_LIT_STATES) return S_FALSE; const unsigned kPad = 16; // ---------- Decode literals ---------- { _literals.AllocAtLeast(LITERALS_PER_BLOCK + 16); _buffer.AllocAtLeast(kPad + litPayloadSize); memset(_buffer, 0, kPad); if (m_InStream.ReadBytes(_buffer + kPad, litPayloadSize) != litPayloadSize) return S_FALSE; UInt32 lit_decoder[NUM_LIT_STATES]; InitLitTable(freqs_LIT, lit_decoder); const Byte *buf_start = _buffer + kPad; const Byte *buf_check = buf_start - 4; const Byte *buf = buf_start + litPayloadSize; CBitStream in; if (FseInStream_Init(&in, literal_bits, &buf) != 0) return S_FALSE; Byte *lit = _literals; const Byte *lit_limit = lit + numLiterals; for (; lit < lit_limit; lit += 4) { FseInStream_FLUSH DECODE_LIT (lit[0], lit_state_0); DECODE_LIT (lit[1], lit_state_1); FseInStream_FLUSH DECODE_LIT (lit[2], lit_state_2); DECODE_LIT (lit[3], lit_state_3); } if ((buf_start - buf) * 8 != (int)in.numBits) return S_FALSE; } // ---------- Decode LMD ---------- _buffer.AllocAtLeast(kPad + lmdPayloadSize); memset(_buffer, 0, kPad); if (m_InStream.ReadBytes(_buffer + kPad, lmdPayloadSize) != lmdPayloadSize) return S_FALSE; CExtraEntry l_decoder[NUM_L_STATES]; CExtraEntry m_decoder[NUM_M_STATES]; CExtraEntry d_decoder[NUM_D_STATES]; InitExtraDecoderTable(NUM_L_STATES, NUM_L_SYMBOLS, freqs_L, k_L_extra, l_decoder); InitExtraDecoderTable(NUM_M_STATES, NUM_M_SYMBOLS, freqs_M, k_M_extra, m_decoder); InitExtraDecoderTable(NUM_D_STATES, NUM_D_SYMBOLS, freqs_D, k_D_extra, d_decoder); const Byte *buf_start = _buffer + kPad; const Byte *buf_check = buf_start - 4; const Byte *buf = buf_start + lmdPayloadSize; CBitStream in; if (FseInStream_Init(&in, lmd_bits, &buf)) return S_FALSE; const Byte *lit = _literals; const Byte *lit_limit = lit + numLiterals; UInt32 D = 0; for (;;) { if (numMatches == 0) break; numMatches--; FseInStream_FLUSH unsigned L = (unsigned)FseDecodeExtra(&l_state, l_decoder, &in); FseInStream_FLUSH unsigned M = (unsigned)FseDecodeExtra(&m_state, m_decoder, &in); FseInStream_FLUSH { UInt32 new_D = FseDecodeExtra(&d_state, d_decoder, &in); if (new_D) D = new_D; } if (L != 0) { if (L > (size_t)(lit_limit - lit)) return S_FALSE; unsigned cur = L; if (cur > unpackSize) cur = (unsigned)unpackSize; m_OutWindowStream.PutBytes(lit, cur); unpackSize -= cur; lit += cur; if (cur != L) return S_FALSE; } if (M != 0) { if (unpackSize == 0 || D == 0) return S_FALSE; unsigned cur = M; if (cur > unpackSize) cur = (unsigned)unpackSize; if (!m_OutWindowStream.CopyBlock(D - 1, cur)) return S_FALSE; unpackSize -= cur; if (cur != M) return S_FALSE; } } if (unpackSize != 0) return S_FALSE; // LZFSE encoder writes 8 additional zero bytes before LMD payload // We test it: if ((buf - buf_start) * 8 + in.numBits != 64) return S_FALSE; if (GetUi64(buf_start) != 0) return S_FALSE; return S_OK; } STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) { PRF(printf("\n\nLzfseDecoder %7u %7u\n", (unsigned)*outSize, (unsigned)*inSize)); const UInt32 kLzfseDictSize = 1 << 18; if (!m_OutWindowStream.Create(kLzfseDictSize)) return E_OUTOFMEMORY; if (!m_InStream.Create(1 << 18)) return E_OUTOFMEMORY; m_OutWindowStream.SetStream(outStream); m_OutWindowStream.Init(false); m_InStream.SetStream(inStream); m_InStream.Init(); CCoderReleaser coderReleaser(this); UInt64 prevOut = 0; UInt64 prevIn = 0; for (;;) { const UInt64 pos = m_OutWindowStream.GetProcessedSize(); const UInt64 packPos = m_InStream.GetProcessedSize(); if (progress && ((pos - prevOut) >= (1 << 22) || (packPos - prevIn) >= (1 << 22))) { RINOK(progress->SetRatioInfo(&packPos, &pos)); prevIn = packPos; prevOut = pos; } const UInt64 rem = *outSize - pos; UInt32 v; RINOK(GetUInt32(v)) if ((v & 0xFFFFFF) != 0x787662) // bvx return S_FALSE; v >>= 24; if (v == 0x24) // '$', end of stream break; UInt32 unpackSize; RINOK(GetUInt32(unpackSize)); UInt32 cur = unpackSize; if (cur > rem) cur = (UInt32)rem; unpackSize -= cur; HRESULT res; if (v == kSignature_LZFSE_V1 || v == kSignature_LZFSE_V2) res = DecodeLzfse(cur, (Byte)v); else if (v == 0x6E) // 'n' res = DecodeLzvn(cur); else if (v == 0x2D) // '-' res = DecodeUncompressed(cur); else return E_NOTIMPL; if (res != S_OK) return res; if (unpackSize != 0) return S_FALSE; } coderReleaser.NeedFlush = false; HRESULT res = m_OutWindowStream.Flush(); if (res == S_OK) if (*inSize != m_InStream.GetProcessedSize() || *outSize != m_OutWindowStream.GetProcessedSize()) res = S_FALSE; return res; } STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) { try { return CodeReal(inStream, outStream, inSize, outSize, progress); } catch(const CInBufferException &e) { return e.ErrorCode; } catch(const CLzOutWindowException &e) { return e.ErrorCode; } catch(...) { return E_OUTOFMEMORY; } // catch(...) { return S_FALSE; } } }}
23,104
9,986
// // Upcaste Performance Libraries // Copyright (C) 2012-2013 Jesse W. Towner // // 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 <up/cinttypes.hpp> #include <up/cmath.hpp> #include <up/log.hpp> #include <up/random.hpp> #include <up/test.hpp> namespace prng { UP_TEST_CASE(generate_canonical) { up::xorshift64_engine<uint_least32_t, 13, 7, 17> engine32; up::xorshift64_engine<uint_least64_t, 13, 7, 17> engine64; long double sum; double d; float f; size_t i; for (sum = 0.0l, i = 1; i <= 32768; sum += f, ++i) { f = ::up::generate_canonical<float, FLT_MANT_DIG>(engine32); require((0.0f <= f) && (f < 1.0f)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); for (sum = 0.0l, i = 1; i <= 32768; sum += f, ++i) { f = ::up::generate_canonical<float, FLT_MANT_DIG>(engine64); require((0.0f <= f) && (f < 1.0f)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); for (sum = 0.0l, i = 1; i <= 32768; sum += d, ++i) { d = ::up::generate_canonical<double, DBL_MANT_DIG>(engine32); require((0.0 <= d) && (d < 1.0)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); for (sum = 0.0l, i = 1; i <= 32768; sum += d, ++i) { d = ::up::generate_canonical<float, DBL_MANT_DIG>(engine64); require((0.0 <= d) && (d < 1.0)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); } UP_TEST_CASE(generate_random_seed) { uint_least32_t seed; uint_least32_t seq[4]; seed = 0; up::generate_random_seed(seq, 4, &seed, 1); require(seq[0] == 0xb0a842fd); require(seq[1] == 0x04290315); require(seq[2] == 0x75a0adfa); require(seq[3] == 0x1fb83b0f); seed = 1; up::generate_random_seed(seq, 4, &seed, 1); require(seq[0] == 0x4dc239dd); require(seq[1] == 0x529c8ec8); require(seq[2] == 0x60e79bf6); require(seq[3] == 0x624f7451); seed = 521288629; up::generate_random_seed(seq, 4, &seed, 1); require(seq[0] == 0xb887f987); require(seq[1] == 0x6e42c737); require(seq[2] == 0xd6c4c175); require(seq[3] == 0xf71737b9); } UP_TEST_CASE(xorshift64_engine) { up::default_xorshift64_engine engine; require(engine.min() == ((UINT_FAST32_MAX > 0xFFFFFFFF) ? 1 : 0)) require(engine.max() == UINT_FAST32_MAX); #ifdef UP_DEBUG up::log_event(up::log_level_info, "First 128 values...\n\n"); for (size_t i = 1; i <= 128; ++i) { up::log_eventf(up::log_level_info, "%#.8" PRIxFAST32 " ", static_cast<uintmax_t>(engine())); if ((i % 4) == 0) { up::log_event(up::log_level_info, "\n"); } } #else engine.discard(128); #endif #if UINT_FAST32_MAX == 0xFFFFFFFF require(engine() == 0xfb699180); #else require(engine() == 0xda8b4c09021984c3ull); #endif } UP_TEST_CASE(xorshift128_engine) { up::default_xorshift128_engine engine; require(engine.min() == 0) require(engine.max() == UINT_FAST32_MAX); #ifdef UP_DEBUG up::log_event(up::log_level_info, "First 128 values...\n\n"); for (size_t i = 1; i <= 128; ++i) { up::log_eventf(up::log_level_info, "%#.8" PRIxFAST32 " ", static_cast<uintmax_t>(engine())); if ((i % 4) == 0) { up::log_event(up::log_level_info, "\n"); } } #else engine.discard(128); #endif #if UINT_FAST32_MAX == 0xFFFFFFFF require(engine() == 0xc72a4e0a); #else require(engine() == 0x60f38d031f5c90b1); #endif } UP_TEST_CASE(uniform_int_distribution) { up::default_random_engine engine; long double sum; size_t i; int x; static_assert(up::is_same<int, up::uniform_int_distribution<int>::result_type>::value, "unexpected type"); up::uniform_int_distribution<int> dist0(0, 0); require((dist0.a() == 0) && (dist0.b() == 0)); require((dist0.min() == 0) && (dist0.max() == 0)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_int_distribution<int> dist1(0, 10); require((dist1.a() == 0) && (dist1.b() == 10)); require((dist1.min() == 0) && (dist1.max() == 10)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist1(engine); require((x >= 0) && (x <= 10)); } require_approx(sum / 16384.0l, 5.0l, 0.05l); up::uniform_int_distribution<int> dist2(-10, 0); require((dist2.a() == -10) && (dist2.b() == 0)); require((dist2.min() == -10) && (dist2.max() == 0)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist2(engine); require((x >= -10) && (x <= 0)); } require_approx(sum / 16384.0l, -5.0l, 0.05l); up::uniform_int_distribution<int> dist3(-10, 10); require((dist3.a() == -10) && (dist3.b() == 10)); require((dist3.min() == -10) && (dist3.max() == 10)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist3(engine); require((x >= -10) && (x <= 10)); } require_approx(sum / 16384.0l, 0.0l, 0.05l); up::uniform_int_distribution<int> dist4; require((dist4.a() == 0) && (dist4.b() == INT_MAX)); require((dist4.min() == 0) && (dist4.max() == INT_MAX)); for (sum = 0.0l, i = 1; i <= (INT_MAX / 8); sum += x, ++i) { x = dist4(engine); require((x >= 0) && (x <= INT_MAX)); } require_approx(sum / (INT_MAX / 8.0l), (INT_MAX / 2.0l), 50000.0l); } UP_TEST_CASE(uniform_llong_distribution) { typedef long long llong; up::default_random_engine engine; long double sum; llong x; size_t i; static_assert(up::is_same<llong, up::uniform_int_distribution<llong>::result_type>::value, "unexpected type"); up::uniform_int_distribution<llong> dist0(0, 0); require((dist0.a() == 0) && (dist0.b() == 0)); require((dist0.min() == 0) && (dist0.max() == 0)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_int_distribution<llong> dist1(-100, 100); require((dist1.a() == -100) && (dist1.b() == 100)); require((dist1.min() == -100) && (dist1.max() == 100)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist1(engine); require((x >= -100) && (x <= 100)); } require_approx(sum / 16384.0l, 0.0l, 1.0l); up::uniform_int_distribution<llong> dist2; require((dist2.a() == 0) && (dist2.b() == LLONG_MAX)); require((dist2.min() == 0) && (dist2.max() == LLONG_MAX)); for (sum = 0.0l, i = 1; i <= (INT_MAX / 8); sum += x, ++i) { x = dist2(engine); require((x >= 0) && (x <= LLONG_MAX)); } require_approx(sum / (INT_MAX / 8.0l), (LLONG_MAX / 2.0l), 4.0e+14); } UP_TEST_CASE(uniform_ullong_distribution) { typedef unsigned long long ullong; up::default_random_engine engine; long double sum; ullong x; size_t i; static_assert(up::is_same<ullong, up::uniform_int_distribution<ullong>::result_type>::value, "unexpected type"); up::uniform_int_distribution<ullong> dist0(0, 0); require((dist0.a() == 0) && (dist0.b() == 0)); require((dist0.min() == 0) && (dist0.max() == 0)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_int_distribution<ullong> dist1(0, 100); require((dist1.a() == 0) && (dist1.b() == 100)); require((dist1.min() == 0) && (dist1.max() == 100)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist1(engine); require(x <= 100); } require_approx(sum / 16384.0l, 50.0l, 1.0l); up::uniform_int_distribution<ullong> dist2; require((dist2.a() == 0) && (dist2.b() == ULLONG_MAX)); require((dist2.min() == 0) && (dist2.max() == ULLONG_MAX)); for (sum = 0.0l, i = 1; i <= (INT_MAX / 8); sum += x, ++i) { x = dist2(engine); require(x <= ULLONG_MAX); } require_approx(sum / (INT_MAX / 8.0l), (ULLONG_MAX / 2.0l), 4.0e+14); } UP_TEST_CASE(uniform_float_distribution) { up::default_random_engine engine; long double sum; float x; size_t i; static_assert(up::is_same<float, up::uniform_real_distribution<float>::result_type>::value, "unexpected type"); up::uniform_real_distribution<float> dist0(0.0f, 0.0f); require((dist0.a() == 0.0f) && (dist0.b() == 0.0f)); require((dist0.min() == 0.0f) && (dist0.max() == 0.0f)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0.0f); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_real_distribution<float> dist1; require((dist1.a() == 0.0f) && (dist1.b() == 1.0f)); require((dist1.min() == 0.0f) && (dist1.max() == 1.0f)); for (sum = 0.0l, i = 1; i <= 32768; sum += x, ++i) { x = dist1(engine); require((0.0f <= x) && (x < 1.0f)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); up::uniform_real_distribution<float> dist2(-128.0f, 128.0f); require((dist2.a() == -128.0f) && (dist2.b() == 128.0f)); require((dist2.min() == -128.0f) && (dist2.max() == 128.0f)); for (sum = 0.0l, i = 1; i <= 32768; sum += x, ++i) { x = dist2(engine); require((-128.0f <= x) && (x < 128.0f)); } require_approx(sum / 32768.0l, 0.0l, 1.0l); } UP_TEST_CASE(uniform_double_distribution) { up::default_random_engine engine; long double sum; double x; size_t i; static_assert(up::is_same<double, up::uniform_real_distribution<double>::result_type>::value, "unexpected type"); up::uniform_real_distribution<double> dist0(0.0, 0.0); require((dist0.a() == 0.0) && (dist0.b() == 0.0)); require((dist0.min() == 0.0) && (dist0.max() == 0.0)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0.0); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_real_distribution<double> dist1; require((dist1.a() == 0.0) && (dist1.b() == 1.0)); require((dist1.min() == 0.0) && (dist1.max() == 1.0)); for (sum = 0.0l, i = 1; i <= 32768; sum += x, ++i) { x = dist1(engine); require((0.0 <= x) && (x < 1.0)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); up::uniform_real_distribution<double> dist2(-128.0, 128.0); require((dist2.a() == -128.0) && (dist2.b() == 128.0)); require((dist2.min() == -128.0) && (dist2.max() == 128.0)); for (sum = 0.0l, i = 1; i <= 32768; sum += x, ++i) { x = dist2(engine); require((-128.0 <= x) && (x < 128.0)); } require_approx(sum / 32768.0l, 0.0l, 1.0l); up::uniform_real_distribution<double> dist3(-FLT_MAX, FLT_MAX); require((dist3.a() == -FLT_MAX) && (dist3.b() == FLT_MAX)); require((dist3.min() == -FLT_MAX) && (dist3.max() == FLT_MAX)); for (sum = 0.0l, i = 1; i <= INT_MAX; sum += x, ++i) { x = dist3(engine); require((-FLT_MAX <= x) && (x < FLT_MAX)); } require_approx(sum / INT_MAX, 0.0l, FLT_MAX); } }
13,685
5,774
#include <iostream> #include <turbo/Engine.hpp> int main() { turbo::EventHandler<unsigned int, float> event_handler([](unsigned int i, float j) { std::cout << "i: " << i << ", j: " << j << std::endl; }); turbo::Event<unsigned int, float> testEvent; testEvent += event_handler; testEvent(4, -4.84); testEvent(8, 17.5); testEvent(19, 0.1); return 0; }
390
148
#pragma once #include <iostream> #include <vector> #define MECH_INF 0 #define ARMOR 1 #define ARTILLARY 2 #define SF 3 #define INF 4 class Regiment{ public: int type; int battalions; double BBV; double BDV; double BS; double BBD; double BSP; void addBattalion(); int getStrength(); double getBV(); double getDV(); double getBD(); double getSpeed(); Regiment(int t, int b); };
406
177
#include <iostream> #include <fstream> using namespace std; typedef struct node{ int n; struct node * left; struct node * right; }node; node * make_tree(){ node * n5 = new node; n5->n = 5; n5->left = nullptr; n5->right = nullptr; node * n4 = new node; n4->n = 4; n4->left = nullptr; n4->right = nullptr; node * n3 = new node; n3->n = 3; n3->left = nullptr; n3->right = nullptr; node * n2 = new node; n2->n = 2; n2->left = n4; n2->right = n5; node * root = new node; root->n = 1; root->left = n2; root->right = n3; return root; } int main(){ ifstream reader("a.txt"); string str1, str2, str3, str4; reader >> str1 >> str2 >> str3 >> str4; if(str1 == "") cout << "1" << endl; if(str2 == "") cout << "2" << endl; if(str3 == "") cout << "3" << endl; if(str4 == "") cout << "4" << endl; reader.close(); return 0; }
889
359
// Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "fiddle/examples.h" // HASH=0d2cbf82f490ffb180e0b4531afa232c REG_FIDDLE(Picture_MakePlaceholder, 256, 256, false, 0) { class MyCanvas : public SkCanvas { public: MyCanvas(SkCanvas* c) : canvas(c) {} void onDrawPicture(const SkPicture* picture, const SkMatrix* , const SkPaint* ) override { const SkRect rect = picture->cullRect(); SkPaint redPaint; redPaint.setColor(SK_ColorRED); canvas->drawRect(rect, redPaint); } SkCanvas* canvas; }; void draw(SkCanvas* canvas) { SkPictureRecorder recorder; SkCanvas* pictureCanvas = recorder.beginRecording({0, 0, 256, 256}); sk_sp<SkPicture> placeholder = SkPicture::MakePlaceholder({10, 40, 80, 110}); pictureCanvas->drawPicture(placeholder); sk_sp<SkPicture> picture = recorder.finishRecordingAsPicture(); MyCanvas myCanvas(canvas); myCanvas.drawPicture(picture); } } // END FIDDLE
1,075
375
/////////////////////////////////////////////////////////////////////////////// // // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ // /////////////////////////////////////////////////////////////////////////////// // Process creation test. // Create processes on local and remote nodes using both // waited and no-waited create. // #include <stdio.h> #include <stdlib.h> #include "clio.h" #include "sqevlog/evl_sqlog_writer.h" #include "montestutil.h" #include "xmpi.h" MonTestUtil util; long trace_settings = 0; FILE *shell_locio_trace_file = NULL; bool tracing = false; const char *MyName; int MyRank = -1; int gv_ms_su_nid = -1; // Local IO nid to make compatible w/ Seabed SB_Verif_Type gv_ms_su_verif = -1; char ga_ms_su_c_port[MPI_MAX_PORT_NAME] = {0}; // connect const int MAX_WORKERS = 5; const char *workerName[] = {"$SERV0","$SERV1", "$SERV2", "$SERV3", "$SERVX"}; int workerCreateNid[MAX_WORKERS]; // Node on which to create the process bool workerNowait[MAX_WORKERS] = {false, false, true, true, true}; int workerNid[MAX_WORKERS]; int workerPid[MAX_WORKERS]; int workerVerifier[MAX_WORKERS]; bool testSuccess = true; class WorkerProcess { public: WorkerProcess(const char * name, int nid, int pid, Verifier_t verifier); ~WorkerProcess(){} const char * getName() { return name_.c_str(); } int getNid() { return nid_; } int getPid() { return pid_; } int getVerifier() { return verifier_; } void incrDeathNotice() { ++deathNotices_; } int getDeathNoticeCount() { return deathNotices_; } void incrCreatedNotice() { ++createdNotices_; } int getCreatedNoticeCount() { return createdNotices_; } private: string name_; int nid_; int pid_; Verifier_t verifier_; int deathNotices_; int createdNotices_; }; WorkerProcess::WorkerProcess( const char *name , int nid , int pid , Verifier_t verifier) : name_(name) , nid_(nid) , pid_(pid) , verifier_(verifier) , deathNotices_ (0) , createdNotices_(0) { } WorkerProcess* procList[50]; int procListCount = 0; // Routine for handling notices void recv_notice_msg(struct message_def *recv_msg, int ) { if ( recv_msg->type == MsgType_Shutdown ) { if ( tracing ) printf("[%s] Shutdown notice received, level=%d\n", MyName, recv_msg->u.request.u.shutdown.level); } else if ( recv_msg->type == MsgType_ProcessDeath ) { if ( tracing ) printf("[%s] Process death notice received for %s (%d, %d:%d)," " trans_id=%lld.%lld.%lld.%lld., aborted=%d\n", MyName, recv_msg->u.request.u.death.process_name, recv_msg->u.request.u.death.nid, recv_msg->u.request.u.death.pid, recv_msg->u.request.u.death.verifier, recv_msg->u.request.u.death.trans_id.txid[0], recv_msg->u.request.u.death.trans_id.txid[1], recv_msg->u.request.u.death.trans_id.txid[2], recv_msg->u.request.u.death.trans_id.txid[3], recv_msg->u.request.u.death.aborted); bool found = false; for (int i=0; i<procListCount; i++) { if (procList[i]->getNid() == recv_msg->u.request.u.death.nid && procList[i]->getPid() == recv_msg->u.request.u.death.pid) { procList[i]->incrDeathNotice(); found = true; break; } } if (!found) { printf("[%s] Could not find procList object for %s (%d, %d)\n", MyName, recv_msg->u.request.u.death.process_name, recv_msg->u.request.u.death.nid, recv_msg->u.request.u.death.pid); } } else if ( recv_msg->type == MsgType_ProcessCreated ) { if ( tracing ) printf("[%s] Process creation notice received for %s (%d, %d:%d)," " port=%s, tag=%lld, ret code=%d\n", MyName, recv_msg->u.request.u.process_created.process_name, recv_msg->u.request.u.process_created.nid, recv_msg->u.request.u.process_created.pid, recv_msg->u.request.u.process_created.verifier, recv_msg->u.request.u.process_created.port, recv_msg->u.request.u.process_created.tag, recv_msg->u.request.u.process_created.return_code); bool found = false; for (int i=0; i<procListCount; i++) { if ( strcmp(procList[i]->getName(), recv_msg->u.request.u.process_created.process_name) == 0) { printf("[%s] *** ERROR *** Got process creation notice for " " %s (%d, %d) but process already in list.\n", MyName, recv_msg->u.request.u.process_created.process_name, recv_msg->u.request.u.process_created.nid, recv_msg->u.request.u.process_created.pid); testSuccess = false; found = true; break; } } if (!found) { int i; for (i=0; i<MAX_WORKERS; i++) { if ( strcmp(workerName[i], recv_msg->u.request.u.process_created.process_name) == 0) { printf("[%s] Got process creation notice for " " %s (%d, %d) adding process to procList[%d].\n", MyName, recv_msg->u.request.u.process_created.process_name, recv_msg->u.request.u.process_created.nid, recv_msg->u.request.u.process_created.pid, i); found = true; break; } } if ( found ) { procList[i] = new WorkerProcess ( recv_msg->u.request.u.process_created.process_name, recv_msg->u.request.u.process_created.nid, recv_msg->u.request.u.process_created.pid, recv_msg->u.request.u.process_created.verifier); procList[i]->incrCreatedNotice(); ++procListCount; if ( tracing ) printf ("[%s] Worker #%d: %s (%d, %d:%d)\n", MyName, i, recv_msg->u.request.u.process_created.process_name, recv_msg->u.request.u.process_created.nid, recv_msg->u.request.u.process_created.pid, recv_msg->u.request.u.process_created.verifier); } } } else { printf("[%s] unexpected notice, type=%s\n", MyName, MessageTypeString( recv_msg->type)); testSuccess = false; } } int main (int argc, char *argv[]) { char *serverArgs[1] = {(char *) "-t"}; char *server5ArgsTrace[2] = {(char *) "-t",(char *) "-x"}; char *server5ArgsNoTrace[1] = {(char *) "-x"}; char procName[25]; util.processArgs (argc, argv); tracing = util.getTrace(); MyName = util.getProcName(); util.InitLocalIO( ); assert (gp_local_mon_io); // Set local io callback function for "notices" gp_local_mon_io->set_cb(recv_notice_msg, "notice"); gp_local_mon_io->set_cb(recv_notice_msg, "event"); gp_local_mon_io->set_cb(recv_notice_msg, "recv"); gp_local_mon_io->set_cb(recv_notice_msg, "unsol"); util.requestStartup (); // verify correct number of nodes testSuccess = util.validateNodeCount(2); if(!testSuccess) { printf("Process Creation Test:\t\t%s\n", "FAILED due to an invalid configuration"); // tell monitor we are exiting util.requestExit ( ); XMPI_Close_port (util.getPort()); if ( gp_local_mon_io ) { delete gp_local_mon_io; } exit (0); } int myNid = util.getNid(); int otherNid = ( myNid == 0 ) ? 1 : 0; if ( util.getShutdownBeforeStartup() ) { printf("[%s] ShutdownBeforeStartup Test\n", MyName); workerCreateNid[0] = myNid; workerCreateNid[1] = otherNid; workerCreateNid[2] = myNid; workerCreateNid[3] = otherNid; workerCreateNid[4] = otherNid; // Create all processes except the 5th process for (int i = 0; i < (MAX_WORKERS-1); i++) { printf("[%s] Starting process %s on node %d, %s\n", MyName, workerName[i], workerCreateNid[i], (workerNowait[i] ? "nowait" : "wait")); testSuccess = util.requestNewProcess( workerCreateNid[i] , ProcessType_Generic , workerNowait[i] , workerName[i] , "server" , "" // inFile , "" // outFile , ((tracing) ? 1: 0) , serverArgs , workerNid[i] , workerPid[i] , workerVerifier[i] , procName); if ( testSuccess ) { if ( workerNowait[i] == false ) { procList[procListCount] = new WorkerProcess( workerName[i] , workerNid[i] , workerPid[i] , workerVerifier[i] ); ++procListCount; if ( tracing ) printf ("[%s] Worker #%d: %s (%d, %d:%d)\n", MyName, procListCount-1, workerName[i], workerNid[i], workerPid[i], workerVerifier[i] ); } } } sleep(2); // Kill the processes previously created for (int j=0; j<procListCount; j++) { printf("[%s] Killing process %s (%d, %d)\n", MyName, procList[j]->getName(), procList[j]->getNid(), procList[j]->getPid()); util.requestKill( procList[j]->getName(), procList[j]->getVerifier() ); } // Create the the 5th process printf("[%s] Starting process %s on node %d, %s, args=%s %s\n", MyName, workerName[(MAX_WORKERS-1)], workerCreateNid[(MAX_WORKERS-1)], (workerNowait[(MAX_WORKERS-1)] ? "nowait" : "wait"), server5ArgsTrace[0],((tracing)?server5ArgsTrace[1]:"") ); testSuccess = util.requestNewProcess ( workerCreateNid[(MAX_WORKERS-1)], ProcessType_Generic, workerNowait[(MAX_WORKERS-1)], workerName[(MAX_WORKERS-1)], "server", "", // inFile "", // outFile ((tracing)?2:1), ((tracing)?server5ArgsTrace:server5ArgsNoTrace), workerNid[(MAX_WORKERS-1)], workerPid[(MAX_WORKERS-1)], workerVerifier[(MAX_WORKERS-1)], procName); if ( testSuccess ) { if ( workerNowait[(MAX_WORKERS-1)] == false ) { procList[procListCount] = new WorkerProcess ( workerName[(MAX_WORKERS-1)] , workerNid[(MAX_WORKERS-1)] , workerPid[(MAX_WORKERS-1)] , workerVerifier[(MAX_WORKERS-1)] ); ++procListCount; if ( tracing ) printf ( "[%s] Worker #%d: %s (%d, %d:%d)\n", MyName , procListCount-1 , workerName[(procListCount-1)] , workerNid[(procListCount-1)] , workerPid[(procListCount-1)] , workerVerifier[(procListCount-1)] ); } } // Wait for a while so process will be created sleep(1); util.requestShutdown ( ShutdownLevel_Normal ); // Wait for a while so can receive notices sleep(3); // Verify that got all notices and that processes were created // on the correct nodes bool found; for (int i = 0; i < MAX_WORKERS; i++) { found = false; for (int j=0; j<procListCount; j++) { if ( strcmp(workerName[i], procList[j]->getName()) ==0) { found = true; if (workerCreateNid[i] != workerNid[j]) { printf("[%s] *** ERROR *** For worker %s requested " "process creation on node %d but it was created " "on node %d.\n", MyName, workerName[i], workerCreateNid[i], workerNid[j]); testSuccess = false; } if ( workerNowait[i] && procList[j]->getCreatedNoticeCount() == 0) { printf("[%s] *** ERROR *** For worker %s did not get " "process creation notice as expected.\n", MyName, workerName[i]); testSuccess = false; } if ( procList[j]->getDeathNoticeCount() == 0 ) { printf("[%s] *** ERROR *** For worker %s did not get " "process death notice as expected.\n", MyName, workerName[i]); testSuccess = false; } } } if ( !found ) { printf("[%s] *** ERROR *** Worker process %s not created " "as expected.\n", MyName, workerName[i]); testSuccess = false; } } printf("Process Creation Test:\t\t%s\n", (testSuccess) ? "PASSED" : "FAILED"); } if ( util.getNodedownBeforeStartup() ) { printf("[%s] NodedownBeforeStartup Test\n", MyName); char *serverArgsNodeDownNotrace[1] = {(char *) "-y"}; char *serverArgsNodeDown2[2] = {(char *) "-t", (char *) "-y"}; workerCreateNid[0] = otherNid; workerCreateNid[1] = otherNid; workerNowait[0] = true; workerNowait[1] = false; int maxworkers = 2; procListCount = 0; // Create all processes except the 5th process for (int i = 0; i < maxworkers; i++) { printf("[%s] Starting process %s on node %d, %s\n", MyName, workerName[i], workerCreateNid[i], (workerNowait[i] ? "nowait" : "wait")); testSuccess = util.requestNewProcess( workerCreateNid[i] , ProcessType_Generic , workerNowait[i] , workerName[i] , "server" , "" // inFile , "" // outFile , ((tracing) ? 2: 1) //argument count , (tracing)?serverArgsNodeDown2:serverArgsNodeDownNotrace , workerNid[i] , workerPid[i] , workerVerifier[i] , procName); if ( testSuccess ) { if ( workerNowait[i] == false ) { procList[procListCount] = new WorkerProcess( workerName[i] , workerNid[i] , workerPid[i] , workerVerifier[i] ); ++procListCount; if ( tracing ) printf ("[%s] Worker #%d: %s (%d, %d:%d)\n", MyName, procListCount-1, workerName[i], workerNid[i], workerPid[i], workerVerifier[i] ); } } } //sleep for x sec for external script to issue node down. // Wait for a while so can receive notices sleep(5); // Verify that we got all notices bool found; for (int i = 0; i < maxworkers; i++) { found = false; for (int j=0; j<procListCount; j++) { if ( strcmp(workerName[i], procList[j]->getName()) ==0) { found = true; if (workerCreateNid[i] != workerNid[j]) { printf("[%s] *** ERROR *** For worker %s requested " "process creation on node %d but it was created " "on node %d.\n", MyName, workerName[i], workerCreateNid[i], workerNid[j]); testSuccess = false; } if ( workerNowait[i] && procList[j]->getCreatedNoticeCount() == 0) { printf("[%s] *** ERROR *** For worker %s did not get " "process creation notice as expected.\n", MyName, workerName[i]); testSuccess = false; } if ( procList[j]->getDeathNoticeCount() == 0 ) { printf("[%s] *** ERROR *** For worker %s did not get " "process death notice as expected.\n", MyName, workerName[i]); testSuccess = false; } } } if ( !found ) { printf("[%s] Worker process %s not created " "as expected.\n", MyName, workerName[i]); testSuccess = true; //not finding it is expected here. } } printf("Node Down Before Startup Test :\t%s\n", (testSuccess) ? "PASSED" : "FAILED"); } // tell monitor we are exiting util.requestExit ( ); XMPI_Close_port (util.getPort()); if ( gp_local_mon_io ) { delete gp_local_mon_io; } exit (0); }
20,802
5,902
// // CPUModelResults.hpp // SNR_opencl_multi // // Created by tihmstar on 27.11.19. // Copyright © 2019 tihmstar. All rights reserved. // #ifndef CPUModelResults_hpp #define CPUModelResults_hpp #include <vector> #include "numerics.hpp" class CPUModelResults { std::string _modelName; cl_uint _modelSize; cl_uint _point_per_trace; std::vector<combtrace> _groupsMean; std::vector<combtrace> _groupsCensum; public: CPUModelResults(std::string modelName, cl_uint modelSize, cl_uint point_per_trace); CPUModelResults(const CPUModelResults &cpy) = delete; ~CPUModelResults(); void combineResults(std::vector<combtrace> &retgroupsMean,std::vector<combtrace> &retgroupsCensum); std::vector<combtrace> &groupsMean(); std::vector<combtrace> &groupsCensum(); }; #endif /* CPUModelResults_hpp */
844
301
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "mixerFvMesh.hpp" #include "Time.hpp" #include "regionSplit.hpp" #include "slidingInterface.hpp" #include "addToRunTimeSelectionTable.hpp" #include "mapPolyMesh.hpp" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace CML { defineTypeNameAndDebug(mixerFvMesh, 0); addToRunTimeSelectionTable(topoChangerFvMesh, mixerFvMesh, IOobject); } // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // void CML::mixerFvMesh::addZonesAndModifiers() { // Add zones and modifiers for motion action if ( pointZones().size() || faceZones().size() || cellZones().size() || topoChanger_.size() ) { Info<< "void mixerFvMesh::addZonesAndModifiers() : " << "Zones and modifiers already present. Skipping." << endl; return; } Info<< "Time = " << time().timeName() << endl << "Adding zones and modifiers to the mesh" << endl; // Add zones List<pointZone*> pz(1); // Add an empty zone for cut points pz[0] = new pointZone ( "cutPointZone", labelList(0), 0, pointZones() ); // Do face zones for slider List<faceZone*> fz(3); // Inner slider const word innerSliderName(motionDict_.subDict("slider").lookup("inside")); const polyPatch& innerSlider = boundaryMesh()[innerSliderName]; labelList isf(innerSlider.size()); forAll(isf, i) { isf[i] = innerSlider.start() + i; } fz[0] = new faceZone ( "insideSliderZone", isf, boolList(innerSlider.size(), false), 0, faceZones() ); // Outer slider const word outerSliderName(motionDict_.subDict("slider").lookup("outside")); const polyPatch& outerSlider = boundaryMesh()[outerSliderName]; labelList osf(outerSlider.size()); forAll(osf, i) { osf[i] = outerSlider.start() + i; } fz[1] = new faceZone ( "outsideSliderZone", osf, boolList(outerSlider.size(), false), 1, faceZones() ); // Add empty zone for cut faces fz[2] = new faceZone ( "cutFaceZone", labelList(0), boolList(0, false), 2, faceZones() ); List<cellZone*> cz(1); // Mark every cell with its topological region regionSplit rs(*this); // Get the region of the cell containing the origin. label originRegion = rs[findNearestCell(cs().origin())]; labelList movingCells(nCells()); label nMovingCells = 0; forAll(rs, cellI) { if (rs[cellI] == originRegion) { movingCells[nMovingCells] = cellI; nMovingCells++; } } movingCells.setSize(nMovingCells); Info<< "Number of cells in the moving region: " << nMovingCells << endl; cz[0] = new cellZone ( "movingCells", movingCells, 0, cellZones() ); Info<< "Adding point, face and cell zones" << endl; addZones(pz, fz, cz); // Add a topology modifier Info<< "Adding topology modifiers" << endl; topoChanger_.setSize(1); topoChanger_.set ( 0, new slidingInterface ( "mixerSlider", 0, topoChanger_, outerSliderName + "Zone", innerSliderName + "Zone", "cutPointZone", "cutFaceZone", outerSliderName, innerSliderName, slidingInterface::INTEGRAL ) ); topoChanger_.writeOpt() = IOobject::AUTO_WRITE; write(); } void CML::mixerFvMesh::calcMovingMasks() const { if (debug) { Info<< "void mixerFvMesh::calcMovingMasks() const : " << "Calculating point and cell masks" << endl; } if (movingPointsMaskPtr_) { FatalErrorInFunction << "point mask already calculated" << abort(FatalError); } // Set the point mask movingPointsMaskPtr_ = new scalarField(points().size(), 0); scalarField& movingPointsMask = *movingPointsMaskPtr_; const cellList& c = cells(); const faceList& f = faces(); const labelList& cellAddr = cellZones()["movingCells"]; forAll(cellAddr, cellI) { const cell& curCell = c[cellAddr[cellI]]; forAll(curCell, faceI) { // Mark all the points as moving const face& curFace = f[curCell[faceI]]; forAll(curFace, pointI) { movingPointsMask[curFace[pointI]] = 1; } } } const word innerSliderZoneName ( word(motionDict_.subDict("slider").lookup("inside")) + "Zone" ); const labelList& innerSliderAddr = faceZones()[innerSliderZoneName]; forAll(innerSliderAddr, faceI) { const face& curFace = f[innerSliderAddr[faceI]]; forAll(curFace, pointI) { movingPointsMask[curFace[pointI]] = 1; } } const word outerSliderZoneName ( word(motionDict_.subDict("slider").lookup("outside")) + "Zone" ); const labelList& outerSliderAddr = faceZones()[outerSliderZoneName]; forAll(outerSliderAddr, faceI) { const face& curFace = f[outerSliderAddr[faceI]]; forAll(curFace, pointI) { movingPointsMask[curFace[pointI]] = 0; } } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Construct from components CML::mixerFvMesh::mixerFvMesh ( const IOobject& io ) : topoChangerFvMesh(io), motionDict_ ( IOdictionary ( IOobject ( "dynamicMeshDict", time().constant(), *this, IOobject::MUST_READ_IF_MODIFIED, IOobject::NO_WRITE, false ) ).subDict(typeName + "Coeffs") ), csPtr_ ( coordinateSystem::New ( "coordinateSystem", motionDict_.subDict("coordinateSystem") ) ), rpm_(readScalar(motionDict_.lookup("rpm"))), movingPointsMaskPtr_(nullptr) { addZonesAndModifiers(); Info<< "Mixer mesh:" << nl << " origin: " << cs().origin() << nl << " axis: " << cs().axis() << nl << " rpm: " << rpm_ << endl; } // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // CML::mixerFvMesh::~mixerFvMesh() { deleteDemandDrivenData(movingPointsMaskPtr_); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // // Return moving points mask. Moving points marked with 1 const CML::scalarField& CML::mixerFvMesh::movingPointsMask() const { if (!movingPointsMaskPtr_) { calcMovingMasks(); } return *movingPointsMaskPtr_; } bool CML::mixerFvMesh::update() { // Rotational speed needs to be converted from rpm movePoints ( csPtr_->globalPosition ( csPtr_->localPosition(points()) + vector(0, rpm_*360.0*time().deltaTValue()/60.0, 0) *movingPointsMask() ) ); // Make changes. Use inflation (so put new points in topoChangeMap) autoPtr<mapPolyMesh> topoChangeMap = topoChanger_.changeMesh(true); if (topoChangeMap.valid()) { if (debug) { Info<< "Mesh topology is changing" << endl; } deleteDemandDrivenData(movingPointsMaskPtr_); } movePoints ( csPtr_->globalPosition ( csPtr_->localPosition(oldPoints()) + vector(0, rpm_*360.0*time().deltaTValue()/60.0, 0) *movingPointsMask() ) ); return true; } // ************************************************************************* //
8,884
2,902
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: W. Michael Brown (Intel) ------------------------------------------------------------------------- */ #include "npair_halffull_newton_intel.h" #include "neighbor.h" #include "neigh_list.h" #include "atom.h" #include "atom_vec.h" #include "comm.h" #include "modify.h" #include "molecule.h" #include "domain.h" #include "my_page.h" #include "error.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ NPairHalffullNewtonIntel::NPairHalffullNewtonIntel(LAMMPS *lmp) : NPair(lmp) { int ifix = modify->find_fix("package_intel"); if (ifix < 0) error->all(FLERR, "The 'package intel' command is required for /intel styles"); _fix = static_cast<FixIntel *>(modify->fix[ifix]); } /* ---------------------------------------------------------------------- build half list from full list pair stored once if i,j are both owned and i < j if j is ghost, only store if j coords are "above and to the right" of i works if full list is a skip list ------------------------------------------------------------------------- */ template <class flt_t, class acc_t> void NPairHalffullNewtonIntel::build_t(NeighList *list, IntelBuffers<flt_t,acc_t> *buffers) { const int inum_full = list->listfull->inum; const int nlocal = atom->nlocal; const int e_nall = nlocal + atom->nghost; const ATOM_T * _noalias const x = buffers->get_x(); int * _noalias const ilist = list->ilist; int * _noalias const numneigh = list->numneigh; int ** _noalias const firstneigh = list->firstneigh; const int * _noalias const ilist_full = list->listfull->ilist; const int * _noalias const numneigh_full = list->listfull->numneigh; const int ** _noalias const firstneigh_full = (const int ** const)list->listfull->firstneigh; #if defined(_OPENMP) #pragma omp parallel #endif { int tid, ifrom, ito; IP_PRE_omp_range_id(ifrom, ito, tid, inum_full, comm->nthreads); // each thread has its own page allocator MyPage<int> &ipage = list->ipage[tid]; ipage.reset(); // loop over parent full list for (int ii = ifrom; ii < ito; ii++) { int n = 0; int *neighptr = ipage.vget(); const int i = ilist_full[ii]; const flt_t xtmp = x[i].x; const flt_t ytmp = x[i].y; const flt_t ztmp = x[i].z; // loop over full neighbor list const int * _noalias const jlist = firstneigh_full[i]; const int jnum = numneigh_full[i]; #if defined(LMP_SIMD_COMPILER) #pragma vector aligned #pragma ivdep #endif for (int jj = 0; jj < jnum; jj++) { const int joriginal = jlist[jj]; const int j = joriginal & NEIGHMASK; int addme = 1; if (j < nlocal) { if (i > j) addme = 0; } else { if (x[j].z < ztmp) addme = 0; if (x[j].z == ztmp) { if (x[j].y < ytmp) addme = 0; if (x[j].y == ytmp && x[j].x < xtmp) addme = 0; } } if (addme) neighptr[n++] = joriginal; } ilist[ii] = i; firstneigh[i] = neighptr; numneigh[i] = n; int pad_end = n; IP_PRE_neighbor_pad(pad_end, 0); #if defined(LMP_SIMD_COMPILER) #pragma vector aligned #pragma loop_count min=1, max=INTEL_COMPILE_WIDTH-1, \ avg=INTEL_COMPILE_WIDTH/2 #endif for ( ; n < pad_end; n++) neighptr[n] = e_nall; ipage.vgot(n); if (ipage.status()) error->one(FLERR,"Neighbor list overflow, boost neigh_modify one"); } } list->inum = inum_full; } /* ---------------------------------------------------------------------- build half list from full 3-body list half list is already stored as first part of 3-body list ------------------------------------------------------------------------- */ template <class flt_t> void NPairHalffullNewtonIntel::build_t3(NeighList *list, int *numhalf) { const int inum_full = list->listfull->inum; const int e_nall = atom->nlocal + atom->nghost; int * _noalias const ilist = list->ilist; int * _noalias const numneigh = list->numneigh; int ** _noalias const firstneigh = list->firstneigh; const int * _noalias const ilist_full = list->listfull->ilist; const int * _noalias const numneigh_full = numhalf; const int ** _noalias const firstneigh_full = (const int ** const)list->listfull->firstneigh; int packthreads = 1; if (comm->nthreads > INTEL_HTHREADS) packthreads = comm->nthreads; #if defined(_OPENMP) #pragma omp parallel if(packthreads > 1) #endif { int tid, ifrom, ito; IP_PRE_omp_range_id(ifrom, ito, tid, inum_full, packthreads); // each thread has its own page allocator MyPage<int> &ipage = list->ipage[tid]; ipage.reset(); // loop over parent full list for (int ii = ifrom; ii < ito; ii++) { int n = 0; int *neighptr = ipage.vget(); const int i = ilist_full[ii]; // loop over full neighbor list const int * _noalias const jlist = firstneigh_full[i]; const int jnum = numneigh_full[ii]; #if defined(LMP_SIMD_COMPILER) #pragma vector aligned #pragma ivdep #endif for (int jj = 0; jj < jnum; jj++) { const int joriginal = jlist[jj]; neighptr[n++] = joriginal; } ilist[ii] = i; firstneigh[i] = neighptr; numneigh[i] = n; int pad_end = n; IP_PRE_neighbor_pad(pad_end, 0); #if defined(LMP_SIMD_COMPILER) #pragma vector aligned #pragma loop_count min=1, max=INTEL_COMPILE_WIDTH-1, \ avg=INTEL_COMPILE_WIDTH/2 #endif for ( ; n < pad_end; n++) neighptr[n] = e_nall; ipage.vgot(n); if (ipage.status()) error->one(FLERR,"Neighbor list overflow, boost neigh_modify one"); } } list->inum = inum_full; } /* ---------------------------------------------------------------------- */ void NPairHalffullNewtonIntel::build(NeighList *list) { if (_fix->three_body_neighbor() == 0) { if (_fix->precision() == FixIntel::PREC_MODE_MIXED) build_t(list, _fix->get_mixed_buffers()); else if (_fix->precision() == FixIntel::PREC_MODE_DOUBLE) build_t(list, _fix->get_double_buffers()); else build_t(list, _fix->get_single_buffers()); } else { int *nhalf, *cnum; if (_fix->precision() == FixIntel::PREC_MODE_MIXED) { _fix->get_mixed_buffers()->get_list_data3(list->listfull, nhalf, cnum); build_t3<float>(list, nhalf); } else if (_fix->precision() == FixIntel::PREC_MODE_DOUBLE) { _fix->get_double_buffers()->get_list_data3(list->listfull, nhalf, cnum); build_t3<double>(list, nhalf); } else { _fix->get_single_buffers()->get_list_data3(list->listfull, nhalf, cnum); build_t3<float>(list, nhalf); } } }
7,612
2,664
//-*-mode:c++; mode:font-lock;-*- /*! \file VSSimCoordTransform.hpp Perform coordinate transforms on simulation events. \author Matthew Wood \n UCLA \n mdwood@astro.ucla.edu \n \version 1.0 \date 09/11/2008 $Id: VSSimCoordTransform.hpp,v 3.1 2008/09/24 20:01:16 matthew Exp $ */ #ifndef VSSIMCOORDTRANSFORM_HPP #define VSSIMCOORDTRANSFORM_HPP #include <SphericalCoords.h> #include <VSOptions.hpp> namespace VERITAS { class VSSimCoordTransform { public: VSSimCoordTransform(const std::pair<double,double>& src_radec = s_default_src_radec, double wobble_phi_deg = s_default_wobble_phi_deg); virtual ~VSSimCoordTransform(); virtual void transform(SEphem::SphericalCoords& radec, unsigned corsika_particle_id, const SEphem::SphericalCoords& azzn, const SEphem::SphericalCoords& obs_azzn); virtual void setObsRADec(const SEphem::SphericalCoords& obs_radec) { m_obs_radec = obs_radec; } static void configure(VSOptions& options, const std::string& profile="", const std::string& opt_prefix=""); private: SEphem::SphericalCoords m_src_radec; SEphem::SphericalCoords m_obs_radec; double m_wobble_phi_rad; // Default options -------------------------------------------------------- static std::pair< double, double > s_default_src_radec; static double s_default_wobble_phi_deg; }; } // namespace VERITAS #endif // VSSIMCOORDTRANSFORM_HPP
1,584
597
/*! \file microfacet-inl.hpp \author Sho Ikeda Copyright (c) 2015-2018 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef NANAIRO_MICROFACET_INL_HPP #define NANAIRO_MICROFACET_INL_HPP #include "microfacet.hpp" // Standard C++ library #include <utility> // Zisc #include "zisc/error.hpp" #include "zisc/math.hpp" #include "zisc/utility.hpp" // Nanairo #include "fresnel.hpp" #include "NanairoCore/nanairo_core_config.hpp" #include "NanairoCore/Geometry/vector.hpp" #include "NanairoCore/Sampling/sampled_direction.hpp" namespace nanairo { /*! */ template <> inline Float Microfacet::SmithMicrosurface::evalG1( const Float roughness_x, const Float roughness_y, const Vector3& v, const Vector3& m_normal) noexcept { Float g1 = 0.0; const Float cos_nv = v[2]; const Float cos_mv = zisc::dot(m_normal, v); if (((0.0 <= cos_nv) && (0.0 <= cos_mv)) || ((cos_nv < 0.0) && (cos_mv < 0.0))) { const Float r2t2 = Microfacet::calcRoughness2Tan2(roughness_x, roughness_y, v); g1 = 2.0 / (1.0 + zisc::sqrt(1.0 + r2t2)); } ZISC_ASSERT(zisc::isInClosedBounds(g1, 0.0, 1.0), "GGX G1 isn't [0, 1]."); return g1; } /*! */ template <> inline Float Microfacet::SmithMicrosurface::evalG2( const Float roughness_x, const Float roughness_y, const Vector3& vin, const Vector3& vout, const Vector3& m_normal) noexcept { const Float g2 = evalG1(roughness_x, roughness_y, vin, m_normal) * evalG1(roughness_x, roughness_y, vout, m_normal); ZISC_ASSERT(zisc::isInClosedBounds(g2, 0.0, 1.0), "GGX G2 isn't [0, 1]."); return g2; } /*! \details No detailed. */ inline SampledDirection Microfacet::calcReflectionDirection( const Vector3& vin, const SampledDirection& sampled_m_normal) noexcept { ZISC_ASSERT(0.0 <= sampled_m_normal.inversePdf(), "The microfacet normal is negative."); // Calculate the reflection direction const auto& m_normal = sampled_m_normal.direction(); const auto vout = Fresnel::calcReflectionDirection(vin, m_normal); // Calculate the pdf of the direction const Float cos_mi = zisc::dot(m_normal, vin); const Float inverse_jacobian = calcReflectionInverseJacobian(cos_mi); ZISC_ASSERT(0.0 < inverse_jacobian, "The jacobian isn't negative."); const Float inverse_pdf = inverse_jacobian * sampled_m_normal.inversePdf(); return SampledDirection{vout, inverse_pdf}; } /*! \details No detailed. */ inline Vector3 Microfacet::calcReflectionHalfVector(const Vector3& vin, const Vector3& vout) noexcept { const auto half_vector = vin + vout; return half_vector.normalized(); } /*! \details No detailed. */ inline Float Microfacet::calcReflectionInverseJacobian(const Float cos_mi) noexcept { const Float inverse_jacobian = 4.0 * zisc::abs(cos_mi); ZISC_ASSERT(0.0 < inverse_jacobian, "Jacobian isn't positive."); return inverse_jacobian; } /*! \details n = n_transmission_side / n_incident_side */ inline SampledDirection Microfacet::calcRefractionDirection( const Vector3& vin, const SampledDirection& sampled_m_normal, const Float n, const Float g) noexcept { // Calculate the refraction direction const auto& m_normal = sampled_m_normal.direction(); const auto vout = Fresnel::calcRefractionDirection(vin, m_normal, n, g); // Calculate the pdf of the direction const Float cos_mi = zisc::dot(m_normal, vin); const Float cos_mo = zisc::dot(m_normal, vout); ZISC_ASSERT(zisc::isInBounds(-cos_mo, 0.0, 1.0), "cos_mo isn't [0, 1]."); const Float inverse_jacobian = calcRefractionInverseJacobian(cos_mi, cos_mo, n); const Float inverse_pdf = inverse_jacobian * sampled_m_normal.inversePdf(); ZISC_ASSERT(0.0 < inverse_pdf, "PDF isn't positive."); return SampledDirection{vout, inverse_pdf}; } /*! \details n = n_transmission_side / n_incident_side */ inline Vector3 Microfacet::calcRefractionHalfVector(const Vector3& vin, const Vector3& vout, const Float n) noexcept { ZISC_ASSERT(n != 1.0, "The relative index of refraction is 1."); const auto half = (1.0 < n) ? -(vin + n * vout) : (vin + n * vout); return half.normalized(); } /*! \details n = n_transmission_side / n_incident_side */ inline Float Microfacet::calcRefractionInverseJacobian(const Float cos_mi, const Float cos_mo, const Float n) noexcept { const Float tmp = cos_mi + n * cos_mo; const Float inverse_jacobian = zisc::power<2>(tmp) / (zisc::power<2>(n) * zisc::abs(cos_mo)); ZISC_ASSERT(0.0 < inverse_jacobian, "Jacobian isn't positive."); return inverse_jacobian; } /*! */ inline Float Microfacet::calcRoughness2Tan2(const Float roughness_x, const Float roughness_y, const Vector3& v) noexcept { ZISC_ASSERT(v[2] != 0.0, "The v[2] is zero."); const Float r2 = (zisc::power<2>(v[0]) * zisc::power<2>(roughness_x) + zisc::power<2>(v[1]) * zisc::power<2>(roughness_y)) / zisc::power<2>(v[2]); return r2; } } // namespace nanairo #endif // NANAIRO_MICROFACET_INL_HPP
5,526
2,024
#include <OpenGP/SurfaceMesh/SurfaceMesh.h> #include <OpenGP/SurfaceMesh/bounding_box.h> #include <OpenGP/GL/glfw_helpers.h> #include <OpenGP/GL/glfw_trackball.h> #include <OpenGP/GL/Eigen.h> #include <OpenGP/MLogger.h> using namespace OpenGP; using namespace std; /// Viewer global status SurfaceMesh mesh; std::vector<unsigned int> triangles; /// @todo Find a better place where to put it GLuint programID; /// Matrix stack Eigen::Matrix4f projection; Eigen::Matrix4f model; Eigen::Matrix4f view; void set_uniform_vector(GLuint programID, const char* NAME, const Eigen::Vector3f& vector){ GLuint matrix_id = glGetUniformLocation(programID, NAME); glUniform3fv(matrix_id, 1, vector.data()); } void set_uniform_matrix(GLuint programID, const char* NAME, const Eigen::Matrix4f& matrix){ GLuint matrix_id = glGetUniformLocation(programID, NAME); glUniformMatrix4fv(matrix_id, 1, GL_FALSE, matrix.data()); } void update_projection_matrix() { /// Define projection matrix (FOV, aspect, near, far) projection = OpenGP::perspective(45.0f, static_cast<float>(_width)/static_cast<float>(_height), 0.1f, 10.f); // cout << projection << endl; } /// OpenGL initialization void init(){ ///----------------------- DATA ---------------------------- auto vpoints = mesh.get_vertex_property<Vec3>("v:point"); auto vnormals = mesh.get_vertex_property<Vec3>("v:normal"); assert(vpoints); assert(vnormals); ///---------------------- TRIANGLES ------------------------ triangles.clear(); for(auto f: mesh.faces()) for(auto v: mesh.vertices(f)) triangles.push_back(v.idx()); ///---------------------- OPENGL GLOBALS-------------------- glClearColor(1.0f, 1.0f, 1.0f, 0.0f); ///< background glEnable(GL_DEPTH_TEST); // Enable depth test // glDisable(GL_CULL_FACE); // Cull back-facing /// Compile the shaders programID = load_shaders("vshader.glsl", "fshader.glsl"); if(!programID) exit(EXIT_FAILURE); glUseProgram( programID ); ///---------------------- CAMERA ---------------------------- { typedef Eigen::Vector3f vec3; typedef Eigen::Matrix4f mat4; update_projection_matrix(); /// Define the view matrix (camera extrinsics) vec3 cam_pos(0,0,5); vec3 cam_look(0,0,-1); /// Remember: GL swaps viewdir vec3 cam_up(0,1,0); view = OpenGP::lookAt(cam_pos, cam_look, cam_up); // cout << view << endl; /// Define the modelview matrix model = mat4::Identity(); // cout << model << endl; /// Set initial matrices set_uniform_matrix(programID,"M",model); ///< to get world coordinates set_uniform_matrix(programID,"MV",view*model); ///< to get camera coordinates set_uniform_matrix(programID,"MVP",projection*view*model); ///< to get clip coordinates } ///---------------------- LIGHT ----------------------------- { Vec3 light_dir(0,0,1); set_uniform_vector(programID,"LDIR",light_dir); ///< to get camera coordinates } ///---------------------- VARRAY ---------------------------- { GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); } ///---------------------- BUFFERS ---------------------------- GLuint vertexbuffer, normalbuffer, trianglebuffer; { /// Load mesh vertices glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, mesh.n_vertices() * sizeof(Vec3), vpoints.data(), GL_STATIC_DRAW); /// Load mesh normals glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, mesh.n_vertices() * sizeof(Vec3), vnormals.data(), GL_STATIC_DRAW); /// Triangle indexes buffer glGenBuffers(1, &trianglebuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, trianglebuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, triangles.size() * sizeof(unsigned int), &triangles[0], GL_STATIC_DRAW); } ///---------------------- SHADER ATTRIBUTES ---------------------------- { /// Vertex positions in shader variable "vposition" GLuint vposition = glGetAttribLocation(programID, "vposition"); glEnableVertexAttribArray(vposition); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(vposition, 3, GL_FLOAT, DONT_NORMALIZE, ZERO_STRIDE, ZERO_BUFFER_OFFSET); /// Vertex normals in in shader variable "vnormal" GLuint vnormal = glGetAttribLocation(programID, "vnormal"); glEnableVertexAttribArray(vnormal); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer(vnormal, 3, GL_FLOAT, DONT_NORMALIZE, ZERO_STRIDE, ZERO_BUFFER_OFFSET); } } /// void update_matrices(Eigen::Matrix4f model){ set_uniform_matrix(programID,"M",model); set_uniform_matrix(programID,"MV",view*model); set_uniform_matrix(programID,"MVP",projection*view*model); } /// OpenGL render loop void display(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawElements(GL_TRIANGLES, triangles.size(), GL_UNSIGNED_INT, ZERO_BUFFER_OFFSET); } /// Entry point int main(int argc, char** argv){ if(argc!=2) mFatal("usage: glfwviewer bunny.obj"); int success = mesh.read(argv[1]); if(!success) mFatal() << "File not found"; mesh.triangulate(); mesh.update_vertex_normals(); cout << "input: '" << argv[1] << "' num vertices " << mesh.vertices_size() << endl; cout << "BBOX: " << bounding_box(mesh) << endl; glfwInitWindowSize(_width, _height); if (glfwMakeWindow(__FILE__) == EXIT_FAILURE) return EXIT_FAILURE; glfwDisplayFunc(display); glfwTrackball(update_matrices, update_projection_matrix); init(); glfwMainLoop(); return EXIT_SUCCESS; }
6,104
2,019
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/chime-sdk-identity/model/EndpointStatusReason.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ChimeSDKIdentity { namespace Model { namespace EndpointStatusReasonMapper { static const int INVALID_DEVICE_TOKEN_HASH = HashingUtils::HashString("INVALID_DEVICE_TOKEN"); static const int INVALID_PINPOINT_ARN_HASH = HashingUtils::HashString("INVALID_PINPOINT_ARN"); EndpointStatusReason GetEndpointStatusReasonForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == INVALID_DEVICE_TOKEN_HASH) { return EndpointStatusReason::INVALID_DEVICE_TOKEN; } else if (hashCode == INVALID_PINPOINT_ARN_HASH) { return EndpointStatusReason::INVALID_PINPOINT_ARN; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<EndpointStatusReason>(hashCode); } return EndpointStatusReason::NOT_SET; } Aws::String GetNameForEndpointStatusReason(EndpointStatusReason enumValue) { switch(enumValue) { case EndpointStatusReason::INVALID_DEVICE_TOKEN: return "INVALID_DEVICE_TOKEN"; case EndpointStatusReason::INVALID_PINPOINT_ARN: return "INVALID_PINPOINT_ARN"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace EndpointStatusReasonMapper } // namespace Model } // namespace ChimeSDKIdentity } // namespace Aws
2,224
654
// Copyright 2017 Rainer Gemulla // // 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. /* * ioProjected_impl.h * * Created on: Jul 14, 2011 * Author: chteflio */ #include <boost/foreach.hpp> #include <boost/filesystem.hpp> #include <mf/matrix/io/ioProjected.h> #include <mf/matrix/io/read.h> #include <mf/matrix/io/write.h> namespace mf { void writeMapFile(const std::string& file,const std::vector<mf_size_type>& map, mf_size_type size){ LOG4CXX_INFO(detail::logger, "Writing map file: " << file); std::ofstream out(file.c_str()); if (!out.is_open()) RG_THROW(rg::IOException, std::string("Cannot open file ") + file); // write dimension line out << map.size() << " " << size <<std::endl; mf_size_type i=0; // write elements BOOST_FOREACH( mf_size_type element, map) { out <<(i+1)<<" "<<(element+1)<<std::endl; i++; } // done out.close(); } void readMapFile(const std::string& file, std::vector<mf_size_type>& map, mf_size_type& size){ LOG4CXX_INFO(detail::logger, "Reading map file: " << file); // open file std::ifstream in(file.c_str()); if (!in.is_open()) RG_THROW(rg::IOException, std::string("Cannot open file ") + file); std::string line; mf_size_type projectedSize; if (!getline(in, line)) RG_THROW(rg::IOException, std::string("Unexpected EOF in file ") + file); // read 1st line, which contains the dimensions of sample and original matrix if (sscanf(line.c_str(), "%ld %ld", &projectedSize, &size) != 2) RG_THROW(rg::IOException, std::string("Invalid vector dimensions in file ") + file); // initialize the vector of indexes map.reserve(projectedSize); // read matrix for (mf_size_type p=0; p<projectedSize; p++){ if (!getline(in, line)) RG_THROW(rg::IOException, std::string("Unexpected EOF in file ") + file); mf_size_type indSample, indOriginal; if (sscanf(line.c_str(), "%ld %ld", &indSample, &indOriginal) != 2) RG_THROW(rg::IOException, std::string("Invalid index entry in file ") + file); map.push_back(indOriginal-1); // row1 should map to array[0] } // done in.close(); } void writeProjectedMatrix(const ProjectedSparseMatrix& projectedMatrix, const IndexMapFileDescriptor& mapDescriptor){ LOG4CXX_INFO(detail::logger, "Writing projected matrix & map files: " << mapDescriptor.completeProjectedMatrixFilename() << " & " << mapDescriptor.completeMap1Filename() << ", " << mapDescriptor.completeMap2Filename() ); writeMatrix(mapDescriptor.completeProjectedMatrixFilename(), projectedMatrix.data); writeMapFile(mapDescriptor.completeMap1Filename(), projectedMatrix.map1, projectedMatrix.size1); writeMapFile(mapDescriptor.completeMap2Filename(), projectedMatrix.map2, projectedMatrix.size2); } void readProjectedMatrix(ProjectedSparseMatrix& projectedMatrix, const std::string& projectedMatrixFilename, const std::string& map1Filename, const std::string& map2Filename){ readMatrix(projectedMatrixFilename, projectedMatrix.data); readMapFile(map1Filename, projectedMatrix.map1, projectedMatrix.size1); readMapFile(map2Filename, projectedMatrix.map2, projectedMatrix.size2); } void readProjectedMatrix(ProjectedSparseMatrix& projectedMatrix, const std::string& indexMapDescriptorFilename){ IndexMapFileDescriptor mapDescriptor; mapDescriptor.load(indexMapDescriptorFilename); readProjectedMatrix(projectedMatrix, mapDescriptor.completeProjectedMatrixFilename(), mapDescriptor.completeMap1Filename(), mapDescriptor.completeMap2Filename()); } }
4,016
1,385
//! \file PdbCompilandStream.cpp //! \brief PDB compiland stream. //! \author Oleg Krivtsov //! \date 2011 #include "stdafx.h" #include "PdbCompilandStream.h" #include "PdbDebugInfoStream.h" #include "Buffer.h" #include "strconv.h" #include "PdbStreamStruct.h" #include "PdbReader.h" CPdbCompilandStream::CPdbCompilandStream() : CPdbSymbolStream() { m_bInitialized = FALSE; m_nModuleIndex = -1; m_dwCompilandType = 0; } CPdbCompilandStream::CPdbCompilandStream(CPdbReader* pPdbReader, CMsfStream* pStream, DBI_ModuleInfo* pModuleInfo, BOOL* pbResult) { *pbResult = Init(pPdbReader, pStream, pModuleInfo); } CPdbCompilandStream::~CPdbCompilandStream() { Destroy(); } BOOL CPdbCompilandStream::Init(CPdbReader* pPdbReader, CMsfStream* pStream, DBI_ModuleInfo* pModuleInfo) { //! PDB compiland stream (stream number >=10) //! The stream has the following structure: //! 1. Header including compiland name (variable length). //! 2. Subheader followed by array of zero-terminated string pairs. //! The first string in a pair defines property name, the second one defines property value. //! 3. Symbol section follows (array of symbol records, as in stream #8). The size of this section can be determined from appropriate DBI stream's MODI record. //! 4. C13 Line numbers section follows. Size of this section can be determined from MODI record. //! 4.1. DWORD - maybe count or signature, or segment? //! 4.2. [DWORD - 16 byte] sequences (DWORD+16 byte checksum) //! 5. Some section follows. Leading 4 bytes is the size (size doesn't include 4 bytes). BOOL bResult=FALSE; DWORD dwOffs = 0; std::string str; std::string sParamName; int nCount = -1; DWORD dwLen = 0; DWORD dwLineSectionStart = 0; BOOL bBlocks = TRUE; // Reset stream pos pStream->SetStreamPos(0); // Allocate buffer for the entire stream DWORD dwStreamLen = pStream->GetStreamLen(); CBuffer buf(dwStreamLen); DWORD dwBytesRead = 0; BOOL bRead = pStream->ReadData(buf, dwStreamLen, &dwBytesRead, FALSE); if(!bRead || dwBytesRead!=dwStreamLen) goto cleanup; // Save module index m_nModuleIndex = pModuleInfo->m_nModuleIndex; // Read compiland type m_dwCompilandType = *(LPDWORD)buf.GetPtr(); if(m_dwCompilandType == CT_RESFILE) { // Resource file bResult = true; goto cleanup; } else if(m_dwCompilandType != CT_OBJMODULE) { // Invalid compiland type goto cleanup; } // // Read symbols following the header. // if((LONG)dwOffs<pModuleInfo->m_Info.cbSymbols) { if(!CPdbSymbolStream::Init(pPdbReader, pStream, 4, pModuleInfo->m_Info.cbSymbols-4, &dwOffs)) goto cleanup; } // // Read source file checksums and line numbers // // Read source checksum header //dwOffs = pModuleInfo->m_Info.cbSymbols; pStream->SetStreamPos(dwOffs); while(bBlocks) { BLOCK_HEADER_32 BlockHeader; bRead = pStream->ReadData((LPBYTE)&BlockHeader, sizeof(BLOCK_HEADER_32), &dwBytesRead, FALSE); if(!bRead || dwBytesRead!=sizeof(BLOCK_HEADER_32)) { // End of file reached bResult = true; goto cleanup; } switch(BlockHeader.dwBlockType) { case 0xF4: // Source file checksums { dwLineSectionStart = pStream->GetStreamPos(); BLOCK_HEADER_32 SrcChecksumHeader; bRead = pStream->ReadData((LPBYTE)&SrcChecksumHeader, sizeof(BLOCK_HEADER_32), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(BLOCK_HEADER_32)) { // It seems there is no source checsums bResult = true; goto cleanup; } assert(SrcChecksumHeader.dwBlockType==0xF4); dwOffs = 0; // Read source file checksums int i; for(i=0; dwOffs<SrcChecksumHeader.dwLength; i++) { SOURCE_CHECKSUM sc; bRead = pStream->ReadData((LPBYTE)&sc, sizeof(SOURCE_CHECKSUM), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(SOURCE_CHECKSUM)) { goto cleanup; } DWORD dwChecksumOffs = dwOffs; dwOffs += sizeof(SOURCE_CHECKSUM); SrcChecksum src_checksum; src_checksum.m_Info = sc; if(sc.wCheckSumType==CHECKSUM_MD5) { src_checksum.m_CheckSum.Allocate(16); bRead = pStream->ReadData((LPBYTE)src_checksum.m_CheckSum, 16, &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=16) goto cleanup; LPBYTE pCheckSum = src_checksum.m_CheckSum.GetPtr(); char szCheckSum[128] = ""; #ifdef _WIN32 sprintf_s( szCheckSum, 128, "0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x", pCheckSum[0], pCheckSum[1], pCheckSum[2], pCheckSum[3], pCheckSum[4], pCheckSum[5], pCheckSum[6], pCheckSum[7], pCheckSum[8], pCheckSum[9], pCheckSum[10], pCheckSum[11], pCheckSum[12], pCheckSum[13], pCheckSum[14], pCheckSum[15]); #else sprintf( szCheckSum, "0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x", pCheckSum[0], pCheckSum[1], pCheckSum[2], pCheckSum[3], pCheckSum[4], pCheckSum[5], pCheckSum[6], pCheckSum[7], pCheckSum[8], pCheckSum[9], pCheckSum[10], pCheckSum[11], pCheckSum[12], pCheckSum[13], pCheckSum[14], pCheckSum[15]); #endif src_checksum.m_sCheckSum = szCheckSum; dwOffs += 16; } dwOffs += 2; // skip padding bytes pStream->SetStreamPosRel(2); m_aSrcChecksums.push_back(src_checksum); m_aSrcChecksumOffsets[dwChecksumOffs] = m_aSrcChecksums.size()-1; } } break; case 0xF2: // Line numbers { SymbolLines SymLines; // Read symbol lines header SYMBOL_LINES sl; bRead = pStream->ReadData((LPBYTE)&sl, sizeof(SYMBOL_LINES), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(SYMBOL_LINES)) goto cleanup; SymLines.m_Header = sl; dwOffs = sizeof(SYMBOL_LINES)-8; // Read line addresses following the header for(;dwOffs<sl.Header.dwLength;) { LINE_ADDRESS la; bRead = pStream->ReadData((LPBYTE)&la, sizeof(LINE_ADDRESS), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(LINE_ADDRESS)) goto cleanup; SymLines.m_Lines.push_back(la); dwOffs += sizeof(LINE_ADDRESS); } m_aSrcLines.push_back(SymLines); } break; default: bBlocks = FALSE; break; } } // Read the last strange section (possibly relocations or OMAP) // Read section length DWORD bRead = pStream->ReadData((LPBYTE)&dwLen, sizeof(DWORD), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(DWORD)) goto cleanup; // Read DWORDs following the header nCount = dwLen/sizeof(DWORD); int i; for(i=0; i<nCount; i++) { DWORD dwNumber = 0; bRead = pStream->ReadData((LPBYTE)&dwNumber, sizeof(DWORD), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(DWORD)) goto cleanup; m_aNumbers.push_back(dwNumber); } bResult=TRUE; cleanup: m_bInitialized = bResult; return bResult; } void CPdbCompilandStream::Destroy() { // Destroy parent CPdbSymbolStream::Destroy(); m_aNumbers.clear(); m_aSrcLines.clear(); m_aSrcChecksumOffsets.clear(); m_aSrcChecksums.clear(); } DWORD CPdbCompilandStream::GetCompilandType() { return m_dwCompilandType; } int CPdbCompilandStream::GetSrcFileCheckSumCount() { return (int)m_aSrcChecksums.size(); } SrcChecksum* CPdbCompilandStream::GetSrcFileCheckSum(int nIndex) { if(nIndex<0 || nIndex>=(int)m_aSrcChecksums.size()) return NULL; return &m_aSrcChecksums[nIndex]; } int CPdbCompilandStream::GetSrcFileCheckSumIndexByOffs(DWORD dwOffs) { std::map<DWORD, size_t>::iterator it = m_aSrcChecksumOffsets.find(dwOffs); if(it==m_aSrcChecksumOffsets.end()) return -1; // Not found such offset return (int)it->second; } int CPdbCompilandStream::GetSymbolLineCount() { return (int)m_aSrcLines.size(); } SymbolLines* CPdbCompilandStream::GetSymbolLines(int nIndex) { return &m_aSrcLines[nIndex]; } bool CPdbCompilandStream::FindSrcFileAndLineByAddr(DWORD64 dwAddr, std::wstring& sFileName, int& nLineNumber, DWORD& dwOffsInLine) { sFileName = L""; nLineNumber = -1; CPdbDebugInfoStream* pDBI = m_pPdbReader->GetDebugInfoStream(); CPdbSectionMapStream* pSectionMap = m_pPdbReader->GetSectionMapStream(); size_t i; for(i=0; i<m_aSrcLines.size(); i++) { // Get section start address SymbolLines& lines = m_aSrcLines[i]; IMAGE_SECTION_HEADER* pSecHdr = pSectionMap->GetSection(lines.m_Header.dwSegment-1); if(!pSecHdr) continue; // Get RVA and size of this section contribution DWORD dwStart = pSecHdr->VirtualAddress + lines.m_Header.dwOffset; DWORD dwSize = lines.m_Header.dwSectionContribLen; // Check if user-provided address belongs to this section contribution if(dwStart<=dwAddr && dwAddr<dwStart+dwSize) { int nCheckSumIndex = GetSrcFileCheckSumIndexByOffs(lines.m_Header.dwSrcCheckSumOffs); SrcChecksum* pChecksum = GetSrcFileCheckSum(nCheckSumIndex); assert(pChecksum); int nFileNameIndex = pDBI->FindSrcFileNameByModule(m_nModuleIndex, nCheckSumIndex); if(nFileNameIndex>=0) { sFileName = pDBI->GetSrcFileName(nFileNameIndex); } // Get line number DWORD dwOffs = (DWORD)dwAddr-dwStart; int j; for(j=(int)lines.m_Lines.size()-1; j>=0; j--) { LINE_ADDRESS& line = lines.m_Lines[j]; if(dwOffs<line.dwOffset) continue; nLineNumber = line.wNumber; dwOffsInLine = dwOffs-line.dwOffset; break; } return true; } } // No source file information found return false; }
11,233
3,921
// Copyright (c) 2007-2009 Google Inc. // Copyright (c) 2006-2007 Jaiku Ltd. // Copyright (c) 2002-2006 Mika Raento and Renaud Petit // // This software is licensed at your choice under either 1 or 2 below. // // 1. MIT License // // 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. // // 2. Gnu General Public license 2.0 // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // // This file is part of the JaikuEngine mobile client. #include "cu_cellnaming.h" #include "app_context_impl.h" #include "cbbsession.h" #include "csd_event.h" #include "emptytext.h" #include "csd_cell.h" #include "break.h" #include "cu_common.h" #include "csd_cellnaming.h" #include "csd_base.h" #include "reporting.h" #include "AknNotifyStd.h" #include <aknnotewrappers.h> #include <bautils.h> #include <coeaui.h> #include <contextui.rsg> #include <eikenv.h> #include "contextvariant.hrh" void CheckPredicatesL() { if ( ((CCoeAppUi*)CEikonEnv::Static()->AppUi())->IsDisplayingMenuOrDialog()) return; MApp_context* c=GetContext(); TApaTaskList tl(CEikonEnv::Static()->WsSession()); TApaTask app_task=tl.FindApp( KUidcontext_log ); if (! app_task.Exists() ) { //FIXMELOC c->Reporting().ShowGlobalNote(EAknGlobalErrorNote , _L("Jaiku Settings is not running. Location naming requires Jaiku Settings.")); return; } } HBufC* GetTupleValueL(const TTupleName& aNameTuple) { CBBSession* bbsession=GetContext()->BBSession(); MBBData* name_event_m=0; bbsession->GetL(aNameTuple, KNullDesC, name_event_m, ETrue); bb_auto_ptr<MBBData> eventp(name_event_m); const CBBSensorEvent* name_event=bb_cast<CBBSensorEvent>(name_event_m); const TBBFixedLengthStringBase* existing_name=0; if (name_event) { existing_name=bb_cast<TBBShortString>(name_event->iData()); if (!existing_name) existing_name=bb_cast<TBBLongString>(name_event->iData()); } if (existing_name) return existing_name->Value().AllocL(); else return NULL; } TInt GetBaseIdL(const TTupleName& aNameTuple) { CBBSession* bbsession=GetContext()->BBSession(); TInt baseid=-1; TTime base_event_t(0); if (aNameTuple==KCellNameTuple) { MBBData *base_event_d=0; bbsession->GetL(KLocationTuple, KNullDesC, base_event_d, ETrue); bb_auto_ptr<MBBData> p(base_event_d); const CBBSensorEvent *ev=bb_cast<CBBSensorEvent>(base_event_d); if (ev) { const TBBLocation* c=bb_cast<TBBLocation>(ev->iData()); if (c && c->iIsBase()) { base_event_t=ev->iStamp(); baseid=c->iLocationId(); } } } TBool no_coverage=EFalse; { MBBData *cell_event_d=0; bbsession->GetL(KCellIdTuple, KNullDesC, cell_event_d, ETrue); bb_auto_ptr<MBBData> p(cell_event_d); const CBBSensorEvent *ev=bb_cast<CBBSensorEvent>(cell_event_d); if (!ev) return KErrNotFound; const TBBCellId* c=bb_cast<TBBCellId>(ev->iData()); if (!c) return KErrNotFound; if (c->iLocationAreaCode()==0 && c->iCellId()==0) { no_coverage=ETrue; //FIXMELOC return KErrNotFound; // no coverage } if (baseid==-1 || ev->iStamp() > base_event_t) { baseid=c->iMappedId(); } } return baseid; } void StoreTupleL(const TTupleName& aNameTuple, const TTupleName& aGivenNameTuple, const TDesC& aNameName, const TDesC& aValue, TInt aBaseId) { TTime exp=GetTime(); exp+=TTimeIntervalMinutes(10); bb_auto_ptr<CBBSensorEvent> e(new (ELeave) CBBSensorEvent(aNameName, aGivenNameTuple, GetContext()->BBDataFactory(), GetTime())); e->iData.SetOwnsValue(EFalse); if (aNameTuple==KCellNameTuple) { TBBCellNaming name; name.iMappedId=aBaseId; name.iName()=aValue; e->iData.SetValue(&name); GetContext()->BBSession()->PutL(aGivenNameTuple, KNullDesC, e.get(), exp); } else { TBBLongString name(aValue, aNameName); e->iData.SetValue(&name); GetContext()->BBSession()->PutL(aGivenNameTuple, KNullDesC, e.get(), exp); } } #ifdef __DEV__ #include "reporting.h" void DebugLog(const TDesC& aMsg) { GetContext()->Reporting().DebugLog(aMsg); } #else inline void DebugLog(const TDesC&) { } #endif class CEmptyAllowingMultiLineDataQueryDialog : public CAknMultiLineDataQueryDialog { public: CEmptyAllowingMultiLineDataQueryDialog() : CAknMultiLineDataQueryDialog(ENoTone) { } void ConstructL(TDes& aDataText, TDes& aDataText2) { SetDataL(aDataText, aDataText2); } static CEmptyAllowingMultiLineDataQueryDialog* NewL(TDes& aDataText, TDes& aDataText2) { auto_ptr<CEmptyAllowingMultiLineDataQueryDialog> ret(new (ELeave) CEmptyAllowingMultiLineDataQueryDialog); ret->ConstructL(aDataText, aDataText2); return ret.release(); } void UpdateLeftSoftKeyL() { MakeLeftSoftkeyVisible(ETrue); } TKeyResponse OfferKeyEventL (const TKeyEvent &aKeyEvent, TEventCode aType) { return CAknMultiLineDataQueryDialog::OfferKeyEventL(aKeyEvent, aType); } }; void NameLocationL() { DebugLog(_L("CheckPredicatesL")); CheckPredicatesL(); const TInt KMaxLen(BB_LONGSTRING_MAXLEN); auto_ptr<HBufC> hood(HBufC::NewL(KMaxLen)); auto_ptr<HBufC> hoodOld( GetTupleValueL( KCellNameTuple ) ); if (hoodOld.get()) hood->Des() = *hoodOld; TBool no_coverage = EFalse; DebugLog(_L("GetBaseIdL")); TInt baseid = GetBaseIdL( KCellNameTuple ); if ( baseid == KErrNotFound ) { no_coverage = ETrue; } auto_ptr<HBufC> city(HBufC::NewL(KMaxLen)); auto_ptr<HBufC> cityOld( GetTupleValueL( KCityNameTuple ) ); if (cityOld.get()) city->Des() = *cityOld; if ( no_coverage ) { DebugLog(_L("no coverage")); _LIT(KNoCoverageNote, "No network coverage. Location naming is not possible."); CAknInformationNote* note = new (ELeave) CAknInformationNote( ETrue ); //Waiting note->ExecuteLD(KNoCoverageNote); //Blocks until } else { DebugLog(_L("ask name")); TPtr hoodP = hood->Des(); TPtr cityP = city->Des(); CEmptyAllowingMultiLineDataQueryDialog* dlg = CEmptyAllowingMultiLineDataQueryDialog::NewL(hoodP, cityP); dlg->SetPredictiveTextInputPermitted( ETrue ); if (dlg->ExecuteLD(R_LOCATION_NAME_QUERY) && ! no_coverage ) { TBool cityModified = ( ! cityOld.get() ) || (cityOld->Compare(*city) != 0); TBool hoodModified = ( ! hoodOld.get() ) || (hoodOld->Compare(*hood) != 0); if (hoodModified) StoreTupleL( KCellNameTuple, KGivenCellNameTuple, KCellName, *hood, baseid); if (cityModified) StoreTupleL( KCityNameTuple, KGivenCityNameTuple, KCity, *city, baseid); } } } void name_cellL(const TTupleName& aNameTuple, const TTupleName& aGivenNameTuple, const TDesC& aNameName) { CheckPredicatesL(); const TInt NAME_LENGTH=255; auto_ptr<HBufC> textData(HBufC::NewL(NAME_LENGTH)); auto_ptr<HBufC> existing_name( GetTupleValueL( aNameTuple ) ); if (existing_name.get()) textData->Des() = *existing_name; TBool no_coverage = EFalse; TInt baseid = GetBaseIdL( aNameTuple ); if ( baseid == KErrNotFound ) { _LIT(KNoCoverage, "[no coverage]"); textData->Des() = KNoCoverage; no_coverage = ETrue; } TPtr16 p=textData->Des(); auto_ptr<HBufC> f(0); if (aNameTuple==KCellNameTuple) { f.reset(CEikonEnv::Static()->AllocReadResourceL(R_CL_NAME_OLD_CELL_CAPTION)); } else { // city f.reset(CEikonEnv::Static()->AllocReadResourceL(R_CL_NAME_OLD_CITY_CAPTION)); } auto_ptr<HBufC> pr(HBufC::NewL(f->Des().Length()+4)); pr->Des()=*f; CAknTextQueryDialog* dlg = new(ELeave) CEmptyAllowingTextQuery(p); CleanupStack::PushL(dlg); dlg->SetMaxLength(NAME_LENGTH); dlg->SetPromptL(*pr); CleanupStack::Pop(); TInt resource=R_CONTEXT_LOG_NAME_INPUT; if (no_coverage) resource=R_CONTEXT_LOG_NAME_INPUT_READONLY; dlg->SetPredictiveTextInputPermitted(ETrue); if (dlg->ExecuteLD(resource) && textData->Length() && !no_coverage) { if (existing_name.get() && existing_name->Compare(*textData)==0) return; StoreTupleL( aNameTuple, aGivenNameTuple, aNameName, *textData, baseid); } } TInt LoadResourceFileL() { return LoadSystemResourceL(CEikonEnv::Static(), _L("contextui")); } EXPORT_C void AskUserForCurrentCellNameL() { TInt res=LoadResourceFileL(); CC_TRAPD(err, name_cellL(KCellNameTuple, KGivenCellNameTuple, KCellName)); if (res) CEikonEnv::Static()->DeleteResourceFile(res); User::LeaveIfError(err); } EXPORT_C void AskUserForCurrentCityNameL() { TInt res=LoadResourceFileL(); CC_TRAPD(err, name_cellL(KCityNameTuple, KGivenCityNameTuple, KCity)); if (res) CEikonEnv::Static()->DeleteResourceFile(res); User::LeaveIfError(err); } EXPORT_C void AskUserForCurrentLocationL() { TInt res=LoadResourceFileL(); CC_TRAPD(err, NameLocationL()); if (res) CEikonEnv::Static()->DeleteResourceFile(res); User::LeaveIfError(err); }
10,277
4,174
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mir/Shape.h" #include <algorithm> #include <cassert> #include <sstream> namespace mir { constexpr int32_t mir::Shape::autoDim; void Shape::resize(int32_t size) { _dims.resize(size); } int32_t Shape::numElements() const { int32_t res = 1; for (int32_t axis = 0; axis < rank(); ++axis) { assert(dim(axis) != Shape::autoDim); res *= dim(axis); } return res; } Shape broadcastShapes(const Shape &lhs_shape, const Shape &rhs_shape) { const int num_dims = std::max(lhs_shape.rank(), rhs_shape.rank()); Shape result_shape(num_dims); for (int i = 0; i < num_dims; ++i) { const std::int32_t lhs_dim = (i >= num_dims - lhs_shape.rank()) ? lhs_shape.dim(i - (num_dims - lhs_shape.rank())) : 1; const std::int32_t rhs_dim = (i >= num_dims - rhs_shape.rank()) ? rhs_shape.dim(i - (num_dims - rhs_shape.rank())) : 1; if (lhs_dim == 1) { result_shape.dim(i) = rhs_dim; } else { assert(rhs_dim == 1 || rhs_dim == lhs_dim); result_shape.dim(i) = lhs_dim; } } return result_shape; } std::string toString(const Shape &shape) { std::stringstream ss; ss << "["; for (int32_t axis = 0; axis < shape.rank(); ++axis) { if (axis != 0) ss << ", "; if (shape.dim(axis) == Shape::autoDim) ss << "AUTO"; else ss << shape.dim(axis); } ss << "]"; return ss.str(); } } // namespace mir
2,055
783
#include "I.hpp" #include "T.hpp" using namespace std; int main() { }
71
31
#include "File.h"
17
8
/* * ResetableObject.cpp * * Created on: Oct 29, 2014 * Author: ricardo */ #include "ResetableObject.h" ResetableObject::ResetableObject() : DynamicObject() { this->setAlive(false); this->_resetTime = rand() % 10; } ResetableObject::~ResetableObject() { } void ResetableObject::resetPosition() { this->setPosition(this->_resetPosition); } void ResetableObject::die() { this->resetPosition(); this->setAlive(false); this->_resetTime = rand() % 10; } void ResetableObject::respawn() { this->resetPosition(); this->setAlive(true); } void ResetableObject::updateResetTime() { this->_resetTime--; }
656
232
#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include "shape.hpp" #include <glm/vec3.hpp> #include "box.hpp" #include "sphere.hpp" #include "color.hpp" #include "scene.hpp" #include "scene.cpp" #include <string> #include <sstream> TEST_CASE ("rec", "[rec]"){ glm::vec3 origin {0.f, 0.f, 0.f}; glm::vec3 corner1 {2.f, 2.f, 2.f}; Color color{0.f, 0.f, 0.f}; float z = 2; Material m1 = {"Holz", color, 0.f, 0.f, 0.f, 2}; std::shared_ptr<Material> c1 = std::make_shared<Material>(Material{}); Box b1 {origin,corner1,"KASTEN",c1}; REQUIRE(b1.area()==16); REQUIRE(b1.volume()==8); std::cout<<b1; } TEST_CASE ("sph", "[sph]"){ glm::vec3 origin {0.f, 0.f, 0.f}; std::shared_ptr<Material> c1 = std::make_shared<Material>(Material{}); Sphere s1 {origin, 4.f,"KREIS", c1}; REQUIRE(round(s1.area())==201); REQUIRE(round(s1.volume())==268); std::cout<<s1; } #include <glm/glm.hpp> #include <glm/gtx/intersect.hpp> TEST_CASE ("intersect_ray_sphere", "[intersect]") { // Ray glm::vec3 ray_origin {0.0f, 0.0f, 0.0f}; // ray direction has to be normalized ! // you can use : //v = glm::normalize (some_vector) glm::vec3 ray_direction{0.0f ,0.0f, 1.0f}; // Sphere glm::vec3 sphere_center{0.0f, 0.0f, 5.0f}; float sphere_radius {1.0f}; float distance = 0.0f; auto result = glm::intersectRaySphere( ray_origin, ray_direction , sphere_center , sphere_radius * sphere_radius , // squared radius !!! distance); REQUIRE(distance == Approx(4.0f)); glm::vec3 origin {8.f, 0.f, 0.f}; std::shared_ptr<Material> c1 = std::make_shared<Material>(Material{}); Sphere s1 {origin, 5.f,"KREIS", c1}; glm::vec3 rayo{0.0f, 0.0f, 0.0f}; glm::vec3 rayd{1.f, 0.f, 0.f}; Ray testray{rayo, rayd}; float t = 2; } TEST_CASE ("delete", "[delete]") { glm::vec3 origin {8.f, 0.f, 0.f}; std::shared_ptr<Material> red = std::make_shared<Material>(Material{}); Sphere* s1 =new Sphere{origin, 5.f,"sphere0", red}; Shape* s2 =new Sphere{origin, 5.f,"sphere1", red}; delete s1; delete s2; } TEST_CASE ("squareint", "[intersect]"){ glm::vec3 origin {1.f, 1.f, 1.f}; glm::vec3 corner1 {4.f, 4.f, 4.f}; std::shared_ptr<Material> c1 = std::make_shared<Material>(Material{}); Box b1 {origin,corner1,"BOX",c1}; glm::vec3 rayo{0.0f, 0.0f, 0.0f}; glm::vec3 rayd{1.f, 1.f, 1.f}; glm::vec3 rayc{1.f, 0.f, 1.f}; Ray testray2{rayo, rayc}; Ray testray{rayo, rayd}; float t = 1; REQUIRE(b1.intersect(testray, t).cut_); REQUIRE(!b1.intersect(testray2, t).cut_); } TEST_CASE ("tostruc", "[tostruc]"){ std::string path = "/home/vincent/Dokumente/programmiersprachen-raytracer/source/material.sdf"; Scene S {createscene(path)}; } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); }
2,767
1,316
#include <stdlib.h> #include <unistd.h> #include <string> #include <iostream> using namespace std; int main(int argc, char** argv) { string cmd = "python \"C:\\path\\to\\xml-associator.py\" "; if(argc != 2) { return 1; } string file = string("\"")+argv[1]+"\""; cmd += file; cout << cmd << std::endl; system(cmd.c_str()); }
336
141
// // Copyright (c) 2019 Maxime Pinard // // Distributed under the MIT license // See accompanying file LICENSE or copy at // https://opensource.org/licenses/MIT // #include "config.hpp" #include "utils.hpp" #include "RandomDynamicBitsetGenerator.hpp" #include <catch2/catch.hpp> #include <sul/dynamic_bitset.hpp> #include <cstdint> #if DYNAMIC_BITSET_CAN_USE_LIBPOPCNT # define COUNT_TESTED_IMPL "libpopcnt" #elif DYNAMIC_BITSET_CAN_USE_STD_BITOPS # define COUNT_TESTED_IMPL "C++20 binary operations" #elif DYNAMIC_BITSET_CAN_USE_GCC_BUILTIN # define COUNT_TESTED_IMPL "gcc builtins" #elif DYNAMIC_BITSET_CAN_USE_CLANG_BUILTIN_POPCOUNT # define COUNT_TESTED_IMPL "clang builtins" #else # define COUNT_TESTED_IMPL "base" #endif TEMPLATE_TEST_CASE("count (" COUNT_TESTED_IMPL ")", "[dynamic_bitset][libpopcnt][builtin][c++20]", uint16_t, uint32_t, uint64_t) { CAPTURE(SEED); SECTION("empty bitset") { sul::dynamic_bitset<TestType> bitset; REQUIRE(bitset.count() == 0); } SECTION("non-empty bitset") { sul::dynamic_bitset<TestType> bitset = GENERATE(take(RANDOM_VECTORS_TO_TEST, randomDynamicBitset<TestType>(SEED))); CAPTURE(bitset); size_t count = 0; for(size_t i = 0; i < bitset.size(); ++i) { count += static_cast<size_t>(bitset[i]); } SECTION("general") { REQUIRE(bitset.count() == count); } SECTION("first block empty") { bitset.append(0); bitset <<= bits_number<TestType>; REQUIRE(bitset.count() == count); } SECTION("last block empty") { bitset.append(0); REQUIRE(bitset.count() == count); } } }
1,655
736
#include <iostream> #include <vector> #include <list> using namespace std; typedef vector<vector<int>> graph; void visit(int v, const graph &g, vector<int> &visited, list<int> &order) { visited[v] = true; for(int w : g[v]) { if(!visited[w]) visit(w, g, visited, order); } order.push_front(v); } list<int> topologicalSort(const graph &g) { vector<int> visited(g.size(), false); list<int> order; for(int v = 0; v < g.size(); v++) { if(!visited[v]) visit(v, g, visited, order); } return order; } int main() { graph g {{1, 7}, {2, 7}, {5}, {2, 4}, {5}, {}, {7}, {}, {}}; list<int> order = topologicalSort(g); cout << "Topological sort order: "; for(int v : order) cout << v << " "; cout << endl; return 0; }
942
345
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011-2013 Data Differential, http://datadifferential.com/ * Copyright (C) 2008 Brian Aker, Eric Day * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * @file * @brief Connection Definitions */ #include "gear_config.h" #include "libgearman-server/common.h" #include <libgearman-server/plugins/base.h> #include <cstring> #include <cerrno> #include <cassert> #ifndef SOCK_NONBLOCK # define SOCK_NONBLOCK 0 #endif #ifndef MSG_DONTWAIT # define MSG_DONTWAIT 0 #endif static void _connection_close(gearmand_io_st *connection) { if (connection->has_fd()) { assert(connection->options.external_fd); if (connection->options.external_fd) { connection->options.external_fd= false; } else { gearmand_log_fatal(GEARMAN_DEFAULT_LOG_PARAM, "We should never have an internal fd"); } connection->clear(); connection->_state= gearmand_io_st::GEARMAND_CON_UNIVERSAL_INVALID; connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_STATE_NONE; connection->send_buffer_ptr= connection->send_buffer; connection->send_buffer_size= 0; connection->send_data_size= 0; connection->send_data_offset= 0; connection->recv_state= gearmand_io_st::GEARMAND_CON_RECV_UNIVERSAL_NONE; if (connection->recv_packet != NULL) { gearmand_packet_free(connection->recv_packet); connection->recv_packet= NULL; } connection->recv_buffer_ptr= connection->recv_buffer; connection->recv_buffer_size= 0; } } const char* gearmand_io_st::host() const { if (context) { return context->host; } return "-"; } const char* gearmand_io_st::port() const { if (context) { return context->port; } return "-"; } #if __GNUC__ >= 7 #pragma GCC diagnostic warning "-Wimplicit-fallthrough" #endif static size_t _connection_read(gearman_server_con_st *con, void *data, size_t data_size, gearmand_error_t &ret) { ssize_t read_size; gearmand_io_st *connection= &con->con; while (1) { #if defined(HAVE_SSL) && HAVE_SSL if (con->_ssl) { # if defined(HAVE_WOLFSSL) && HAVE_WOLFSSL read_size= wolfSSL_recv(con->_ssl, data, int(data_size), MSG_DONTWAIT); # else read_size= SSL_read(con->_ssl, data, int(data_size)); # endif assert(HAVE_SSL); // Just to make sure if macro is aligned. int ssl_error; switch ((ssl_error= SSL_get_error(con->_ssl, int(read_size)))) { case SSL_ERROR_NONE: break; case SSL_ERROR_ZERO_RETURN: read_size= 0; break; case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_X509_LOOKUP: read_size= SOCKET_ERROR; errno= EAGAIN; break; case SSL_ERROR_SYSCALL: if (errno) // If errno is really set, then let our normal error logic handle. { read_size= SOCKET_ERROR; break; } /* fall-thru */ case SSL_ERROR_SSL: default: { // All other errors char errorString[SSL_ERROR_SIZE]; ERR_error_string_n(ssl_error, errorString, sizeof(errorString)); ret= GEARMAND_LOST_CONNECTION; gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "SSL failure(%s) errno:%d", errorString, errno); _connection_close(connection); return 0; } } } else #endif { read_size= recv(connection->fd(), data, data_size, MSG_DONTWAIT); } if (read_size == 0) { ret= GEARMAND_LOST_CONNECTION; gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "Peer connection has called close()"); _connection_close(connection); return 0; } else if (read_size == SOCKET_ERROR) { int local_errno= errno; switch (local_errno) { case EAGAIN: ret= gearmand_io_set_events(con, POLLIN); if (gearmand_failed(ret)) { gearmand_perror(local_errno, "recv"); return 0; } ret= GEARMAND_IO_WAIT; return 0; case EINTR: continue; case EPIPE: case ECONNRESET: case EHOSTDOWN: { ret= GEARMAND_LOST_CONNECTION; gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "Peer connection has called close()"); _connection_close(connection); return 0; } default: ret= GEARMAND_ERRNO; } gearmand_perror(local_errno, "closing connection due to previous errno error"); _connection_close(connection); return 0; } break; } ret= GEARMAND_SUCCESS; return size_t(read_size); } static gearmand_error_t gearmand_connection_recv_data(gearman_server_con_st *con, void *data, size_t data_size) { gearmand_io_st *connection= &con->con; if (connection->recv_data_size == 0) { return GEARMAND_SUCCESS; } if ((connection->recv_data_size - connection->recv_data_offset) < data_size) { data_size= connection->recv_data_size - connection->recv_data_offset; } size_t recv_size= 0; if (connection->recv_buffer_size > 0) { if (connection->recv_buffer_size < data_size) { recv_size= connection->recv_buffer_size; } else { recv_size= data_size; } memcpy(data, connection->recv_buffer_ptr, recv_size); connection->recv_buffer_ptr+= recv_size; connection->recv_buffer_size-= recv_size; } gearmand_error_t ret; if (data_size != recv_size) { recv_size+= _connection_read(con, ((uint8_t *)data) + recv_size, data_size - recv_size, ret); connection->recv_data_offset+= recv_size; } else { connection->recv_data_offset+= recv_size; ret= GEARMAND_SUCCESS; } if (connection->recv_data_size == connection->recv_data_offset) { connection->recv_data_size= 0; connection->recv_data_offset= 0; connection->recv_state= gearmand_io_st::GEARMAND_CON_RECV_UNIVERSAL_NONE; } return ret; } static gearmand_error_t _connection_flush(gearman_server_con_st *con) { gearmand_io_st *connection= &con->con; assert(connection->_state == gearmand_io_st::GEARMAND_CON_UNIVERSAL_CONNECTED); while (1) { switch (connection->_state) { case gearmand_io_st::GEARMAND_CON_UNIVERSAL_INVALID: assert(0); return GEARMAND_ERRNO; case gearmand_io_st::GEARMAND_CON_UNIVERSAL_CONNECTED: uint32_t loop_counter= 0; while (connection->send_buffer_size) { ssize_t write_size; #if defined(HAVE_SSL) && HAVE_SSL if (con->_ssl) { #if defined(HAVE_WOLFSSL) && HAVE_WOLFSSL write_size= wolfSSL_send(con->_ssl, connection->send_buffer_ptr, int(connection->send_buffer_size), MSG_NOSIGNAL|MSG_DONTWAIT); #elif defined(HAVE_OPENSSL) && HAVE_OPENSSL write_size= SSL_write(con->_ssl, connection->send_buffer_ptr, int(connection->send_buffer_size)); #endif assert(HAVE_SSL); // Just to make sure if macro is aligned. int ssl_error; switch ((ssl_error= SSL_get_error(con->_ssl, int(write_size)))) { case SSL_ERROR_NONE: break; case SSL_ERROR_ZERO_RETURN: errno= ECONNRESET; write_size= SOCKET_ERROR; break; case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_X509_LOOKUP: write_size= SOCKET_ERROR; errno= EAGAIN; break; case SSL_ERROR_SYSCALL: if (errno) // If errno is really set, then let our normal error logic handle. { write_size= SOCKET_ERROR; break; } /* fall-thru */ case SSL_ERROR_SSL: default: { char errorString[SSL_ERROR_SIZE]; ERR_error_string_n(ssl_error, errorString, sizeof(errorString)); _connection_close(connection); return gearmand_log_gerror(GEARMAN_DEFAULT_LOG_PARAM, GEARMAND_LOST_CONNECTION, "SSL failure(%s)", errorString); } } } else #endif { write_size= send(connection->fd(), connection->send_buffer_ptr, connection->send_buffer_size, MSG_NOSIGNAL|MSG_DONTWAIT); } if (write_size == 0) // detect infinite loop? { ++loop_counter; gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "send() sent zero bytes of %u", uint32_t(connection->send_buffer_size)); if (loop_counter > 5) { _connection_close(connection); return gearmand_log_gerror(GEARMAN_DEFAULT_LOG_PARAM, GEARMAND_LOST_CONNECTION, "send() failed to send data"); } continue; } else if (write_size == SOCKET_ERROR) { int local_errno= errno; switch (local_errno) { #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK: #endif case EAGAIN: { gearmand_error_t gret= gearmand_io_set_events(con, POLLOUT); if (gret != GEARMAND_SUCCESS) { return gret; } return GEARMAND_IO_WAIT; } case EINTR: continue; case EPIPE: case ECONNRESET: case EHOSTDOWN: _connection_close(connection); return gearmand_perror(local_errno, "lost connection to client during send(EPIPE || ECONNRESET || EHOSTDOWN)"); default: break; } _connection_close(connection); return gearmand_perror(local_errno, "send() failed, closing connection"); } gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "send() %u bytes to peer", uint32_t(write_size)); connection->send_buffer_size-= static_cast<size_t>(write_size); if (connection->send_state == gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_FLUSH_DATA) { connection->send_data_offset+= static_cast<size_t>(write_size); if (connection->send_data_offset == connection->send_data_size) { connection->send_data_size= 0; connection->send_data_offset= 0; break; } if (connection->send_buffer_size == 0) { return GEARMAND_SUCCESS; } } else if (connection->send_buffer_size == 0) { break; } connection->send_buffer_ptr+= write_size; } connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_STATE_NONE; connection->send_buffer_ptr= connection->send_buffer; return GEARMAND_SUCCESS; } } } /** * @addtogroup gearmand_io_static Static Connection Declarations * @ingroup gearman_connection * @{ */ void gearmand_connection_init(gearmand_connection_list_st *gearman, gearmand_io_st *connection, gearmand_con_st *dcon, gearmand_connection_options_t *options) { assert(gearman); assert(connection); connection->options.ready= false; connection->options.packet_in_use= false; connection->options.external_fd= false; connection->options.close_after_flush= false; if (options) { while (*options != GEARMAND_CON_MAX) { gearman_io_set_option(connection, *options, true); options++; } } connection->_state= gearmand_io_st::GEARMAND_CON_UNIVERSAL_INVALID; connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_STATE_NONE; connection->recv_state= gearmand_io_st::GEARMAND_CON_RECV_UNIVERSAL_NONE; connection->clear(); connection->created_id= 0; connection->created_id_next= 0; connection->send_buffer_size= 0; connection->send_data_size= 0; connection->send_data_offset= 0; connection->recv_buffer_size= 0; connection->recv_data_size= 0; connection->recv_data_offset= 0; connection->universal= gearman; GEARMAND_LIST__ADD(gearman->con, connection); connection->context= dcon; connection->send_buffer_ptr= connection->send_buffer; connection->recv_packet= NULL; connection->recv_buffer_ptr= connection->recv_buffer; } void gearmand_connection_list_st::list_free() { while (con_list) { gearmand_io_free(con_list); } } gearmand_connection_list_st::gearmand_connection_list_st() : con_count(0), con_list(NULL), event_watch_fn(NULL), event_watch_context(NULL) { } void gearmand_connection_list_st::init(gearmand_event_watch_fn *watch_fn, void *watch_context) { ready_con_count= 0; ready_con_list= NULL; con_count= 0; con_list= NULL; event_watch_fn= watch_fn; event_watch_context= watch_context; } void gearmand_io_free(gearmand_io_st *connection) { if (connection->has_fd()) { _connection_close(connection); } if (connection->options.ready) { connection->options.ready= false; GEARMAND_LIST_DEL(connection->universal->ready_con, connection, ready_); } GEARMAND_LIST__DEL(connection->universal->con, connection); if (connection->options.packet_in_use) { gearmand_packet_free(&(connection->packet)); } } gearmand_error_t gearman_io_set_option(gearmand_io_st *connection, gearmand_connection_options_t options, bool value) { switch (options) { case GEARMAND_CON_PACKET_IN_USE: connection->options.packet_in_use= value; break; case GEARMAND_CON_EXTERNAL_FD: connection->options.external_fd= value; break; case GEARMAND_CON_CLOSE_AFTER_FLUSH: connection->options.close_after_flush= value; break; case GEARMAND_CON_MAX: return GEARMAND_INVALID_COMMAND; } return GEARMAND_SUCCESS; } /** @} */ /* * Public Definitions */ gearmand_error_t gearman_io_set_fd(gearmand_io_st *connection, int fd_) { assert(connection); return connection->set_fd(fd_); } gearmand_con_st *gearman_io_context(const gearmand_io_st *connection) { return connection->context; } #if __GNUC__ >= 7 #pragma GCC diagnostic warning "-Wimplicit-fallthrough" #endif gearmand_error_t gearman_io_send(gearman_server_con_st *con, const gearmand_packet_st *packet, bool flush) { size_t send_size; gearmand_io_st *connection= &con->con; switch (connection->send_state) { case gearmand_io_st::GEARMAND_CON_SEND_STATE_NONE: if (! (packet->options.complete)) { gearmand_error("packet not complete"); return GEARMAND_INVALID_PACKET; } /* Pack first part of packet, which is everything but the payload. */ while (1) { gearmand_error_t ret; send_size= con->protocol->pack(packet, con, connection->send_buffer +connection->send_buffer_size, GEARMAND_SEND_BUFFER_SIZE -connection->send_buffer_size, ret); if (ret == GEARMAND_SUCCESS) { connection->send_buffer_size+= send_size; break; } else if (ret == GEARMAND_IGNORE_PACKET) { return GEARMAND_SUCCESS; } else if (ret != GEARMAND_FLUSH_DATA) { return ret; } /* We were asked to flush when the buffer is already flushed! */ if (connection->send_buffer_size == 0) { gearmand_error("send buffer too small"); return GEARMAND_SEND_BUFFER_TOO_SMALL; } /* Flush buffer now if first part of packet won't fit in. */ connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_PRE_FLUSH; case gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_PRE_FLUSH: { gearmand_error_t local_ret; if ((local_ret= _connection_flush(con)) != GEARMAND_SUCCESS) { return local_ret; } } } /* Return here if we have no data to send. */ if (packet->data_size == 0) { break; } /* If there is any room in the buffer, copy in data. */ if (packet->data and (GEARMAND_SEND_BUFFER_SIZE - connection->send_buffer_size) > 0) { connection->send_data_offset= GEARMAND_SEND_BUFFER_SIZE - connection->send_buffer_size; if (connection->send_data_offset > packet->data_size) { connection->send_data_offset= packet->data_size; } memcpy(connection->send_buffer +connection->send_buffer_size, packet->data, connection->send_data_offset); connection->send_buffer_size+= connection->send_data_offset; /* Return if all data fit in the send buffer. */ if (connection->send_data_offset == packet->data_size) { connection->send_data_offset= 0; break; } } /* Flush buffer now so we can start writing directly from data buffer. */ connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_FORCE_FLUSH; /* fall-thru */ case gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_FORCE_FLUSH: { gearmand_error_t local_ret; if ((local_ret= _connection_flush(con)) != GEARMAND_SUCCESS) { return local_ret; } /* fall-thru */ } connection->send_data_size= packet->data_size; /* If this is NULL, then ?? function will be used. */ if (packet->data == NULL) { connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_FLUSH_DATA; return GEARMAND_SUCCESS; } /* Copy into the buffer if it fits, otherwise flush from packet buffer. */ connection->send_buffer_size= packet->data_size - connection->send_data_offset; if (connection->send_buffer_size < GEARMAND_SEND_BUFFER_SIZE) { memcpy(connection->send_buffer, packet->data + connection->send_data_offset, connection->send_buffer_size); connection->send_data_size= 0; connection->send_data_offset= 0; break; } connection->send_buffer_ptr= const_cast<char *>(packet->data) + connection->send_data_offset; connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_FLUSH_DATA; /* fall-thru */ case gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_FLUSH: case gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_FLUSH_DATA: { gearmand_error_t local_ret= _connection_flush(con); if (local_ret == GEARMAND_SUCCESS and connection->options.close_after_flush) { _connection_close(connection); local_ret= GEARMAND_LOST_CONNECTION; gearmand_debug("closing connection after flush by request"); } return local_ret; } } /* fall-thru */ if (flush) { connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_UNIVERSAL_FLUSH; gearmand_error_t local_ret= _connection_flush(con); if (local_ret == GEARMAND_SUCCESS and connection->options.close_after_flush) { _connection_close(connection); local_ret= GEARMAND_LOST_CONNECTION; gearmand_debug("closing connection after flush by request"); } return local_ret; } connection->send_state= gearmand_io_st::GEARMAND_CON_SEND_STATE_NONE; return GEARMAND_SUCCESS; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" gearmand_error_t gearman_io_recv(gearman_server_con_st *con, bool recv_data) { gearmand_io_st *connection= &con->con; gearmand_packet_st *packet= &(con->packet->packet); switch (connection->recv_state) { case gearmand_io_st::GEARMAND_CON_RECV_UNIVERSAL_NONE: if (connection->_state != gearmand_io_st::GEARMAND_CON_UNIVERSAL_CONNECTED) { gearmand_error("not connected"); return GEARMAND_NOT_CONNECTED; } connection->recv_packet= packet; // The options being passed in are just defaults. connection->recv_packet->reset(GEARMAN_MAGIC_TEXT, GEARMAN_COMMAND_TEXT); connection->recv_state= gearmand_io_st::GEARMAND_CON_RECV_UNIVERSAL_READ; /* fall-thru */ case gearmand_io_st::GEARMAND_CON_RECV_UNIVERSAL_READ: while (1) { gearmand_error_t ret; if (connection->recv_buffer_size > 0) { assert(con->protocol); size_t recv_size= con->protocol->unpack(connection->recv_packet, con, connection->recv_buffer_ptr, connection->recv_buffer_size, ret); connection->recv_buffer_ptr+= recv_size; connection->recv_buffer_size-= recv_size; if (gearmand_success(ret)) { break; } else if (ret != GEARMAND_IO_WAIT) { gearmand_gerror_warn("protocol failure, closing connection", ret); _connection_close(connection); return ret; } } /* Shift buffer contents if needed. */ if (connection->recv_buffer_size > 0) { memmove(connection->recv_buffer, connection->recv_buffer_ptr, connection->recv_buffer_size); } connection->recv_buffer_ptr= connection->recv_buffer; size_t recv_size= _connection_read(con, connection->recv_buffer + connection->recv_buffer_size, GEARMAND_RECV_BUFFER_SIZE - connection->recv_buffer_size, ret); if (gearmand_failed(ret)) { // GEARMAND_LOST_CONNECTION is not worth a warning, clients/workers just // drop connections for close. if (ret != GEARMAND_LOST_CONNECTION) { gearmand_gerror_warn("Failed while in _connection_read()", ret); } return ret; } gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "read %lu bytes", (unsigned long)recv_size); connection->recv_buffer_size+= recv_size; } if (packet->data_size == 0) { connection->recv_state= gearmand_io_st::GEARMAND_CON_RECV_UNIVERSAL_NONE; break; } connection->recv_data_size= packet->data_size; if (not recv_data) { connection->recv_state= gearmand_io_st::GEARMAND_CON_RECV_STATE_READ_DATA; break; } packet->data= static_cast<char *>(realloc(NULL, packet->data_size)); if (not packet->data) { // Server up the memory error first, in case _connection_close() // creates any. gearmand_merror("realloc", char, packet->data_size); _connection_close(connection); return GEARMAND_MEMORY_ALLOCATION_FAILURE; } packet->options.free_data= true; connection->recv_state= gearmand_io_st::GEARMAND_CON_RECV_STATE_READ_DATA; /* fall-thru */ case gearmand_io_st::GEARMAND_CON_RECV_STATE_READ_DATA: while (connection->recv_data_size) { gearmand_error_t ret; ret= gearmand_connection_recv_data(con, ((uint8_t *)(packet->data)) + connection->recv_data_offset, packet->data_size - connection->recv_data_offset); if (gearmand_failed(ret)) { return ret; } } connection->recv_state= gearmand_io_st::GEARMAND_CON_RECV_UNIVERSAL_NONE; break; } packet= connection->recv_packet; connection->recv_packet= NULL; return GEARMAND_SUCCESS; } gearmand_error_t gearmand_io_set_events(gearman_server_con_st *con, short events) { gearmand_io_st *connection= &con->con; if ((connection->events | events) == connection->events) { return GEARMAND_SUCCESS; } connection->events|= events; if (connection->universal->event_watch_fn) { gearmand_error_t ret= connection->universal->event_watch_fn(connection, connection->events, (void *)connection->universal->event_watch_context); if (gearmand_failed(ret)) { gearmand_gerror_warn("event watch failed, closing connection", ret); _connection_close(connection); return ret; } } return GEARMAND_SUCCESS; } gearmand_error_t gearmand_io_set_revents(gearman_server_con_st *con, short revents) { gearmand_io_st *connection= &con->con; if (revents != 0) { connection->options.ready= true; GEARMAND_LIST_ADD(connection->universal->ready_con, connection, ready_); } connection->revents= revents; /* Remove external POLLOUT watch if we didn't ask for it. Otherwise we spin forever until another POLLIN state change. This is much more efficient than removing POLLOUT on every state change since some external polling mechanisms need to use a system call to change flags (like Linux epoll). */ if (revents & POLLOUT && !(connection->events & POLLOUT) && connection->universal->event_watch_fn != NULL) { gearmand_error_t ret= connection->universal->event_watch_fn(connection, connection->events, (void *)connection->universal->event_watch_context); if (gearmand_failed(ret)) { gearmand_gerror_warn("event watch failed, closing connection", ret); _connection_close(connection); return ret; } } connection->events&= (short)~revents; return GEARMAND_SUCCESS; } /* * Static Definitions */ gearmand_error_t gearmand_io_st::_io_setsockopt() { { int setting= 1; if (setsockopt(_fd, IPPROTO_TCP, TCP_NODELAY, &setting, (socklen_t)sizeof(int)) and errno != EOPNOTSUPP) { return gearmand_perror(errno, "setsockopt(TCP_NODELAY)"); } } { struct linger linger; linger.l_onoff= 1; linger.l_linger= GEARMAND_DEFAULT_SOCKET_TIMEOUT; if (setsockopt(_fd, SOL_SOCKET, SO_LINGER, &linger, (socklen_t)sizeof(struct linger))) { return gearmand_perror(errno, "setsockopt(SO_LINGER)"); } } #if defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__) { int setting= 1; // This is not considered a fatal error if (setsockopt(_fd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&setting, sizeof(int))) { gearmand_perror(errno, "setsockopt(SO_NOSIGPIPE)"); } } #endif #if 0 if (0) { struct timeval waittime; waittime.tv_sec= GEARMAND_DEFAULT_SOCKET_TIMEOUT; waittime.tv_usec= 0; if (setsockopt(_fd, SOL_SOCKET, SO_SNDTIMEO, &waittime, (socklen_t)sizeof(struct timeval)) and errno != ENOPROTOOPT) { return gearmand_perror(errno, "setsockopt(SO_SNDTIMEO)"); } if (setsockopt(_fd, SOL_SOCKET, SO_RCVTIMEO, &waittime, (socklen_t)sizeof(struct timeval)) and errno != ENOPROTOOPT) { return gearmand_perror(errno, "setsockopt(SO_RCVTIMEO)"); } } #endif #if 0 if (0) { int setting= GEARMAND_DEFAULT_SOCKET_SEND_SIZE; if (setsockopt(_fd, SOL_SOCKET, SO_SNDBUF, &setting, (socklen_t)sizeof(int))) { return gearmand_perror(errno, "setsockopr(SO_SNDBUF)"); } setting= GEARMAND_DEFAULT_SOCKET_RECV_SIZE; if (setsockopt(_fd, SOL_SOCKET, SO_RCVBUF, &setting, (socklen_t)sizeof(int))) { return gearmand_perror(errno, "setsockopt(SO_RCVBUF)"); } } #endif if (SOCK_NONBLOCK == 0) { gearmand_error_t local_ret; if ((local_ret= gearmand_sockfd_nonblock(_fd))) { return local_ret; } } return GEARMAND_SUCCESS; } gearmand_error_t gearmand_sockfd_nonblock(const int& sockfd) { int flags; do { flags= fcntl(sockfd, F_GETFL, 0); if (flags == -1) { gearmand_log_perror_warn(GEARMAN_DEFAULT_LOG_PARAM, flags, "gearmand_sockfd_nonblock"); } } while (flags == -1 and (errno == EINTR or errno == EAGAIN)); if (flags == -1) { return gearmand_perror(errno, "fcntl(F_GETFL)"); } else if ((flags & O_NONBLOCK) == 0) { int retval; do { retval= fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); if (retval == -1) { gearmand_log_perror_warn(GEARMAN_DEFAULT_LOG_PARAM, retval, "gearmand_sockfd_nonblock"); } } while (retval == -1 and (errno == EINTR or errno == EAGAIN)); if (retval == -1) { return gearmand_perror(errno, "fcntl(F_SETFL)"); } } return GEARMAND_SUCCESS; } void gearmand_sockfd_close(int& sockfd) { if (sockfd != INVALID_SOCKET) { /* in case of death shutdown to avoid blocking at close() */ if (shutdown(sockfd, SHUT_RDWR) == SOCKET_ERROR && get_socket_errno() != ENOTCONN) { gearmand_perror(errno, "shutdown"); assert(errno != ENOTSOCK); } else if (closesocket(sockfd) == SOCKET_ERROR) { gearmand_perror(errno, "close"); } sockfd= INVALID_SOCKET; } else { gearmand_debug("gearmand_sockfd_close() called with an invalid socket, this was probably ok"); } } void gearmand_pipe_close(int& pipefd) { if (pipefd == INVALID_SOCKET) { gearmand_error("gearmand_pipe_close() called with an invalid socket"); return; } if (closesocket(pipefd) == SOCKET_ERROR) { gearmand_perror(errno, "close"); } pipefd= -1; } #pragma GCC diagnostic pop
30,898
11,186
#include "state_machine.h" #include "digital_io.h" #include "globals.h" // take care to have all enum values of StateType present void (*state_machine[])(void) = { sm_state_BEGIN, sm_state_WAIT_VIN_ON, sm_state_ENT_CHARGING, sm_state_CHARGING, sm_state_ENT_ON, sm_state_ON, sm_state_ENT_DEPLETING, sm_state_DEPLETING, sm_state_ENT_SHUTDOWN, sm_state_SHUTDOWN, sm_state_ENT_WATCHDOG_REBOOT, sm_state_WATCHDOG_REBOOT, sm_state_ENT_OFF, sm_state_OFF, }; StateType sm_state = BEGIN; StateType get_sm_state() { return sm_state; } // PATTERN: *___________________ int off_pattern[] = {50, 950, -1}; void sm_state_BEGIN() { set_en5v_pin(false); i2c_register = 0xff; watchdog_limit = 0; gpio_poweroff_elapsed = 0; status_blinker.set_pattern(off_pattern); sm_state = WAIT_VIN_ON; } void sm_state_WAIT_VIN_ON() { // never start if DC input voltage is not present if (v_in >= int(VIN_OFF / VIN_MAX * VIN_SCALE)) { sm_state = ENT_CHARGING; } } // PATTERN: *************_*_*_*_ int charging_pattern[] = {650, 50, 50, 50, 50, 50, 50, 50, -1}; void sm_state_ENT_CHARGING() { status_blinker.set_pattern(charging_pattern); sm_state = CHARGING; } void sm_state_CHARGING() { if (v_supercap > power_on_vcap_voltage) { sm_state = ENT_ON; } else if (v_in < int(VIN_OFF / VIN_MAX * VIN_SCALE)) { // if power is cut before supercap is charged, // kill power immediately sm_state = ENT_OFF; } } // PATTERN: ******************** int solid_on_pattern[] = {1000, 0, -1}; void sm_state_ENT_ON() { set_en5v_pin(true); status_blinker.set_pattern(solid_on_pattern); sm_state = ON; } // PATTERN: *******************_ int watchdog_enabled_pattern[] = {950, 50, -1}; void sm_state_ON() { if (watchdog_value_changed) { if (watchdog_limit) { status_blinker.set_pattern(watchdog_enabled_pattern); } else { status_blinker.set_pattern(solid_on_pattern); } watchdog_value_changed = false; } if (watchdog_limit && (watchdog_elapsed > watchdog_limit)) { sm_state = ENT_WATCHDOG_REBOOT; return; } // kill the power if the host has been powered off for more than a second if (gpio_poweroff_elapsed > GPIO_OFF_TIME_LIMIT) { sm_state = ENT_OFF; return; } if (v_in < int(VIN_OFF / VIN_MAX * VIN_SCALE)) { sm_state = ENT_DEPLETING; } } // PATTERN: *_*_*_*_____________ int draining_pattern[] = {50, 50, 50, 50, 50, 50, 50, 650, -1}; void sm_state_ENT_DEPLETING() { status_blinker.set_pattern(draining_pattern); sm_state = DEPLETING; } void sm_state_DEPLETING() { if (watchdog_limit && (watchdog_elapsed > watchdog_limit)) { sm_state = ENT_WATCHDOG_REBOOT; return; } if (shutdown_requested) { shutdown_requested = false; sm_state = ENT_SHUTDOWN; return; } else if (v_in > int(VIN_OFF / VIN_MAX * VIN_SCALE)) { sm_state = ENT_ON; return; } else if (v_supercap < power_off_vcap_voltage) { sm_state = ENT_OFF; return; } // kill the power if the host has been powered off for more than a second if (gpio_poweroff_elapsed > GPIO_OFF_TIME_LIMIT) { sm_state = ENT_OFF; return; } } elapsedMillis elapsed_shutdown; // PATTERN: ****____ int shutdown_pattern[] = {200, 200, -1}; void sm_state_ENT_SHUTDOWN() { status_blinker.set_pattern(shutdown_pattern); // ignore watchdog watchdog_limit = 0; elapsed_shutdown = 0; sm_state = SHUTDOWN; } void sm_state_SHUTDOWN() { if ((gpio_poweroff_elapsed > GPIO_OFF_TIME_LIMIT) || (elapsed_shutdown > SHUTDOWN_WAIT_DURATION)) { sm_state = ENT_OFF; } } elapsedMillis elapsed_off; void sm_state_ENT_OFF() { set_en5v_pin(false); // in case we're not dead, set a blink pattern status_blinker.set_pattern(off_pattern); sm_state = OFF; } void sm_state_OFF() { if (elapsed_off > OFF_STATE_DURATION) { // if we're still alive, jump back to begin sm_state = BEGIN; } } elapsedMillis elapsed_reboot; // PATTERN: *_ int watchdog_pattern[] = {50, 50, -1}; void sm_state_ENT_WATCHDOG_REBOOT() { elapsed_reboot = 0; watchdog_limit = 0; set_en5v_pin(false); status_blinker.set_pattern(watchdog_pattern); sm_state = WATCHDOG_REBOOT; } void sm_state_WATCHDOG_REBOOT() { if (elapsed_reboot > WATCHDOG_REBOOT_DURATION) { sm_state = BEGIN; } } // function to run the state machine void sm_run() { if (sm_state < NUM_STATES) { // call the function for the state (*state_machine[sm_state])(); } else { sm_state = BEGIN; // FIXME: should we restart instead? } }
4,577
1,986
#include <iostream> #include <sys/stat.h> #define MAX_ARR_BOX 100 using namespace std; struct MyException : public std::exception { std::string s; MyException(std::string ss) : s(ss) {} ~MyException() throw () {} // Updated const char* what() const throw() { return s.c_str(); } }; typedef struct Box{ string key; string value; int timestamp; } Box; Box* bb = new Box[MAX_ARR_BOX]; Box setBox(string key, string value); void getBox(Box b); bool s(string key, string value); string g(string key); bool createDir(string dirr); int main() { string key, value="ok, ceci est un example !!!"; // We create the directory createDir("cache"); cout << "> Welcome to in_memo !" << endl; cout << "[-] Set a value, key :"; cin >> key; // cout << "[-] Set the value of " << key << ": "; // cin >> value; if (s(key, value) == true) { cout << "[+] Value setted successfully !" << endl; } else { cout << "[x] An error occured..."; } cout << "[-] < Geting value : "; cin >> key; cout << g(key) << endl; return 0; } bool s(string key, string value) { try { // We loop curent boxes and try to find if a box already exist with that key // if yes, we just replace it for (int i=0; i<sizeof(bb); i++){ if (key == bb[i].key || bb[i].key == "") { bb[i] = setBox(key, value); return true; } } bb[sizeof(bb)] = setBox(key, value); return true; } catch (MyException& caught) { cout << "[x] Got "<< caught.what() << std::endl; return false; } } string g(string key) { // We loop boxes and return it for (int i=0; i<sizeof(bb); i++) return (key == bb[i].key) ? bb[i].value : NULL; return ""; } bool createDir(string s) { // A simpleconvertion from string to char* char cstr[s.size() + 1]; s.copy(cstr, s.size() + 1); cstr[s.size()] = '\0'; if(mkdir(cstr, 0777) == -1) { return true; } else { return false; } } Box setBox(string key, string value) { Box b; b.key = key; b.value = value; return b; } void getBox(Box b) { cout << "key : " << b.key << endl; cout << "value : " << b.value << endl; }
2,347
846
#include <Precomp.h> #include <Renderer/UniformBuffer.h> #include <Renderer/Renderer.h> #include <Platform/OpenGL/OpenGLUniformBuffer.h> namespace OP { Ref<UniformBuffer> UniformBuffer::Create(uint32_t size, uint32_t binding) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: OP_ENGINE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; case RendererAPI::API::OpenGL: return CreateRef<OpenGLUniformBuffer>(size, binding); } OP_ENGINE_ASSERT(false, "Unknown RendererAPI!"); return nullptr; } }
554
203
#include <stan/math/mix.hpp> #include <test/unit/math/rev/fun/util.hpp> #include <gtest/gtest.h> #include <vector> TEST(ProbDistributionsOrdLog, fv_fv) { using stan::math::fvar; using stan::math::ordered_logistic_lpmf; using stan::math::var; using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::vector_fv; int y = 1; fvar<var> lam_fv = -1.32; lam_fv.d_ = 1.0; vector_fv c_fv(3); c_fv << -0.95, -0.10, 0.95; for (int i = 0; i < 3; i++) c_fv[i].d_ = 1.0; fvar<fvar<var>> lam_ffv; lam_ffv.val_ = -1.32; lam_ffv.d_ = 1.0; lam_ffv.val_.d_ = 1.0; vector_ffv c_ffv(3); c_ffv << -0.95, -0.10, 0.95; for (int i = 0; i < 3; i++) { c_ffv[i].d_ = 1.0; c_ffv[i].val_.d_ = 1.0; } fvar<var> out_fv = ordered_logistic_lpmf(y, lam_fv, c_fv); out_fv.d_.grad(); EXPECT_FLOAT_EQ(out_fv.val_.val(), -0.52516294973063); EXPECT_FLOAT_EQ(out_fv.d_.val() + 1, 0.0 + 1); EXPECT_FLOAT_EQ(lam_fv.d_.adj(), -0.40854102156722); EXPECT_FLOAT_EQ(c_fv[0].d_.adj(), -lam_fv.d_.adj()); EXPECT_FLOAT_EQ(c_fv[1].d_.adj(), 0.0); EXPECT_FLOAT_EQ(c_fv[2].d_.adj(), 0.0); fvar<fvar<var>> out_ffv = ordered_logistic_lpmf(y, lam_ffv, c_ffv); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -0.52516294973063); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val() + 1, 0.0 + 1); EXPECT_FLOAT_EQ(lam_ffv.d_.val_.adj(), -0.40854102156722); EXPECT_FLOAT_EQ(c_ffv[0].d_.val_.adj(), -lam_ffv.d_.val_.adj()); EXPECT_FLOAT_EQ(c_ffv[1].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(c_ffv[2].d_.val_.adj(), 0.0); } TEST(ProbDistributionsOrdLog, fv_d) { using stan::math::fvar; using stan::math::ordered_logistic_lpmf; using stan::math::var; using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::vector_fv; int y = 1; fvar<var> lam_fv = -1.32; lam_fv.d_ = 1.0; double lam_d = -1.32; vector_fv c_fv(3); c_fv << -0.95, -0.10, 0.95; for (int i = 0; i < 3; i++) c_fv[i].d_ = 1.0; vector_d c_d(3); c_d << -0.95, -0.10, 0.95; fvar<fvar<var>> lam_ffv; lam_ffv.val_ = -1.32; lam_ffv.d_ = 1.0; lam_ffv.val_.d_ = 1.0; vector_ffv c_ffv(3); c_ffv << -0.95, -0.10, 0.95; for (int i = 0; i < 3; i++) { c_ffv[i].d_ = 1.0; c_ffv[i].val_.d_ = 1.0; } fvar<var> out = ordered_logistic_lpmf(y, lam_fv, c_d); out.d_.grad(); EXPECT_FLOAT_EQ(out.val_.val(), -0.52516294973063); EXPECT_FLOAT_EQ(out.d_.val(), -0.40854102156722); EXPECT_FLOAT_EQ(lam_fv.d_.adj(), -0.40854102156722); out = ordered_logistic_lpmf(y, lam_d, c_fv); out.d_.grad(); EXPECT_FLOAT_EQ(out.val_.val(), -0.52516294973063); EXPECT_FLOAT_EQ(out.d_.val(), 0.40854102156722); EXPECT_FLOAT_EQ(c_fv[0].d_.adj(), 0.40854102156722); EXPECT_FLOAT_EQ(c_fv[1].d_.adj(), 0.0); EXPECT_FLOAT_EQ(c_fv[2].d_.adj(), 0.0); fvar<fvar<var>> out_ffv = ordered_logistic_lpmf(y, lam_ffv, c_d); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -0.52516294973063); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val(), -0.40854102156722); EXPECT_FLOAT_EQ(lam_ffv.d_.val_.adj(), -0.40854102156722); out_ffv = ordered_logistic_lpmf(y, lam_d, c_ffv); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -0.52516294973063); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val(), 0.40854102156722); EXPECT_FLOAT_EQ(c_ffv[0].d_.val_.adj(), 0.40854102156722); EXPECT_FLOAT_EQ(c_ffv[1].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(c_ffv[2].d_.val_.adj(), 0.0); } TEST(ProbDistributionsOrdLog, fv_fv_vec) { using stan::math::fvar; using stan::math::ordered_logistic_lpmf; using stan::math::var; using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::vector_fv; std::vector<int> y{1, 2, 3, 4}; vector_fv lam_fv(4); lam_fv << 1.25, -0.33, 1.36, 2.11; for (int i = 0; i < 4; i++) lam_fv[i].d_ = 1.0; vector_fv c_fv(3); c_fv << -1.21, -1.01, 0.90; for (int i = 0; i < 3; i++) c_fv[i].d_ = 1.0; vector_ffv lam_ffv(4); lam_ffv << 1.25, -0.33, 1.36, 2.11; for (int i = 0; i < 4; i++) { lam_ffv[i].d_ = 1.0; lam_ffv[i].val_.d_ = 1.0; } vector_ffv c_ffv(3); c_ffv << -1.21, -1.01, 0.90; for (int i = 0; i < 3; i++) { c_ffv[i].d_ = 1.0; c_ffv[i].val_.d_ = 1.0; } fvar<var> out_fv = ordered_logistic_lpmf(y, lam_fv, c_fv); out_fv.d_.grad(); EXPECT_FLOAT_EQ(out_fv.val_.val(), -7.14656827285528); EXPECT_FLOAT_EQ(out_fv.d_.val() + 1, 0.0 + 1); EXPECT_FLOAT_EQ(lam_fv[0].d_.adj(), -0.921289662829465); EXPECT_FLOAT_EQ(lam_fv[1].d_.adj(), -0.370560918497922); EXPECT_FLOAT_EQ(lam_fv[2].d_.adj(), -0.527525036704529); EXPECT_FLOAT_EQ(lam_fv[3].d_.adj(), 0.229701050953398); EXPECT_FLOAT_EQ(c_fv[0].d_.adj(), -3.88854368220396); EXPECT_FLOAT_EQ(c_fv[1].d_.adj(), 4.92108545347799); EXPECT_FLOAT_EQ(c_fv[2].d_.adj(), 0.557132795804491); fvar<fvar<var>> out_ffv = ordered_logistic_lpmf(y, lam_ffv, c_ffv); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -7.14656827285528); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val() + 1, 0.0 + 1); EXPECT_FLOAT_EQ(lam_ffv[0].d_.val_.adj(), -0.921289662829465); EXPECT_FLOAT_EQ(lam_ffv[1].d_.val_.adj(), -0.370560918497922); EXPECT_FLOAT_EQ(lam_ffv[2].d_.val_.adj(), -0.527525036704529); EXPECT_FLOAT_EQ(lam_ffv[3].d_.val_.adj(), 0.229701050953398); EXPECT_FLOAT_EQ(c_ffv[0].d_.val_.adj(), -3.88854368220396); EXPECT_FLOAT_EQ(c_ffv[1].d_.val_.adj(), 4.92108545347799); EXPECT_FLOAT_EQ(c_ffv[2].d_.val_.adj(), 0.557132795804491); } TEST(ProbDistributionsOrdLog, fv_d_vec) { using stan::math::fvar; using stan::math::ordered_logistic_lpmf; using stan::math::var; using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::vector_fv; std::vector<int> y{1, 2, 3, 4}; vector_fv lam_fv(4); lam_fv << 1.25, -0.33, 1.36, 2.11; for (int i = 0; i < 4; i++) lam_fv[i].d_ = 1.0; vector_fv c_fv(3); c_fv << -2.22, -1.55, -0.36; for (int i = 0; i < 3; i++) c_fv[i].d_ = 1.0; vector_ffv lam_ffv(4); lam_ffv << 1.25, -0.33, 1.36, 2.11; for (int i = 0; i < 4; i++) { lam_ffv[i].d_ = 1.0; lam_ffv[i].val_.d_ = 1.0; } vector_ffv c_ffv(3); c_ffv << -2.22, -1.55, -0.36; for (int i = 0; i < 3; i++) { c_ffv[i].d_ = 1.0; c_ffv[i].val_.d_ = 1.0; } vector_d lam_d(4); lam_d << 1.25, -0.33, 1.36, 2.11; vector_d c_d(3); c_d << -2.22, -1.55, -0.36; fvar<var> out = ordered_logistic_lpmf(y, lam_fv, c_d); out.d_.grad(); EXPECT_FLOAT_EQ(out.val_.val(), -8.21855481819114); EXPECT_FLOAT_EQ(out.d_.val(), -2.32912026425027); EXPECT_FLOAT_EQ(lam_fv[0].d_.adj(), -0.969822018514124); EXPECT_FLOAT_EQ(lam_fv[1].d_.adj(), -0.640819079988261); EXPECT_FLOAT_EQ(lam_fv[2].d_.adj(), -0.796467400877256); EXPECT_FLOAT_EQ(lam_fv[3].d_.adj(), 0.077988235129366); out = ordered_logistic_lpmf(y, lam_d, c_fv); out.d_.grad(); EXPECT_FLOAT_EQ(out.val_.val(), -8.21855481819114); EXPECT_FLOAT_EQ(out.d_.val(), 2.32912026425027); EXPECT_FLOAT_EQ(c_fv[0].d_.adj(), -0.209379786457621); EXPECT_FLOAT_EQ(c_fv[1].d_.adj(), 1.33112093047159); EXPECT_FLOAT_EQ(c_fv[2].d_.adj(), 1.20737912023631); fvar<fvar<var>> out_ffv = ordered_logistic_lpmf(y, lam_ffv, c_d); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -8.21855481819114); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val(), -2.32912026425027); EXPECT_FLOAT_EQ(lam_ffv[0].d_.val_.adj(), -0.969822018514124); EXPECT_FLOAT_EQ(lam_ffv[1].d_.val_.adj(), -0.640819079988261); EXPECT_FLOAT_EQ(lam_ffv[2].d_.val_.adj(), -0.796467400877256); EXPECT_FLOAT_EQ(lam_ffv[3].d_.val_.adj(), 0.077988235129366); out_ffv = ordered_logistic_lpmf(y, lam_d, c_ffv); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -8.21855481819114); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val(), 2.32912026425027); EXPECT_FLOAT_EQ(c_ffv[0].d_.val_.adj(), -0.209379786457621); EXPECT_FLOAT_EQ(c_ffv[1].d_.val_.adj(), 1.33112093047159); EXPECT_FLOAT_EQ(c_ffv[2].d_.val_.adj(), 1.20737912023631); } TEST(ProbDistributionsOrdLog, fv_fv_stvec) { using stan::math::fvar; using stan::math::ordered_logistic_lpmf; using stan::math::var; using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::vector_fv; std::vector<int> y{1, 2, 3, 4}; vector_fv lam_fv(4); lam_fv << 0.61, 2.63, -0.06, 1.04; for (int i = 0; i < 4; i++) lam_fv[i].d_ = 1.0; vector_fv c1_fv(3); c1_fv << -2.58, -1.66, -0.64; for (int i = 0; i < 3; i++) c1_fv[i].d_ = 1.0; vector_fv c2_fv(3); c2_fv << -1.20, 0.22, 1.34; for (int i = 0; i < 3; i++) c2_fv[i].d_ = 1.0; vector_fv c3_fv(3); c3_fv << -1.68, -0.28, 1.33; for (int i = 0; i < 3; i++) c3_fv[i].d_ = 1.0; vector_fv c4_fv(3); c4_fv << -2.51, -0.64, 1.03; for (int i = 0; i < 3; i++) c4_fv[i].d_ = 1.0; vector_ffv lam_ffv(4); lam_ffv << 0.61, 2.63, -0.06, 1.04; for (int i = 0; i < 4; i++) { lam_ffv[i].d_ = 1.0; lam_ffv[i].val_.d_ = 1.0; } vector_ffv c1_ffv(3); c1_ffv << -2.58, -1.66, -0.64; for (int i = 0; i < 3; i++) { c1_ffv[i].d_ = 1.0; c1_ffv[i].val_.d_ = 1.0; } vector_ffv c2_ffv(3); c2_ffv << -1.20, 0.22, 1.34; for (int i = 0; i < 3; i++) { c2_ffv[i].d_ = 1.0; c2_ffv[i].val_.d_ = 1.0; } vector_ffv c3_ffv(3); c3_ffv << -1.68, -0.28, 1.33; for (int i = 0; i < 3; i++) { c3_ffv[i].d_ = 1.0; c3_ffv[i].val_.d_ = 1.0; } vector_ffv c4_ffv(3); c4_ffv << -2.51, -0.64, 1.03; for (int i = 0; i < 3; i++) { c4_ffv[i].d_ = 1.0; c4_ffv[i].val_.d_ = 1.0; } std::vector<vector_fv> std_c_fv{c1_fv, c2_fv, c3_fv, c4_fv}; std::vector<vector_ffv> std_c_ffv{c1_ffv, c2_ffv, c3_ffv, c4_ffv}; fvar<var> out_fv = ordered_logistic_lpmf(y, lam_fv, std_c_fv); out_fv.d_.grad(); EXPECT_FLOAT_EQ(out_fv.val_.val(), -7.74727840068321); EXPECT_FLOAT_EQ(out_fv.d_.val() + 1, 0.0 + 1); EXPECT_FLOAT_EQ(lam_fv[0].d_.adj(), -0.960456220449047); EXPECT_FLOAT_EQ(lam_fv[1].d_.adj(), -0.896338359161074); EXPECT_FLOAT_EQ(lam_fv[2].d_.adj(), 0.245813008044117); EXPECT_FLOAT_EQ(lam_fv[3].d_.adj(), 0.497500020833125); EXPECT_FLOAT_EQ(std_c_fv[0][0].d_.adj(), 0.960456220449047); EXPECT_FLOAT_EQ(std_c_fv[0][1].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[0][2].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[1][0].d_.adj(), -0.340011984816337); EXPECT_FLOAT_EQ(std_c_fv[1][1].d_.adj(), 1.23635034397741); EXPECT_FLOAT_EQ(std_c_fv[1][2].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[2][0].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[2][1].d_.adj(), -0.695045186550866); EXPECT_FLOAT_EQ(std_c_fv[2][2].d_.adj(), 0.44923217850675); EXPECT_FLOAT_EQ(std_c_fv[3][0].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[3][1].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[3][2].d_.adj(), -0.497500020833125); fvar<fvar<var>> out_ffv = ordered_logistic_lpmf(y, lam_ffv, std_c_ffv); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -7.74727840068321); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val() + 1, 0.0 + 1); EXPECT_FLOAT_EQ(lam_ffv[0].d_.val_.adj(), -0.960456220449047); EXPECT_FLOAT_EQ(lam_ffv[1].d_.val_.adj(), -0.896338359161074); EXPECT_FLOAT_EQ(lam_ffv[2].d_.val_.adj(), 0.245813008044117); EXPECT_FLOAT_EQ(lam_ffv[3].d_.val_.adj(), 0.497500020833125); EXPECT_FLOAT_EQ(std_c_ffv[0][0].d_.val_.adj(), 0.960456220449047); EXPECT_FLOAT_EQ(std_c_ffv[0][1].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[0][2].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[1][0].d_.val_.adj(), -0.340011984816337); EXPECT_FLOAT_EQ(std_c_ffv[1][1].d_.val_.adj(), 1.23635034397741); EXPECT_FLOAT_EQ(std_c_ffv[1][2].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[2][0].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[2][1].d_.val_.adj(), -0.695045186550866); EXPECT_FLOAT_EQ(std_c_ffv[2][2].d_.val_.adj(), 0.44923217850675); EXPECT_FLOAT_EQ(std_c_ffv[3][0].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[3][1].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[3][2].d_.val_.adj(), -0.497500020833125); } TEST(ProbDistributionsOrdLog, fv_d_stvec) { using stan::math::fvar; using stan::math::ordered_logistic_lpmf; using stan::math::var; using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::vector_fv; std::vector<int> y{1, 2, 3, 4}; vector_fv lam_fv(4); lam_fv << -3.18, -2.06, 0.52, 1.82; for (int i = 0; i < 4; i++) lam_fv[i].d_ = 1.0; vector_fv c1_fv(3); c1_fv << -1.02, -0.13, 0.86; for (int i = 0; i < 3; i++) c1_fv[i].d_ = 1.0; vector_fv c2_fv(3); c2_fv << -2.38, -1.80, -0.60; for (int i = 0; i < 3; i++) c2_fv[i].d_ = 1.0; vector_fv c3_fv(3); c3_fv << -0.61, 0.25, 1.36; for (int i = 0; i < 3; i++) c3_fv[i].d_ = 1.0; vector_fv c4_fv(3); c4_fv << -1.07, -0.37, 2.69; for (int i = 0; i < 3; i++) c4_fv[i].d_ = 1.0; vector_ffv lam_ffv(4); lam_ffv << -3.18, -2.06, 0.52, 1.82; for (int i = 0; i < 4; i++) { lam_ffv[i].d_ = 1.0; lam_ffv[i].val_.d_ = 1.0; } vector_ffv c1_ffv(3); c1_ffv << -1.02, -0.13, 0.86; for (int i = 0; i < 3; i++) { c1_ffv[i].d_ = 1.0; c1_ffv[i].val_.d_ = 1.0; } vector_ffv c2_ffv(3); c2_ffv << -2.38, -1.80, -0.60; for (int i = 0; i < 3; i++) { c2_ffv[i].d_ = 1.0; c2_ffv[i].val_.d_ = 1.0; } vector_ffv c3_ffv(3); c3_ffv << -0.61, 0.25, 1.36; for (int i = 0; i < 3; i++) { c3_ffv[i].d_ = 1.0; c3_ffv[i].val_.d_ = 1.0; } vector_ffv c4_ffv(3); c4_ffv << -1.07, -0.37, 2.69; for (int i = 0; i < 3; i++) { c4_ffv[i].d_ = 1.0; c4_ffv[i].val_.d_ = 1.0; } vector_d lam_d(4); lam_d << -3.18, -2.06, 0.52, 1.82; vector_d c1_d(3); c1_d << -1.02, -0.13, 0.86; vector_d c2_d(3); c2_d << -2.38, -1.80, -0.60; vector_d c3_d(3); c3_d << -0.61, 0.25, 1.36; vector_d c4_d(3); c4_d << -1.07, -0.37, 2.69; std::vector<vector_fv> std_c_fv{c1_fv, c2_fv, c3_fv, c4_fv}; std::vector<vector_ffv> std_c_ffv{c1_ffv, c2_ffv, c3_ffv, c4_ffv}; std::vector<vector_d> std_c_d{c1_d, c2_d, c3_d, c4_d}; fvar<var> out_fv = ordered_logistic_lpmf(y, lam_fv, std_c_d); out_fv.d_.grad(); EXPECT_FLOAT_EQ(out_fv.val_.val(), -4.59320177226145); EXPECT_FLOAT_EQ(out_fv.d_.val(), 0.718029597231206); EXPECT_FLOAT_EQ(lam_fv[0].d_.adj(), -0.10340045145825); EXPECT_FLOAT_EQ(lam_fv[1].d_.adj(), -0.01468796034572); EXPECT_FLOAT_EQ(lam_fv[2].d_.adj(), 0.131372311037084); EXPECT_FLOAT_EQ(lam_fv[3].d_.adj(), 0.704745697998091); out_fv = ordered_logistic_lpmf(y, lam_d, std_c_fv); out_fv.d_.grad(); EXPECT_FLOAT_EQ(out_fv.val_.val(), -4.59320177226145); EXPECT_FLOAT_EQ(out_fv.d_.val(), -0.718029597231206); EXPECT_FLOAT_EQ(std_c_fv[0][0].d_.adj(), 0.10340045145825); EXPECT_FLOAT_EQ(std_c_fv[0][1].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[0][2].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[1][0].d_.adj(), -1.69287817572205); EXPECT_FLOAT_EQ(std_c_fv[1][1].d_.adj(), 1.70756613606778); EXPECT_FLOAT_EQ(std_c_fv[1][2].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[2][0].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[2][1].d_.adj(), -0.924462566644255); EXPECT_FLOAT_EQ(std_c_fv[2][2].d_.adj(), 0.793090255607171); EXPECT_FLOAT_EQ(std_c_fv[3][0].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[3][1].d_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_fv[3][2].d_.adj(), -0.704745697998091); fvar<fvar<var>> out_ffv = ordered_logistic_lpmf(y, lam_ffv, std_c_d); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -4.59320177226145); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val(), 0.718029597231206); EXPECT_FLOAT_EQ(lam_ffv[0].d_.val_.adj(), -0.10340045145825); EXPECT_FLOAT_EQ(lam_ffv[1].d_.val_.adj(), -0.01468796034572); EXPECT_FLOAT_EQ(lam_ffv[2].d_.val_.adj(), 0.131372311037084); EXPECT_FLOAT_EQ(lam_ffv[3].d_.val_.adj(), 0.704745697998091); out_ffv = ordered_logistic_lpmf(y, lam_d, std_c_ffv); out_ffv.d_.val_.grad(); EXPECT_FLOAT_EQ(out_ffv.val_.val_.val(), -4.59320177226145); EXPECT_FLOAT_EQ(out_ffv.d_.val_.val(), -0.718029597231206); EXPECT_FLOAT_EQ(std_c_ffv[0][0].d_.val_.adj(), 0.10340045145825); EXPECT_FLOAT_EQ(std_c_ffv[0][1].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[0][2].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[1][0].d_.val_.adj(), -1.69287817572205); EXPECT_FLOAT_EQ(std_c_ffv[1][1].d_.val_.adj(), 1.70756613606778); EXPECT_FLOAT_EQ(std_c_ffv[1][2].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[2][0].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[2][1].d_.val_.adj(), -0.924462566644255); EXPECT_FLOAT_EQ(std_c_ffv[2][2].d_.val_.adj(), 0.793090255607171); EXPECT_FLOAT_EQ(std_c_ffv[3][0].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[3][1].d_.val_.adj(), 0.0); EXPECT_FLOAT_EQ(std_c_ffv[3][2].d_.val_.adj(), -0.704745697998091); }
16,783
10,861
/** * TitaniumKit Titanium.Media.AudioPlayer * * Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License. * Please see the LICENSE included with this distribution for details. */ #include "Titanium/Media/AudioPlayer.hpp" #include "Titanium/detail/TiImpl.hpp" namespace Titanium { namespace Media { AudioPlayer::AudioPlayer(const JSContext& js_context) TITANIUM_NOEXCEPT : Module(js_context, "Ti.Media.AudioPlayer") , state_buffering__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Buffering))) , state_initialized__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Initialized))) , state_paused__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Paused))) , state_playing__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Playing))) , state_starting__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Starting))) , state_stopped__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Stopped))) , state_stopping__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Stopping))) , state_waiting_for_data__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::WaitingForData))) , state_waiting_for_queue__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::WaitingForQueue))) , allowBackground__(false) , autoplay__(false) , bitRate__(0) , idle__(false) , paused__(false) , playing__(false) , state__(AudioState::Stopped) , url__("") , volume__(0) , waiting__(false) , bufferSize__(0) { } TITANIUM_PROPERTY_READWRITE(AudioPlayer, bool, allowBackground) TITANIUM_PROPERTY_READWRITE(AudioPlayer, bool, autoplay) TITANIUM_PROPERTY_READWRITE(AudioPlayer, std::uint32_t, bitRate) TITANIUM_PROPERTY_READ(AudioPlayer, std::chrono::milliseconds, duration) TITANIUM_PROPERTY_READ(AudioPlayer, bool, idle) TITANIUM_PROPERTY_READWRITE(AudioPlayer, bool, paused) TITANIUM_PROPERTY_READ(AudioPlayer, bool, playing) TITANIUM_PROPERTY_READ(AudioPlayer, std::chrono::milliseconds, progress) TITANIUM_PROPERTY_READ(AudioPlayer, AudioState, state) TITANIUM_PROPERTY_READWRITE(AudioPlayer, std::string, url) TITANIUM_PROPERTY_READWRITE(AudioPlayer, double, volume) TITANIUM_PROPERTY_READ(AudioPlayer, bool, waiting) TITANIUM_PROPERTY_READWRITE(AudioPlayer, std::uint32_t, bufferSize) TITANIUM_PROPERTY_READWRITE(AudioPlayer, std::chrono::milliseconds, time) bool AudioPlayer::isPaused() TITANIUM_NOEXCEPT { return (get_state() == AudioState::Paused); } bool AudioPlayer::isPlaying() TITANIUM_NOEXCEPT { return (get_state() == AudioState::Playing); } void AudioPlayer::pause() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::pause: Unimplemented"); } void AudioPlayer::play() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::play: Unimplemented"); } void AudioPlayer::release() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::release: Unimplemented"); } void AudioPlayer::start() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::start: Unimplemented"); } std::string AudioPlayer::stateDescription(const AudioState& state) TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::stateDescription: Unimplemented"); return ""; } void AudioPlayer::stop() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::stop: Unimplemented"); } void AudioPlayer::JSExportInitialize() { JSExport<AudioPlayer>::SetClassVersion(1); JSExport<AudioPlayer>::SetParent(JSExport<Module>::Class()); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_BUFFERING); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_INITIALIZED); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_PAUSED); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_PLAYING); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_STARTING); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_STOPPED); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_STOPPING); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_WAITING_FOR_DATA); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_WAITING_FOR_QUEUE); TITANIUM_ADD_PROPERTY(AudioPlayer, allowBackground); TITANIUM_ADD_PROPERTY(AudioPlayer, autoplay); TITANIUM_ADD_PROPERTY(AudioPlayer, bitRate); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, duration); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, idle); TITANIUM_ADD_PROPERTY(AudioPlayer, paused); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, playing); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, progress); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, state); TITANIUM_ADD_PROPERTY(AudioPlayer, url); TITANIUM_ADD_PROPERTY(AudioPlayer, volume); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, waiting); TITANIUM_ADD_PROPERTY(AudioPlayer, bufferSize); TITANIUM_ADD_PROPERTY(AudioPlayer, time); TITANIUM_ADD_FUNCTION(AudioPlayer, isPaused); TITANIUM_ADD_FUNCTION(AudioPlayer, isPlaying); TITANIUM_ADD_FUNCTION(AudioPlayer, pause); TITANIUM_ADD_FUNCTION(AudioPlayer, play); TITANIUM_ADD_FUNCTION(AudioPlayer, release); TITANIUM_ADD_FUNCTION(AudioPlayer, start); TITANIUM_ADD_FUNCTION(AudioPlayer, stateDescription); TITANIUM_ADD_FUNCTION(AudioPlayer, stop); TITANIUM_ADD_FUNCTION(AudioPlayer, getAllowBackground); TITANIUM_ADD_FUNCTION(AudioPlayer, setAllowBackground); TITANIUM_ADD_FUNCTION(AudioPlayer, getAutoplay); TITANIUM_ADD_FUNCTION(AudioPlayer, setAutoplay); TITANIUM_ADD_FUNCTION(AudioPlayer, getBitRate); TITANIUM_ADD_FUNCTION(AudioPlayer, setBitRate); TITANIUM_ADD_FUNCTION(AudioPlayer, getDuration); TITANIUM_ADD_FUNCTION(AudioPlayer, getIdle); TITANIUM_ADD_FUNCTION(AudioPlayer, getPaused); TITANIUM_ADD_FUNCTION(AudioPlayer, setPaused); TITANIUM_ADD_FUNCTION(AudioPlayer, getPlaying); TITANIUM_ADD_FUNCTION(AudioPlayer, getProgress); TITANIUM_ADD_FUNCTION(AudioPlayer, getState); TITANIUM_ADD_FUNCTION(AudioPlayer, getUrl); TITANIUM_ADD_FUNCTION(AudioPlayer, setUrl); TITANIUM_ADD_FUNCTION(AudioPlayer, getVolume); TITANIUM_ADD_FUNCTION(AudioPlayer, setVolume); TITANIUM_ADD_FUNCTION(AudioPlayer, getWaiting); TITANIUM_ADD_FUNCTION(AudioPlayer, getBufferSize); TITANIUM_ADD_FUNCTION(AudioPlayer, setBufferSize); TITANIUM_ADD_FUNCTION(AudioPlayer, getTime); TITANIUM_ADD_FUNCTION(AudioPlayer, setTime); } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_BUFFERING) { return state_buffering__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_INITIALIZED) { return state_initialized__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_PAUSED) { return state_paused__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_PLAYING) { return state_playing__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_STARTING) { return state_starting__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_STOPPED) { return state_stopped__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_STOPPING) { return state_stopping__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_WAITING_FOR_DATA) { return state_waiting_for_data__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_WAITING_FOR_QUEUE) { return state_waiting_for_queue__; } TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, allowBackground) TITANIUM_PROPERTY_SETTER_BOOL(AudioPlayer, allowBackground) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, autoplay) TITANIUM_PROPERTY_SETTER_BOOL(AudioPlayer, autoplay) TITANIUM_PROPERTY_GETTER_UINT(AudioPlayer, bitRate) TITANIUM_PROPERTY_SETTER_UINT(AudioPlayer, bitRate) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, idle) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, paused) TITANIUM_PROPERTY_SETTER_BOOL(AudioPlayer, paused) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, playing) TITANIUM_PROPERTY_GETTER_STRING(AudioPlayer, url) TITANIUM_PROPERTY_SETTER_STRING(AudioPlayer, url) TITANIUM_PROPERTY_GETTER_DOUBLE(AudioPlayer, volume) TITANIUM_PROPERTY_SETTER_DOUBLE(AudioPlayer, volume) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, waiting) TITANIUM_PROPERTY_GETTER_UINT(AudioPlayer, bufferSize) TITANIUM_PROPERTY_SETTER_UINT(AudioPlayer, bufferSize) TITANIUM_PROPERTY_GETTER_TIME(AudioPlayer, time) TITANIUM_PROPERTY_SETTER_TIME(AudioPlayer, time) TITANIUM_PROPERTY_GETTER_ENUM(AudioPlayer, state) TITANIUM_PROPERTY_GETTER_TIME(AudioPlayer, duration) TITANIUM_PROPERTY_GETTER_TIME(AudioPlayer, progress) TITANIUM_FUNCTION(AudioPlayer, isPaused) { return get_context().CreateBoolean(isPaused()); } TITANIUM_FUNCTION(AudioPlayer, isPlaying) { return get_context().CreateBoolean(isPlaying()); } TITANIUM_FUNCTION(AudioPlayer, pause) { pause(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(AudioPlayer, play) { play(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(AudioPlayer, release) { release(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(AudioPlayer, start) { start(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(AudioPlayer, stateDescription) { ENSURE_UINT_AT_INDEX(state, 0); return get_context().CreateString(stateDescription(static_cast<AudioState>(state))); } TITANIUM_FUNCTION(AudioPlayer, stop) { stop(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getAllowBackground, allowBackground) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setAllowBackground, allowBackground) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getAutoplay, autoplay) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setAutoplay, autoplay) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getBitRate, bitRate) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setBitRate, bitRate) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getDuration, duration) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getIdle, idle) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getPaused, paused) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setPaused, paused) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getPlaying, playing) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getProgress, progress) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getState, state) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getUrl, url) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setUrl, url) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getVolume, volume) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setVolume, volume) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getWaiting, waiting) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getBufferSize, bufferSize) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setBufferSize, bufferSize) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getTime, time) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setTime, time) } // namespace Media } // namespace Titanium
10,923
4,637
#include<iostream> #include<cstdio> #include<algorithm> #define N 2000002 using namespace std; long long bz[N][3]; int d[100]; int n; void work(int x){ for (int i=2;(long long)i*i<=x;i++) if (x%i==0){ d[++d[0]]=i; while (!(x%i))x/=i; } if (x!=1)d[++d[0]]=x; } int main(){ scanf("%d",&n); bz[n][2]=1,bz[n-1][2]=-1; for (int i=n;i>=1;i--){ bz[i][0]+=bz[i+1][0],bz[i][1]+=bz[i+1][1],bz[i][2]+=bz[i+1][2]; if (bz[i][0]||bz[i][1]||bz[i][2]){ d[0]=0; work(i); if (d[1]==i){ bz[i][0]++; bz[i-1][0]--; continue; } for (int j=1;j<=d[0];j++){ int l=max(i-d[j],d[j]),r=i-1; if (l>r)continue; if (bz[i][2]) bz[l][1]--,bz[r][1]++; if (bz[i][1]) bz[l][0]--,bz[r][0]++; } } } for (int i=1;i<=n;i++) if (bz[i][0]){ printf("%d\n",i); return 0; } printf("%d\n",n); return 0; }
853
577
#ifndef DG_MARCHAND_HPP #define DG_MARCHAND_HPP #include <iostream> #include <sstream> #include <stdlib.h> #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #include "Taille_fenetre.hpp" #include "Global_taille_fenetre.hpp" #include "Hero.hpp" class Marchand { public: //////////////////////////////////////////////////////////// /// Default constructor /// /// \param app : Window in which the string will be displayed /// \param touches_Sys : Define the navigation keys /// \param h : Hero who bargains /// //////////////////////////////////////////////////////////// Marchand(sf::RenderWindow *app, _touches_sys* touches_Sys, Hero *h); //////////////////////////////////////////////////////////// /// Events gestion /// /// \param event : Index of caught event /// //////////////////////////////////////////////////////////// void getEvents(sf::Event event); //////////////////////////////////////////////////////////// /// Draw on the screen the different boxes /// //////////////////////////////////////////////////////////// void Draw(); //////////////////////////////////////////////////////////// // Merchant states //////////////////////////////////////////////////////////// enum buy_sell_enum { STATE_QUESTION = 0, STATE_BUY, STATE_SELL } state_buy_sell; enum action_enum { STATE_CHOOSE = 0, STATE_VALIDATION, STATE_WARNING } state_action; private: //////////////////////////////////////////////////////////// /// Update the items possesed by the hero /// //////////////////////////////////////////////////////////// void UpdateItems(); //////////////////////////////////////////////////////////// /// Load the different merchant items /// //////////////////////////////////////////////////////////// inline void InitMerchantItems(); //////////////////////////////////////////////////////////// /// Load the images used by merchants /// //////////////////////////////////////////////////////////// inline void InitImages(); //////////////////////////////////////////////////////////// /// Load the strings used by merchants /// //////////////////////////////////////////////////////////// inline void InitStrings(); //////////////////////////////////////////////////////////// /// Load the competences modified by items /// //////////////////////////////////////////////////////////// inline void InitComps(); //////////////////////////////////////////////////////////// /// Inline functions for the events /// //////////////////////////////////////////////////////////// inline void keyRight(); inline void keyLeft(); inline void keyUp(); inline void keyDown(); inline void keyEnter(); inline void keyReturn(); //////////////////////////////////////////////////////////// /// Show a warning window with the "Ok" button /// /// \param s : string to display /// //////////////////////////////////////////////////////////// inline void Warning(std::string s); //////////////////////////////////////////////////////////// /// Show a validation window with the "Yes" and "No" buttons /// /// \param s : string to display /// //////////////////////////////////////////////////////////// inline void Validation(std::string s); //////////////////////////////////////////////////////////// /// Called when we leave the merchant /// //////////////////////////////////////////////////////////// void Quit(); //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// enum type_merchant_items { M_POTION_VIE = 0, M_POTION_MANA, M_SAUVEGARDES, M_TAILLE }; struct merchant_obj { std::string name; std::string description; int type; int price; int number; bool show; }; std::vector<struct merchant_obj> merchant_objects, hero_objects, *current_objects, *other_objects; struct comp { std::string name; STATS type; }; std::vector<struct comp> competences; _touches_sys* touchesSys; Hero* heros; sf::RenderWindow* App; sf::Image imgMerchantHeadBox, imgDescriptionBox, imgItemsBox, imgItemsBoxCursor, imgMoneyBox, imgCompetencesBox, imgValidationBox, imgValidationBoxButton, imgValidationBoxCursor, imgBuySellBox, imgBuySellBoxCursor; sf::Sprite sprMerchantHeadBox, sprDescriptionBox, sprItemsBox, sprItemsBoxCursor, sprMyMoneyBox, sprMerchantMoneyBox, sprCompetencesBox, sprValidationBox, sprValidationBoxButton, sprValidationBoxCursor, sprBuySellBox, sprBuySellBoxCursor; sf::String strDescription, strValidation, strValidationYes, strValidationNo, strValidationOk, strMyMoneyTitle, strMyMoney, strMerchantMoneyTitle, strMerchantMoney, strItemsTitle, strItemName, strItemPrice, strCompetencesTitle, strCompetenceName, strBuy, strSell, strQuit; int money, buy_sell_cursor, items_cursor, items_number, items_tobuysell_number; bool choice_cursor, must_update; }; #endif // DG_MARCHAND_HPP
7,228
1,604
/*! * \file ItemObserver.cpp * \brief A persistent observer of items in the world for the spatial world database. * * The world item observer will store item observations in a remote spatial world database by listening to a * rail_manipulation_msgs/SegmentedObjectList message. * * \author Russell Toris, WPI - rctoris@wpi.edu * \date May 5, 2015 */ // World Item Observer #include "world_item_observer/ItemObserver.h" // ROS #include <graspdb/Client.h> using namespace std; using namespace rail::spatial_temporal_learning; using namespace rail::pick_and_place; ItemObserver::ItemObserver() : worldlib::remote::Node() { // load the config okay_ &= this->loadWorldYamlFile(); // create the client we need spatial_world_client_ = this->createSpatialWorldClient(); okay_ &= spatial_world_client_->connect(); // connect to the grasp model database to check for items int port = pick_and_place::graspdb::Client::DEFAULT_PORT; string host("127.0.0.1"); string user("ros"); string password(""); string db("graspdb"); node_.getParam("/graspdb/host", host); node_.getParam("/graspdb/port", port); node_.getParam("/graspdb/user", user); node_.getParam("/graspdb/password", password); node_.getParam("/graspdb/db", db); pick_and_place::graspdb::Client client(host, port, user, password, db); if (client.connect()) { // add the items vector<string> objects; client.getUniqueGraspModelObjectNames(objects); for (size_t i = 0; i < objects.size(); i++) { world_.addItem(worldlib::world::Item(objects[i])); } ROS_INFO("Found %lu unique items in the world.", world_.getNumItems()); okay_ &= true; } // connect to the segmented objects topic string recognized_objects_topic("/object_recognition_listener/recognized_objects"); private_node_.getParam("recognized_objects_topic", recognized_objects_topic); recognized_objects_sub_ = node_.subscribe(recognized_objects_topic, 1, &ItemObserver::recognizedObjectsCallback, this); if (okay_) { ROS_INFO("Item Observer Initialized"); } } ItemObserver::~ItemObserver() { // clean up the client delete spatial_world_client_; } void ItemObserver::recognizedObjectsCallback(const rail_manipulation_msgs::SegmentedObjectListConstPtr &objects) const { // only work on a non-cleared list if (!objects->cleared) { size_t new_observation_count = 0; // used to keep track of what was seen where (to mark things as missing) map<string, vector<string> > seen; // only utilize recognized objects for (size_t i = 0; i < objects->objects.size(); i++) { const rail_manipulation_msgs::SegmentedObject &o = objects->objects[i]; // transform the centroid to the fixed frame (shift down the Z) const worldlib::geometry::Position offset(o.centroid.x, o.centroid.y, o.centroid.z - (o.height / 2.0)); const worldlib::geometry::Pose centroid(offset, worldlib::geometry::Orientation(o.orientation)); const string &frame_id = o.point_cloud.header.frame_id; const worldlib::geometry::Pose p_centroid_world = this->transformToWorld(centroid, frame_id); // check if it is on a surface size_t room_i, surface_i, placement_surface_i; if (world_.findPlacementSurface(p_centroid_world.getPosition(), room_i, surface_i, placement_surface_i)) { const worldlib::world::Room &room = world_.getRoom(room_i); const worldlib::world::Surface &surface = room.getSurface(surface_i); // check if it is recognized, otherwise just mark the surface as being seen if (o.recognized) { // determine the position of the item on the surface const worldlib::geometry::Pose p_centroid_room = room.fromParentFrame(p_centroid_world); const worldlib::geometry::Pose p_centroid_surface = surface.fromParentFrame(p_centroid_room); // create and store the Observation const worldlib::world::Item item(o.name, "", p_centroid_surface, o.width, o.depth, o.height); spatial_world_client_->addObservation(item, surface, p_centroid_surface); new_observation_count++; seen[surface.getName()].push_back(item.getName()); } else { seen[surface.getName()].push_back(""); } } } // check what items were no longer seen on the surface size_t removed_count = 0; for (map<string, vector<string> >::iterator iter = seen.begin(); iter != seen.end(); ++iter) { const string &surface_name = iter->first; const vector<string> &items_seen = iter->second; const vector<worldlib::world::Item> &world_items = world_.getItems(); for (size_t i = 0; i < world_items.size(); i++) { // check if the item was seen const worldlib::world::Item &cur = world_items[i]; if (std::find(items_seen.begin(), items_seen.end(), cur.getName()) == items_seen.end()) { // check if the item had been there previously if (spatial_world_client_->itemExistsOnSurface(cur.getName(), surface_name)) { // mark it as removed spatial_world_client_->markObservationsAsRemoved(cur.getName(), surface_name); removed_count++; } } } } ROS_INFO("Added %lu new observations and marked %lu as removed.", new_observation_count, removed_count); } }
5,449
1,672
/********************************************************************** * CC0 License ********************************************************************** * MergeBathy - Tool to combine one or more bathymetric data files onto a single input grid. * Modified in 2015 by Samantha J.Zambo(samantha.zambo@gmail.com) while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Todd Holland while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Nathaniel Plant while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Kevin Duvieilh while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Paul Elmore while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Will Avera while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Brian Bourgeois while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by A.Louise Perkins while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by David Lalejini while employed by the U.S.Naval Research Laboratory. * To the extent possible under law, the author(s) and the U.S.Naval Research Laboratory have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide.This software is distributed without any warranty. * You should have received a copy of the CC0 Public Domain Dedication along with this software.If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. **********************************************************************/ //============================================================================ // Grid.C // Downloaded from http:\\oldmill.uchicago.edu/~wilder/Code/grid/ << broken // Working site as of 3 Mar 2018: https://sites.google.com/site/jivsoft/Home #include "grid.h" using namespace std; //============================================================================ // SPECIALIZATIONS FOR UCGRID template<> ostream& operator<<(ostream& os, const ucgrid& g) { for (uint i = 0; i < g.rows(); ++i) { for (uint j = 0; j < g.cols(); ++j) os << setw(4) << (int) g(i, j) << " "; os << "\n"; } return os; } //============================================================================ // SPECIALIZATIONS FOR DGRID #ifdef USE_LAPACK const int izero = 0, ione = 1; const double dzero = 0, done = 1; const cplx zzero = 0.0, zone = 1.0; const char notrans = 'N'; extern "C" { //============================================================================ // Blas 1 routine to compute y = a * x + y // Note: dcopy/zcopy and dscal/zscal are not included here as they are // typically not much, if any, faster than non-Blas routines. void daxpy_(const int*, const double*, const double*, const int*, double*, const int*); void zaxpy_(const int*, const cplx*, const cplx*, const int*, cplx*, const int*); void drot_(const int*, double*, const int*, double*, const int*, const double*, const double*); void zrot_(const int*, cplx*, const int*, cplx*, const int*, const double*, const cplx*); void dlartg_(const double*, const double*, double*, double*, double*); void zlartg_(const cplx*, const cplx*, double*, cplx*, cplx*); //============================================================================ // Blas 3 routines to compute the matrix multiplication product of matrices. void dtrmm_(const char* side, const char* uplo, const char* tra, const char* diag, const int* m, const int* n, const double* alpha, const double* a, const int* lda, double* b, const int* ldb); void ztrmm_(const char* side, const char* uplo, const char* tra, const char* diag, const int* m, const int* n, const cplx* alpha, const cplx* a, const int* lda, cplx* b, const int* ldb); void dgemm_(const char*, const char*, const int*, const int*, const int*, const double*, const double*, const int*, const double*, const int*, const double*, double*, const int*); void zgemm_(const char*, const char*, const int*, const int*, const int*, const cplx*, const cplx*, const int*, const cplx*, const int*, const cplx*, cplx*, const int*); //============================================================================ // Blas 3 routines to solve a AX=B where A is triangular. // These are similar to the Lapack trtrs routines, but they also // allow for solving XA=B. void dtrsm_(const char*, const char*, const char*, const char*, const int*, const int*, const double*, const double*, const int*, const double*, const int*); void ztrsm_(const char*, const char*, const char*, const char*, const int*, const int*, const cplx*, const cplx*, const int*, const cplx*, const int*); //============================================================================ // Lapack routines to solve overdetermined or underdetermined systems. // using a QR or LQ factorization. void dgels_(const char* trans, const int* m, const int* n, const int* nrhs, double* a, const int* lda, double* b, const int* ldb, double* work, const int* lwork, int* info); void zgels_(const char* trans, const int* m, const int* n, const int* nrhs, cplx* a, const int* lda, cplx* b, const int* ldb, cplx* work, const int* lwork, int* info); //============================================================================ // Lapack routines to solve AX=B for square matrices A. void dgesv_(const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, int* info); void zgesv_(const int* n, const int* nrhs, cplx* a, const int* lda, int* ipiv, cplx* b, const int* ldb, int* info); void dsysv_(const char* uplo, const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, double* work, const int* lwork, int* info); void zsysv_(const char* uplo, const int* n, const int* nrhs, cplx* a, const int* lda, int* ipiv, cplx* b, const int* ldb, cplx* work, const int* lwork, int* info); void zhesv_(const char* uplo, const int* n, const int* nrhs, cplx* a, const int* lda, int* ipiv, cplx* b, const int* ldb, cplx* work, const int* lwork, int* info); void dposv_(const char* uplo, const int* n, const int* nrhs, double* a, const int* lda, double* b, const int* ldb, int* info); void zposv_(const char* uplo, const int* n, const int* nrhs, cplx* a, const int* lda, cplx* b, const int* ldb, int* info); //============================================================================ // Lapack routines to compute the eigenvalues and (optionally) the // eigenvectors of a matrix. void dgeev_(const char* jobvl, const char* jobvr, const int* n, double* a, const int* lda, double* wr, double* wi, double* vl, const int* ldvl, double* vr, const int* ldvr, double* work, const int* lwork, int* info); void zgeev_(const char* jobvl, const char* jobvr, const int* n, cplx* a, const int* lda, cplx* w, cplx* vl, const int* ldvl, cplx* vr, const int* ldvr, cplx* work, const int* lwork, double* rwork, int* info); void dsyev_(const char* jobz, const char* uplo, const int* n, double* a, const int* lda, double* w, double* work, const int* lwork, int* info); void zheev_(const char* jobz, const char* uplo, const int* n, void* a, const int* lda, void* w, void* work, const int* lwork, const void* work2, int* info); //============================================================================ // Lapack routines to compute the singular values and singular vectors // of a general matrix. void dgesvd(const char* jobu, const char* jobvt, const int* m, const int* n, double* a, const int* lda, double* s, double* u, const int* ldu, double* vt, const int* ldvt, double* work, const int* lwork, int* info); void zgesvd(const char* jobu, const char* jobvt, const int* m, const int* n, cplx* a, const int* lda, double* s, cplx* u, const int* ldu, cplx* vt, const int* ldvt, cplx* work, const int* lwork, int* info); //============================================================================ // Lapack routines to compute the LU/Cholesky Factorization of a matrix // None are needed for triangular matrices... void dgetrf_(const int* m, const int* n, double* a, const int* lda, int* ipiv, int* info); void dsytrf_(const char* uplo, const int* n, double* a, const int* lda, int* ipiv, double* work, const int* lwork, int* info); void dpotrf_(const char* uplo, const int* n, double* a, const int* lda, int* info); void zgetrf_(const int* m, const int* n, cplx* a, const int* lda, int* ipiv, int* info); void zsytrf_(const char* uplo, const int* n, cplx* a, const int* lda, int* ipiv, cplx* work, const int* lwork, int* info); void zpotrf_(const char* uplo, const int* n, cplx* a, const int* lda, int* info); //============================================================================ // Lapack routines to solve a linear system using the // LU/Cholesky Factorization of a matrix void dgetrs_(const char* trans, const int* n, const int* nrhs, const double* a, const int* lda, const int* ipiv, double* b, const int* ldb, int* info); void dsytrs_(const char* uplo, const int* n, const int* nrhs, const double* a, const int* lda, const int* ipiv, double* b, const int* ldb, int* info); void dpotrs_(const char* uplo, const int* n, const int* nrhs, const double* a, const int* lda, double* b, const int* ldb, int* info); void dtrtrs_(const char* uplo, const char* trans, const char* diag, const int* n, const int* nrhs, const double* a, const int* lda, double* b, const int* ldb, int* info); void zgetrs_(const char* trans, const int* n, const int* nrhs, const cplx* a, const int* lda, const int* ipiv, cplx* b, const int* ldb, int* info); void zsytrs_(const char* uplo, const int* n, const int* nrhs, const cplx* a, const int* lda, const int* ipiv, cplx* b, const int* ldb, int* info); void zpotrs_(const char* uplo, const int* n, const int* nrhs, const cplx* a, const int* lda, cplx* b, const int* ldb, int* info); void ztrtrs_(const char* uplo, const char* trans, const char* diag, const int* n, const int* nrhs, const cplx* a, const int* lda, cplx* b, const int* ldb, int* info); //============================================================================ // Lapack routines to compute the inverse of a matrix void dgetri_(const int* n, double* a, const int* lda, const int* ipiv, double* work, const int* lwork, int* info); void dsytri_(const char* uplo, const int* n, double* a, const int* lda, const int* ipiv, double* work, int* info); void dpotri_(const char* uplo, const int* n, double* a, const int* lda, int* info); void dtrtri_(const char* uplo, const char* diag, const int* n, double* a, const int* lda, int* info); void zgetri_(const int* n, cplx* a, const int* lda, const int* ipiv, cplx* work, const int* lwork, int* info); void zsytri_(const char* uplo, const int* n, cplx* a, const int* lda, const int* ipiv, cplx* work, int* info); void zpotri_(const char* uplo, const int* n, cplx* a, const int* lda, int* info); void ztrtri_(const char* uplo, const char* diag, const int* n, cplx* a, const int* lda, int* info); } //============================================================================ // Compute the matrix product c = a %*% b of two grids/vectors: // More efficient: matmult(a, b, c); Less efficient: c = matmult(a, b); // If &c == &a or &c = &b, then 'a' or 'b' will get overwritten. template<> dgrid& matmult(const dgrid& a, const dgrid& b, dgrid& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || &c == &b) { dgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zgrid& matmult(const zgrid& a, const zgrid& b, zgrid& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || &c == &b) { zgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } template<> dgrid& matmult(const dgrid& a, const dvector& b, dgrid& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.size(), bc = 1; int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || (const dvector*)&c == &b) { dgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zgrid& matmult(const zgrid& a, const zvector& b, zgrid& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.size(), bc = 1; int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || (const zvector*)&c == &b) { zgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } template<> dgrid& matmult(const dvector& a, const dgrid& b, dgrid& c, char ta, char tb) { const int ar = a.size(), ac = 1, br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if ((const dvector*)&c == &a || &c == &b) { dgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zgrid& matmult(const zvector& a, const zgrid& b, zgrid& c, char ta, char tb) { const int ar = a.size(), ac = 1, br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if ((const zvector*)&c == &a || &c == &b) { zgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } template<> dvector& matmult(const dgrid& a, const dvector& b, dvector& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.size(), bc = 1; int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if (&c == (const dvector*)&a || &c == &b) { dvector tmp(m); c.swap(matmult(a, b, tmp, ta, tb)); } else { c.resize(m); fill(c.begin(), c.end(), 0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zvector& matmult(const zgrid& a, const zvector& b, zvector& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.size(), bc = 1; int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if (&c == (const zvector*)&a || &c == &b) { zvector tmp(m); c.swap(matmult(a, b, tmp, ta, tb)); } else { c.resize(m); fill(c.begin(), c.end(), 0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } template<> dvector& matmult(const dvector& a, const dgrid& b, dvector& c, char ta, char tb) { const int ar = a.size(), ac = 1, br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || &c == (const dvector*)&b) { dvector tmp(n); c.swap(matmult(a, b, tmp, ta, tb)); } else { c.resize(n); fill(c.begin(), c.end(), 0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zvector& matmult(const zvector& a, const zgrid& b, zvector& c, char ta, char tb) { const int ar = a.size(), ac = 1, br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || &c == (const zvector*)&b) { zvector tmp(n); c.swap(matmult(a, b, tmp, ta, tb)); } else { c.resize(n); fill(c.begin(), c.end(), 0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } //============================================================================ // Compute the eigenvalues, or the magnitudes of the eigenvalues, of a // square matrix 'a'. // These routines reasonably handle the case when either the 'evec' // or 'eval' matrices are the same matrix as 'a' or each other. template<> int eigenvalues(const dgrid& a, dgrid& eval, int gridtype, char ul) { int info = 0; if (&eval == &a) { dgrid tmp; info = eigenvalues(a, tmp, gridtype, ul); eval << tmp; return info; } if (a.rows() != a.cols()) throw dgrid::grid_error("eigenvalues: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } if (gridtype == gengrid) { dgrid evec = a; char jobvl = 'N', jobvr = 'N'; const int n = a.rows(), lwork = 8 * a.rows(); int info = 0; eval.resize(n); dgrid evali(n); dvector work(lwork); dgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &eval[0], &evali[0], 0, &n, 0, &n, &work[0], &lwork, &info); if (info == 0) { for (uint i = 0; i < (uint)n; ++i) eval[i] = std::sqrt(eval[i] * eval[i] + evali[i] * evali[i]); eval.sort(); } } else if (gridtype == symgrid) { dgrid evec = a; char jobz = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); eval.resize(n); dvector work(lwork); dsyev_(&jobz, &ul, &n, &evec[0], &n, &eval[0], &work[0], &lwork, &info); } else throw dgrid::grid_error("eigenvalues: Unknown grid type"); return info; } template<> int eigenvalues(const zgrid& a, dgrid& eval, int gridtype, char ul) { int info = 0; if (a.rows() != a.cols()) throw zgrid::grid_error("eigenvalues: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } if (gridtype == gengrid) { zgrid evec = a; char jobvl = 'N', jobvr = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); int info = 0; eval.resize(n); zvector work(lwork); dgrid rwork(2*n); zgrid evalz(n); zgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &evalz[0], 0, &n, 0, &n, &work[0], &lwork, &rwork[0], &info); for (uint i = 0; i < (uint)n; ++i) eval[i] = std::sqrt(std::abs(evalz[i]*evalz[i])); eval.sort(); } else if (gridtype == symgrid) { // Need evec, not 'a', since it is destroyed by dheev_ zgrid evec = a; char jobz = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); zvector work(lwork), work2(3 * n - 2); eval.resize(n); zheev_(&jobz, &ul, &n, &evec[0], &n, &eval[0], &work[0], &lwork, &work2[0], &info); } else throw zgrid::grid_error("eigenvalues: Unknown grid type"); return info; } template<> int eigenvalues(const dgrid& a, zgrid& eval, int gridtype, char ul) { int info = 0; if (a.rows() != a.cols()) throw dgrid::grid_error("eigenvalues: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } if (gridtype == gengrid) { dgrid evec = a; char jobvl = 'N', jobvr = 'N'; const int n = a.rows(), lwork = 8 * a.rows(); int info = 0; eval.resize(n); dgrid evalr(n), evali(n); dvector work(lwork); dgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &evalr[0], &evali[0], 0, &n, 0, &n, &work[0], &lwork, &info); if (info == 0) for (uint i = 0; i < (uint)n; ++i) eval[i] = cplx(evalr[i], evali[i]); } else if (gridtype == symgrid) { dgrid evec = a; char jobz = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); dgrid evald(n); dvector work(lwork); dsyev_(&jobz, &ul, &n, &evec[0], &n, &evald[0], &work[0], &lwork, &info); if (info == 0) eval = evald; } else throw dgrid::grid_error("eigenvalues: Unknown grid type"); return info; } template<> int eigenvalues(const zgrid& a, zgrid& eval, int gridtype, char ul) { int info = 0; if (&eval == &a) { zgrid tmp; info = eigenvalues(a, tmp, gridtype, ul); eval << tmp; return info; } if (a.rows() != a.cols()) throw zgrid::grid_error("eigenvalues: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } if (gridtype == gengrid) { zgrid evec = a; char jobvl = 'N', jobvr = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); int info = 0; eval.resize(n); zvector work(lwork); dgrid rwork(2*n); zgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &eval[0], 0, &n, 0, &n, &work[0], &lwork, &rwork[0], &info); } else if (gridtype == symgrid) { // Need 'evec', not 'a', since it is destroyed by dheev_ zgrid evec = a; char jobz = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); zvector work(lwork), work2(3 * n - 2); dgrid evald(n); zheev_(&jobz, &ul, &n, &evec[0], &n, &evald[0], &work[0], &lwork, &work2[0], &info); eval = evald; } else throw zgrid::grid_error("eigenvalues: Unknown grid type"); return info; } // Compute the eigenvalues and eigenvectors of a symmetric or hermetian matrix. template<> int eigenvectors(const dgrid& a, dgrid& evec, dgrid& eval, int gridtype, char ul) { int info = 0; if (&eval == &evec) throw dgrid::grid_error("eigenvectors: evec and eval are the same matrix"); if (&eval == &a) { dgrid tmp; info = eigenvectors(a, evec, tmp, gridtype, ul); eval << tmp; } else if (gridtype == gengrid) { throw dgrid::grid_error("eigenvectors: Not implemented for general grids"); dgrid evec = a; char jobvl = 'N', jobvr = 'V'; const int n = a.rows(), lwork = 8 * a.rows(); int info = 0; eval.resize(n); dgrid evali = eval; dvector work(lwork); dgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &eval[0], &evali[0], 0, &n, 0, &n, &work[0], &lwork, &info); } else if (gridtype == symgrid) { evec = a; if (a.rows() != a.cols()) throw dgrid::grid_error("eigenvectors: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } char jobz = 'V'; const int n = a.rows(), lwork = 4 * a.rows(); eval.resize(n); dvector work(lwork); dsyev_(&jobz, &ul, &n, &evec[0], &n, &eval[0], &work[0], &lwork, &info); } else throw dgrid::grid_error("eigenvalues: Unknown grid type"); return info; } template<> int eigenvectors(const zgrid& a, zgrid& evec, dgrid& eval, int gridtype, char ul) { int info = 0; if (gridtype == gengrid) { throw zgrid::grid_error("eigenvectors: Not implemented for general grids"); zgrid evec = a; char jobvl = 'N', jobvr = 'V'; const int n = a.rows(), lwork = 4 * a.rows(); int info = 0; eval.resize(n); zvector work(lwork); dgrid rwork(2*n); zgrid evalz(n); zgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &evalz[0], 0, &n, 0, &n, &work[0], &lwork, &rwork[0], &info); for (uint i = 0; i < (uint)n; ++i) eval[i] = std::sqrt(std::abs(evalz[i]*evalz[i])); } else if (gridtype == symgrid) { evec = a; if (a.rows() != a.cols()) throw zgrid::grid_error("eigenvectors: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } char jobz = 'V'; const int n = a.rows(), lwork = 4 * a.rows(); zvector work(lwork), work2(3 * n - 2); eval.resize(n); zheev_(&jobz, &ul, &n, &evec[0], &n, &eval[0], &work[0], &lwork, &work2[0], &info); } else throw zgrid::grid_error("eigenvalues: Unknown grid type"); return info; } //============================================================================ // Compute the singular values of a symmetric or hermetian matrix // These routines reasonably handle the case when either the 'evec' // or 'eval' matrices are the same matrix as 'a' or each other. template<> int singularvalues(const dgrid& a, dgrid& sval) { int info = 0; throw dgrid::grid_error("singularvalues: Function not yet implemented"); return info; } template<> int singularvalues(const zgrid& a, dgrid& sval) { int info = 0; throw zgrid::grid_error("singularvalues: Function not yet implemented"); return info; } template<> int singularvectors(const dgrid& a, dgrid& svec, dgrid& sval) { int info = 0; throw dgrid::grid_error("singularvalues: Function not yet implemented"); return info; } template<> int singularvectors(const zgrid& a, zgrid& svec, dgrid& sval) { int info = 0; throw zgrid::grid_error("singularvalues: Function not yet implemented"); return info; } //============================================================================ // Use Lapack routines to compute the LU decomposition of a // grid using a LU decomposition appropriate for the type of grid. // For general and symmetric grids there will be be pivots. // If the grid type is positive definite, then the LU decomposition // is the Cholesky decomposition, and the parameter 'ul' is used // to indicate whether the 'U'pper (default) or 'L'ower Cholesky // factor is computed. For triangular matrices, the LU decomposition // is the original matrix. template<> int LU(const dgrid& a, dgrid& g, ivector& pivots, int gridtype, char ul) { if (a.rows() != a.cols()) throw dgrid::grid_error("LU: Grid is not square"); const int n = a.rows(); int info = 0; if (gridtype == gengrid) { g = a; pivots.resize(n); dgetrf_(&n, &n, &g[0], &n, &pivots[0], &info); } else if (gridtype == symgrid) { g = a; pivots.resize(n); dgrid work(n); dsytrf_(&ul, &n, &g[0], &n, &pivots[0], &work[0], &n, &info); } else if (gridtype == posgrid) info = chol(a, g, ul); else if (gridtype == trigrid) g = a; else throw dgrid::grid_error("LU: Unknown grid type"); return info; } template<> int LU(const zgrid& a, zgrid& g, ivector& pivots, int gridtype, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("LU: Grid is not square"); const int n = a.rows(); int info = 0; if (gridtype == gengrid) { g = a; pivots.resize(n); zgetrf_(&n, &n, &g[0], &n, &pivots[0], &info); } else if (gridtype == symgrid) { g = a; pivots.resize(n); zgrid work(n); zsytrf_(&ul, &n, &g[0], &n, &pivots[0], &work[0], &n, &info); } else if (gridtype == posgrid) info = chol(a, g, ul); else if (gridtype == trigrid) g = a; else throw zgrid::grid_error("LU: Unknown grid type"); return info; } // For positive definite grids, compute the Cholesky Factorization. template<> int chol(const dgrid& a, dgrid& g, char ul) { if (a.rows() != a.cols()) throw dgrid::grid_error("chol: Grid is not square"); g = a; const int n = (int) a.rows(); int info = 0; if (ul == 'U') for (int i = 0; i < n - 1; ++i) memset(&g[0] + i * n + i + 1, 0, sizeof(double) * (n - i - 1)); else for (int i = 1; i < n; ++i) memset(&g[0] + i * n, 0, sizeof(double) * i); dpotrf_(&ul, &n, &g[0], &n, &info); return info; } template<> int chol(const zgrid& a, zgrid& g, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("chol: Grid is not square"); g = a; const int n = (int) a.rows(); int info = 0; if (ul == 'U') for (int i = 0; i < n - 1; ++i) memset(&g[0] + i * n + i + 1, 0, sizeof(cplx) * (n - i - 1)); else for (int i = 1; i < n; ++i) memset(&g[0] + i * n, 0, sizeof(cplx) * i); zpotrf_(&ul, &n, &g[0], &n, &info); return info; } //============================================================================ // Solve the linear system a * x = b for square 'a' and arbitrary 'b' // assuming that 'a' contains a previously computed LU decomposition // of 'a'. The pivots matrix is ignored in the cases it is not needed. // Works fine if 'a' or 'b' are the same matrix as 'sol', in which case // 'a' or 'b' get overwritten with the solution. template<> int LUsolve(const dgrid& a, const dgrid& b, dgrid& sol, const ivector& pivots, int gridtype, char ul, char tr, char dg) { if (&sol == &a) { int info = 0; dgrid tmp = b; info = LUsolve(a, b, tmp, pivots, gridtype, ul, tr, dg); sol << tmp; return info; } if (a.rows() != a.cols()) throw dgrid::grid_error("LUsolve: Grid is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("LUsolve: Grids are not comformable"); sol = b; const int n = a.rows(), bc = b.cols(); int info = 0; if (gridtype == gengrid) dgetrs_(&tr, &n, &bc, &a[0], &n, &pivots[0], &sol[0], &n, &info); else if (gridtype == symgrid) dsytrs_(&ul, &n, &bc, &a[0], &n, &pivots[0], &sol[0], &n, &info); else if (gridtype == posgrid) dpotrs_(&ul, &n, &bc, &a[0], &n, &sol[0], &n, &info); else if (gridtype == trigrid) dtrtrs_(&ul, &tr, &dg, &n, &bc, &a[0], &n, &sol[0], &n, &info); else throw dgrid::grid_error("LUsolve: Unknown grid type"); return info; } template<> int LUsolve(const zgrid& a, const zgrid& b, zgrid& sol, const ivector& pivots, int gridtype, char ul, char tr, char dg) { if (&sol == &a) { int info = 0; zgrid tmp = b; info = LUsolve(a, b, tmp, pivots, gridtype, ul, tr, dg); sol << tmp; return info; } if (a.rows() != a.cols()) throw zgrid::grid_error("LUsolve: Grid is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("LUsolve: Grids are not comformable"); sol = b; const int n = a.rows(), bc = b.cols(); int info = 0; if (gridtype == gengrid) zgetrs_(&tr, &n, &bc, &a[0], &n, &pivots[0], &sol[0], &n, &info); else if (gridtype == symgrid) zsytrs_(&ul, &n, &bc, &a[0], &n, &pivots[0], &sol[0], &n, &info); else if (gridtype == posgrid) zpotrs_(&ul, &n, &bc, &a[0], &n, &sol[0], &n, &info); else if (gridtype == trigrid) ztrtrs_(&ul, &tr, &dg, &n, &bc, &a[0], &n, &sol[0], &n, &info); else throw zgrid::grid_error("LUsolve: Unknown grid type"); return info; } template<> int cholupdate(dgrid& a, dvector& x) { double ci, si, temp; const int n = a.rows(); for (int i = 0; i < n - 1; ++i) { dlartg_(&a[i * (1 + n)], &x[i], &ci, &si, &temp); a[i * (1 + n)] = temp; int j = n - i - 1; drot_(&j, &a[i + (i + 1) * n], &n, &x[i + 1], &ione, &ci, &si); } dlartg_(&a[n * n - 1], &x[n - 1], &ci, &si, &temp); a[n * n - 1] = temp; return 0; } template<> int cholupdate(zgrid& a, zvector& x) { double ci; cplx si, temp; const int n = a.rows(); for (int i = 0; i < n - 1; ++i) { zlartg_(&a[i * (1 + n)], &x[i], &ci, &si, &temp); a[i * (1 + n)] = temp; int j = n - i - 1; zrot_(&j, &a[i + (i + 1) * n], &n, &x[i + 1], &ione, &ci, &si); } zlartg_(&a[n * n - 1], &x[n - 1], &ci, &si, &temp); a[n * n - 1] = temp; return 0; } template<> int cholsolve(const dgrid& a, const dgrid& b, dgrid& sol, char ul) { if (&sol == &a) { int info = 0; dgrid tmp = b; info = cholsolve(a, b, tmp, ul); sol << tmp; return info; } if (a.rows() != a.cols()) throw dgrid::grid_error("cholsolve: Grid is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("cholsolve: Grids are not comformable"); sol = b; const int ar = a.rows(), bc = b.cols(); int info = 0; dpotrs_(&ul, &ar, &bc, &a[0], &ar, &sol[0], &ar, &info); return info; } template<> int cholsolve(const zgrid& a, const zgrid& b, zgrid& sol, char ul) { if (&sol == &a) { int info = 0; zgrid tmp = b; info = cholsolve(a, b, tmp, ul); sol << tmp; return info; } if (a.rows() != a.cols()) throw zgrid::grid_error("cholsolve: Grid is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("cholsolve: Grids are not comformable"); sol = b; const int ar = a.rows(), bc = b.cols(); int info = 0; zpotrs_(&ul, &ar, &bc, &a[0], &ar, &sol[0], &ar, &info); return info; } template<> int trsolve(const dgrid& a, const dgrid& b, dgrid& sol, char ul, char tr, char dg) { if (&sol == &a) { int info = 0; dgrid tmp = b; info = trsolve(a, b, tmp, ul, tr, dg); sol << tmp; return info; } if (a.rows() != a.cols()) throw dgrid::grid_error("trsolve: Grid is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("trsolve: Grids are not comformable"); sol = b; const int ar = a.rows(), bc = b.cols(); int info = 0; dtrtrs_(&ul, &tr, &dg, &ar, &bc, &a[0], &ar, &sol[0], &ar, &info); return info; } template<> int trsolve(const zgrid& a, const zgrid& b, zgrid& sol, char ul, char tr, char dg) { if (&sol == &a) { int info = 0; zgrid tmp = b; info = trsolve(a, b, tmp, ul, tr, dg); sol << tmp; return info; } if (a.rows() != a.cols()) throw zgrid::grid_error("trsolve: Grid is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("trsolve: Grids are not comformable"); sol = b; const int ar = a.rows(), bc = b.cols(); int info = 0; ztrtrs_(&ul, &tr, &dg, &ar, &bc, &a[0], &ar, &sol[0], &ar, &info); return info; } //============================================================================ // Use Lapack routines to compute the inverse of a grid using a LU // factorization appropriate for the type of grid. // The paramter 'ul' is used for symmetric and triangular grids and // indicates whether the 'U'pper (default) or 'L'ower triangle of the // grid should be used in the computations. For these matrices, if the // parameter 'fill' is true (default), then the entire inverse will be // computed. Otherwise, only the corresponding upper or lower half will // be computed, and the other half will essentially be garbage. // For triangular matrices, 'dg' can be 'N' (default) to indicate the // diagonal entries will be used, or 'U' to indicate they will be // assumed to be 1 and ignored. // Syntax 1: inv(a, ainv) template<> int inv(const dgrid& a, dgrid& g, int gridtype, char ul, bool fill, char dg) { if (a.rows() != a.cols()) throw dgrid::grid_error("inv: Grid is not square"); g = a; int n = g.rows(); int info = 0; if (gridtype == gengrid) { ivector ipiv(n); dvector work(n); dgetrf_(&n, &n, &g[0], &n, &ipiv[0], &info); if (info == 0) dgetri_(&n, &g[0], &n, &ipiv[0], &work[0], &n, &info); } else if (gridtype == symgrid) { ivector ipiv(n); dvector work(n); dsytrf_(&ul, &n, &g[0], &n, &ipiv[0], &work[0], &n, &info); if (info == 0) dsytri_(&ul, &n, &g[0], &n, &ipiv[0], &work[0], &info); } else if (gridtype == posgrid) { dpotrf_(&ul, &n, &g[0], &n, &info); if (info == 0) dpotri_(&ul, &n, &g[0], &n, &info); } else if (gridtype == trigrid) { dtrtri_(&ul, &dg, &n, &g[0], &n, &info); } if (info == 0 && fill && (gridtype == posgrid || gridtype == symgrid)) if (ul == 'U') for (int i = 1; i < n; ++i) for (int j = 0; j < i; ++j) g(i, j) = g(j, i); else for (int i = 0; i < n - 1; ++i) for (int j = i + 1; j < n; ++j) g(i, j) = g(j, i); return info; } // Syntax 2: ainv = inv(a) template<> dgrid inv(const dgrid& a, int gridtype, char ul, bool fill, char dg) { dgrid tmp; inv(a, tmp, gridtype, ul, fill, dg); return tmp; } // Syntax 1: inv(a, ainv) template<> int inv(const zgrid& a, zgrid& g, int gridtype, char ul, bool fill, char dg) { if (a.rows() != a.cols()) throw dgrid::grid_error("inv: Grid is not square"); g = a; const int n = g.rows(); int info = 0; if (gridtype == gengrid) { ivector ipiv(n); zvector work(n); zgetrf_(&n, &n, &g[0], &n, &ipiv[0], &info); if (info == 0) zgetri_(&n, &g[0], &n, &ipiv[0], &work[0], &n, &info); } else if (gridtype == posgrid) { zpotrf_(&ul, &n, &g[0], &n, &info); if (info == 0) zpotri_(&ul, &n, &g[0], &n, &info); } else if (gridtype == symgrid) { ivector ipiv(n); zvector work(n); zsytrf_(&ul, &n, &g[0], &n, &ipiv[0], &work[0], &n, &info); if (info == 0) zsytri_(&ul, &n, &g[0], &n, &ipiv[0], &work[0], &info); } else if (gridtype == trigrid) { ztrtri_(&ul, &dg, &n, &g[0], &n, &info); } if (info == 0 && fill && (gridtype == posgrid || gridtype == symgrid)) if (ul == 'U') for (int i = 1; i < n; ++i) for (int j = 0; j < i; ++j) g(i, j) = g(j, i); else for (int i = 0; i < n - 1; ++i) for (int j = i + 1; j < n; ++j) g(i, j) = g(j, i); return info; } // Syntax 2: ainv = a.inv() template<> zgrid inv(const zgrid& a, int gridtype, char ul, bool fill, char dg) { zgrid tmp; inv(a, tmp, gridtype, ul, fill, dg); return tmp; } //============================================================================ // Compute y = alpha * x + y dgrid& axpy(const dgrid& x, double alpha, dgrid& y) { if (x.size() != y.size()) throw dgrid::grid_error("axpy: Grids are not comformable"); const int as = x.size(); if (as != 0) daxpy_(&as, &alpha, &x[0], &ione, &y[0], &ione); return y; } zgrid& axpy(const zgrid& x, cplx alpha, zgrid& y) { if (x.size() != y.size()) throw zgrid::grid_error("axpy: Grids are not comformable"); const int as = x.size(); if (as != 0) zaxpy_(&as, &alpha, &x[0], &ione, &y[0], &ione); return y; } //============================================================================ // Compute c = alpha * a * b + beta * c dgrid& trmm(const dgrid& a, dgrid& b, double alpha, const char side, const char uplo, const char tra, const char diag) { if (a.cols() != b.rows()) throw dgrid::grid_error("trmm: Grids are not comformable"); if (&a == &b) throw dgrid::grid_error("trmm: The two grid arguments are the same grid"); if (a.size() != 0 && b.size() != 0) { const int ar = a.rows(), ac = a.cols(), bc = b.cols(); dtrmm_(&side, &uplo, &tra, &diag, &ac, &bc, &alpha, &a[0], &ar, &b[0], &ac); } return b; } zgrid& trmm(const zgrid& a, zgrid& b, const cplx& alpha, const char side, const char uplo, const char tra, const char diag) { if (a.cols() != b.rows()) throw zgrid::grid_error("trmm: Grids are not comformable"); if (&a == &b) throw zgrid::grid_error("trmm: The two grid arguments are the same grid"); if (a.size() != 0 && b.size() != 0) { const int ar = a.rows(), ac = a.cols(), bc = b.cols(); ztrmm_(&side, &uplo, &tra, &diag, &ac, &bc, &alpha, &a[0], &ar, &b[0], &ac); } return b; } dgrid& gemm(const dgrid& a, const dgrid& b, dgrid& c, double alpha, double beta, char tra, char trb) { if (a.cols() != b.rows() || a.rows() != c.rows() || b.cols() != c.cols()) throw dgrid::grid_error("gemm: Grids are not comformable"); if (&a == &c || &b == &c) throw dgrid::grid_error("gemm: Result grid is the same as one of the multipliers"); if (a.cols() != 0 && c.size() != 0) { const int ar = a.rows(), ac = a.cols(), bc = b.cols(); dgemm_(&tra, &trb, &ar, &bc, &ac, &alpha, &a[0], &ar, &b[0], &ac, &beta, &c[0], &ar); } return c; } zgrid& gemm(const zgrid& a, const zgrid& b, zgrid& c, const cplx& alpha, const cplx& beta, char tra, char trb) { if (a.cols() != b.rows() || a.rows() != c.rows() || b.cols() != c.cols()) throw zgrid::grid_error("gemm: Grids are not comformable"); if (&a == &c || &b == &c) throw zgrid::grid_error("gemm: Result grid is the same as one of the multipliers"); if (a.cols() != 0 && c.size() != 0) { const int ar = a.rows(), ac = a.cols(), bc = b.cols(); zgemm_(&tra, &trb, &ar, &bc, &ac, &alpha, &a[0], &ar, &b[0], &ac, &beta, &c[0], &ar); } return c; } //============================================================================ // Solve the over/under-determined linear system a * x = b for arbitary // 'a' and 'b' using a QR or LQ factorization. On exit, 'a' contains // its QR or LQ factorization, while the columns of 'b' contain the // solution 'x'. int gels(dgrid& a, dgrid& b, char trans) { if (a.rows() != b.rows()) throw dgrid::grid_error("gels: Grids are not comformable"); const int m = a.rows(), n = a.cols(), nrhs = b.cols(); int info = 0; const int lwork = 10 * (m + n + nrhs); dvector work(lwork); dgels_(&trans, &m, &n, &nrhs, &a[0], &m, &b[0], &m, &work[0], &lwork, &info); return info; } int gels(zgrid& a, zgrid& b, char trans) { if (a.rows() != b.rows()) throw zgrid::grid_error("gels: Grids are not comformable"); const int m = a.rows(), n = a.cols(), nrhs = b.cols(); int info = 0; const int lwork = 10 * (m + n + nrhs); zvector work(lwork); zgels_(&trans, &m, &n, &nrhs, &a[0], &m, &b[0], &m, &work[0], &lwork, &info); return info; } //============================================================================ // Solve the linear system a * x = b for square 'a' and arbitrary 'b'. // On exit, if 'a' and 'b' are not the same matrix, 'a' contains an LU or // Cholesky decomposition, and 'b' contains the solution 'x'. If 'a' and // 'b' are the same matrix, then they will contain the identity solution. // General square 'a' int gesv(dgrid& a, dgrid& b, ivector& pivots) { if (a.rows() != a.cols()) throw dgrid::grid_error("gesv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("gesv: Grids are not comformable"); if (&a == &b) { b = dgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); dgesv_(&n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &info); return info; } int gesv(zgrid& a, zgrid& b, ivector& pivots) { if (a.rows() != a.cols()) throw zgrid::grid_error("gesv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("gesv: Grids are not comformable"); if (&a == &b) { b = zgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); zgesv_(&n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &info); return info; } // Symmetric square 'a' int sysv(dgrid& a, dgrid& b, ivector& pivots, char ul) { if (a.rows() != a.cols()) throw dgrid::grid_error("sysv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("sysv: Grids are not comformable"); if (&a == &b) { b = dgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); const int lwork = 2 * n; dgrid work(lwork); dsysv_(&ul, &n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &work[0], &lwork, &info); return info; } int sysv(zgrid& a, zgrid& b, ivector& pivots, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("sysv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("sysv: Grids are not comformable"); if (&a == &b) { b = zgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); const int lwork = 2 * n; zgrid work(lwork); zsysv_(&ul, &n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &work[0], &lwork, &info); return info; } // Hermetian square 'a' int hesv(zgrid& a, zgrid& b, ivector& pivots, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("hesv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("hesv: Grids are not comformable"); if (&a == &b) { b = zgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); const int lwork = 2 * n; zgrid work(lwork); zhesv_(&ul, &n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &work[0], &lwork, &info); return info; } // Positive Definite square 'a' int posv(dgrid& a, dgrid& b, char ul) { if (a.rows() != a.cols()) throw dgrid::grid_error("posv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("posv: Grids are not comformable"); if (&a == &b) { b = dgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; dposv_(&ul, &n, &nrhs, &a[0], &n, &b[0], &n, &info); return info; } int posv(zgrid& a, zgrid& b, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("posv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("posv: Grids are not comformable"); if (&a == &b) { b = zgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; zposv_(&ul, &n, &nrhs, &a[0], &n, &b[0], &n, &info); return info; } //============================================================================ // Solve a triangular system (*this) * x = b for x using either // back or forward substitution. template<> dgrid& backsolve(const dgrid& a, const dgrid& b, dgrid& x, char ul) { x = b; if (ul == 'U') trsm(a, b, x, 1.0, 'L', 'U', 'N', 'N'); else trsm(a, b, x, 1.0, 'L', 'L', 'T', 'N'); return x; } template<> zgrid& backsolve(const zgrid& a, const zgrid& b, zgrid& x, char ul) { x = b; if (ul == 'U') trsm(a, b, x, 1.0, 'L', 'U', 'N', 'N'); else trsm(a, b, x, 1.0, 'L', 'L', 'T', 'N'); return x; } template<> dgrid& forwardsolve(const dgrid& a, const dgrid& b, dgrid& x, char ul) { x = b; if (ul == 'L') trsm(a, b, x, 1.0, 'L', 'L', 'N', 'N'); else trsm(a, b, x, 1.0, 'L', 'U', 'T', 'N'); return x; } template<> zgrid& forwardsolve(const zgrid& a, const zgrid& b, zgrid& x, char ul) { x = b; if (ul == 'L') trsm(a, b, x, 1.0, 'L', 'L', 'N', 'N'); else trsm(a, b, x, 1.0, 'L', 'U', 'T', 'N'); return x; } //============================================================================ // Solve prod(op(a), x) = alpha * b, where 'a' is a triangular matrix. // If 'sd' == 'L', prod(a,b) = a %*% b, otherwise, prod(a,b) = b %*% a. // If 'ul' == 'U', use upper half of 'a', otherwise use lower half. // If 'tr' == 'N', op(a) = a, otherwise op(a) = t(a). // If 'dg' != 'U', assume diagonal entries of 'a' are 1. // If x and b are equal, b will be overwritten with the solution x. dgrid& trsm(const dgrid& a, const dgrid& b, dgrid& x, double alpha, char sd, char ul, char tr, char dg) { if (sd != 'l' && sd != 'L') sd = 'R'; if (ul != 'u' && ul != 'U') ul = 'L'; if (tr != 'n' && tr != 'N') tr = 'T'; if (dg != 'n' && dg != 'N') dg = 'U'; x = b; const int br = b.rows(), bc = b.cols(), ar = a.rows(); dtrsm_(&sd, &ul, &tr, &dg, &br, &bc, &alpha, &a[0], &ar, &x[0], &br); return x; } zgrid& trsm(const zgrid& a, const zgrid& b, zgrid& x, const cplx& alpha, char sd, char ul, char tr, char dg) { if (sd != 'l' && sd != 'L') sd = 'R'; if (ul != 'u' && ul != 'U') ul = 'L'; if (tr != 'n' && tr != 'N') tr = 'T'; if (dg != 'n' && dg != 'N') dg = 'U'; x = b; const int br = b.rows(), bc = b.cols(), ar = a.rows(); ztrsm_(&sd, &ul, &tr, &dg, &br, &bc, &alpha, &a[0], &ar, &x[0], &br); return x; } //============================================================================ // grid.C #endif
49,066
19,384
#include "mgr.hpp" #include "if.hpp" namespace rev { ObjMgr::~ObjMgr() { constexpr int N_RETRY = 8; for(int i=0 ; i<N_RETRY ; i++) { // オブジェクトが無くなるまで繰り返しdestroy auto tmp = base_t::getResourceSet(); if(tmp->set.empty()) break; for(auto& obj : tmp->set) { try { if(auto sp = obj.weak.lock()) sp->destroy(); } catch(...) {} } } } void ObjMgr::setLua(const Lua_SP& ls) { _lua = ls; } const Lua_SP& ObjMgr::getLua() const noexcept { return _lua; } } #include "lua.hpp" namespace rev { // -------------------- ObjectT_LuaBase -------------------- bool detail::ObjectT_LuaBase::CallRecvMsg(const Lua_SP& ls, const HObj& hObj, LCValue& dst, const GMessageStr& msg, const LCValue& arg) { ls->push(hObj); LValueS lv(ls->getLS()); dst = lv.callMethodNRet(luaNS::RecvMsg, msg, arg); auto& tbl = *boost::get<LCTable_SP>(dst); if(tbl[1]) { const int sz = tbl.size(); for(int i=1 ; i<=sz ; i++) tbl[i] = std::move(tbl[i+1]); tbl.erase(tbl.find(sz)); return true; } return false; } // -------------------- U_ObjectUpd -------------------- struct U_ObjectUpd::St_None : StateT<St_None> {}; U_ObjectUpd::U_ObjectUpd() { setStateNew<St_None>(); } }
1,224
574
#pragma once #include <string> #include <unordered_map> #include <glpp/core/object/texture_atlas.hpp> #include <glpp/core/object/shader.hpp> namespace glpp::core::render { namespace detail { struct none_t {}; template <class T, class Y> constexpr ptrdiff_t get_offset(Y T::* ptr) { return reinterpret_cast<char*>(&(reinterpret_cast<T*>(0)->*ptr))-reinterpret_cast<char*>(0); } } template <class uniform_description_t = detail::none_t> class renderer_t { public: template <class... shader_t> renderer_t( const shader_t&... shaders ); template <class view_t> void render(const view_t& view); template <class view_t> void render_instanced(const view_t& view, size_t count); template <class T> void set_uniform_name(T uniform_description_t::* uniform, std::string name); template <class T> void set_uniform(T uniform_description_t::* uniform, const T& value); template <class T> void set_uniform_array(T uniform_description_t::* uniform, const T* value, const size_t size); void set_texture(const char* name, const object::texture_slot_t& texture_slot); void set_texture(const char* name, object::texture_slot_t&& texture_slot); template <class texture_slot_iterator> void set_texture_array(const char* name, texture_slot_iterator begin, texture_slot_iterator end); template <class Container> void set_texture_array(const char* name, const Container& container); template <class AllocPolicy> void set_texture_atlas(const char* name, const object::texture_atlas_slot_t<AllocPolicy>& texture_atlas); private: glpp::core::object::shader_program_t m_shader; std::unordered_map<size_t, GLint> m_uniform_map; std::unordered_map<std::string, object::texture_slot_t> m_texture_slots; }; /** * Implementation */ template <class uniform_description_t> template <class... shader_t> renderer_t<uniform_description_t>::renderer_t( const shader_t&... shaders ) : m_shader(shaders...) { } template <class uniform_description_t> template <class view_t> void renderer_t<uniform_description_t>::render(const view_t& view) { m_shader.use(); view.draw(); } template <class uniform_description_t> template <class view_t> void renderer_t<uniform_description_t>::render_instanced(const view_t& view, size_t count) { m_shader.use(); view.draw_instanced(count); } template <class uniform_description_t> template <class T> void renderer_t<uniform_description_t>::set_uniform_name(T uniform_description_t::* uniform, std::string name) { m_uniform_map[detail::get_offset(uniform)] = m_shader.uniform_location(name.c_str()); } template <class uniform_description_t> template <class T> void renderer_t<uniform_description_t>::set_uniform(T uniform_description_t::* uniform, const T& value) { const auto location_it = m_uniform_map.find(detail::get_offset(uniform)); if(location_it == m_uniform_map.end()) { throw std::runtime_error("Could find uniform name for this uniform. Add a call renderer_t::set_uniform_name before renderer_t::set_uniform."); } const auto location = location_it->second; m_shader.set_uniform(location, value); } template <class uniform_description_t> template <class T> void renderer_t<uniform_description_t>::set_uniform_array(T uniform_description_t::* uniform, const T* value, const size_t size) { const auto location_it = m_uniform_map.find(detail::get_offset(uniform)); if(location_it == m_uniform_map.end()) { throw std::runtime_error("Could find uniform name for this uniform. Add a call renderer_t::set_uniform_name before renderer_t::set_uniform."); } const auto location = location_it->second; m_shader.set_uniform_array(location, value, size); } template <class uniform_description_t> void renderer_t<uniform_description_t>::set_texture(const char* name, const object::texture_slot_t& texture_slot) { m_shader.set_texture(name, texture_slot); } template <class uniform_description_t> void renderer_t<uniform_description_t>::set_texture(const char* name, object::texture_slot_t&& texture_slot) { m_shader.set_texture(name, texture_slot); m_texture_slots[name]=std::move(texture_slot); } template <class uniform_description_t> template <class texture_slot_iterator> void renderer_t<uniform_description_t>::set_texture_array(const char* name, texture_slot_iterator begin, texture_slot_iterator end) { m_shader.set_texture_array(name, begin, end); } template <class uniform_description_t> template <class Container> void renderer_t<uniform_description_t>::set_texture_array(const char* name, const Container& container) { set_texture_array(name, container.begin(), container.end()); } template <class uniform_description_t> template <class AllocPolicy> void renderer_t<uniform_description_t>::set_texture_atlas(const char* name, const object::texture_atlas_slot_t<AllocPolicy>& texture_atlas_slots) { set_texture_array(name, texture_atlas_slots.begin(), texture_atlas_slots.end()); } }
4,874
1,686
#include "BookList.h" BookList::BookList(const BookList & anotherList) { capacity_ = anotherList.capacity_; booksCount_ = anotherList.booksCount_; books_ = new Book[capacity_]; for (int i = 0; i < booksCount_; i++) { anotherList.books_[i].setId(i+1); books_[i] = anotherList.books_[i]; } } BookList::BookList(int capacity) { capacity_ = capacity; booksCount_ = 0; books_ = new Book[capacity_]; for (int i = 0; i < capacity_; i++) { books_[i].setTitle(""); books_[i].setIsbn(""); books_[i].setCategory(""); } } void BookList::addBook(Book book) { if (booksCount_ <= capacity_) { books_[booksCount_] = book; booksCount_++; } } Book & BookList::searchBook(string name) { for (int i = 0; i < booksCount_; ++i) { if (books_[i].getTitle() == name) { return books_[i]; } } } Book & BookList::searchBook(int id) { for (int i = 0; i < booksCount_; ++i) { if (books_[i].getId() == id) { return books_[i]; } } } void BookList::deleteBook(int id) { for (int i = 0; i < booksCount_; ++i) { if (books_[i].getId() == id) { for (int j = i; j < booksCount_-1; ++j) { books_[j] = books_[j+1]; } } } booksCount_--; } Book &BookList::getTheHighestRatedBook() { int max = 0; for ( int i = 1; i < booksCount_; ++i) { if (books_[i].getAverageRating() > books_[max].getAverageRating()) { max = i; } } return books_[max]; } Book * BookList::getBooksForUser(User user) { for (int i = 0; i < booksCount_; i++) { if (books_[i].getAuthor() == user) { return &books_[i]; } } } Book &BookList::operator[](int position) { if (position < 0 || position >= capacity_) { cout << "Please enter an existing position" << endl; } else { booksCount_++; return books_[position]; } } void BookList::operator=(const BookList &anotherList) { capacity_ = anotherList.capacity_; booksCount_ = anotherList.booksCount_; books_ = new Book[capacity_]; for (int i = 0; i < booksCount_; i++) { anotherList.books_[i].setId(i+1); books_[i] = anotherList.books_[i]; } } ostream &operator << (ostream &output, BookList & bookList) { for (int i = 0; i < bookList.booksCount_; i++){ output << bookList.books_[i] << endl; } return output; } BookList::~BookList() { delete [] books_; }
2,660
958
#include "StdAfx.h" #include "DecompressClayfighter.h" #include "SharedFunctions.h" CDecompressClayfighter::CDecompressClayfighter(void) { } CDecompressClayfighter::~CDecompressClayfighter(void) { } int CDecompressClayfighter::Decompress(byte *output, byte *input) { bool bVar1; byte bVar2; byte bVar3; byte *pbVar4; byte *pbVar5; pbVar5 = output; while( true ) { while( true ) { bVar3 = *input; pbVar4 = input + 1; if ((bVar3 & 0x80) != 0) break; do { *pbVar5 = *pbVar4; pbVar4 = pbVar4 + 1; pbVar5 = pbVar5 + 1; bVar1 = bVar3 != 0; bVar3 = bVar3 - 1; input = pbVar4; } while (bVar1); } bVar2 = bVar3 & 0x7f; if (bVar3 == 0xff) break; bVar3 = *pbVar4; input = input + 2; do { *pbVar5 = bVar3; pbVar5 = pbVar5 + 1; bVar1 = bVar2 != 0; bVar2 = bVar2 - 1; } while (bVar1); } return (int)pbVar5 - (int)output; }
966
452
#ifndef __LISTAADJACENCIA_H__ #define __LISTAADJACENCIA_H__ #include <iostream> #include <vector> #include "Estrutura_de_dados.hpp" using namespace std; class NodeList { public: /* data */ //NodeList* prior; NodeList* next; int data; double weight; NodeList(int dataa); NodeList(int dataa, double weight); void set(int i); int get(); NodeList* get_next(); void add(NodeList* data); }; class ListaAdjacencia { private: NodeList* top; NodeList* last; NodeList* nextIterator; int iterator=0; int sizeLista; public: ListaAdjacencia(); ListaAdjacencia(int node); bool add(int data); void show(); bool search(int i); int size(); NodeList* getNodePosition(int position); NodeList* getTop(); bool sortedInsert(int val); bool sortedInsert(int val, double newWeight); }; class VectorListaAdjacencia: public EstruturaDeDados { private: vector<ListaAdjacencia> vetorDeListas; public: //VectorListaAdjacencia(int newSizeVector); void setSize(int newSizeVector); bool addAresta(int valor1, int valor2); bool addAresta(int valor1, int valor2, double weight); void show(bool weight); int vizinhoDeVertice(int vertice, int posicaoVizinho); pair <int,double> vizinhoDeVertice(int vertice, int posicaoVizinho, bool weight); int sizeVertice(int vertice); }; #endif
1,579
500
#ifndef PEOPLEEXTRACTORINTERFACESMA_SCENEFRAMEQUEUE_H #define PEOPLEEXTRACTORINTERFACESMA_SCENEFRAMEQUEUE_H #include <boost/interprocess/offset_ptr.hpp> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/containers/deque.hpp> #include <boost/interprocess/allocators/allocator.hpp> #include <string> #include "Image.hpp" namespace peopleextractor_interface_sma { //Define an STL compatible allocator of ints that allocates from the managed_shared_memory. //This allocator will allow placing containers in the segment typedef boost::interprocess::allocator<boost::interprocess::offset_ptr<Image>, boost::interprocess::managed_shared_memory::segment_manager> SceneframeQueueSMA; //Alias a deque that uses the previous STL-like allocator so that allocates its values from the segment typedef boost::interprocess::deque<boost::interprocess::offset_ptr<Image>, SceneframeQueueSMA> SceneframeQueue; const char* const NAME_SCENEFRAME_QUEUE = "SceneframeQueue"; } #endif //PEOPLEEXTRACTORINTERFACESMA_SCENEFRAMEQUEUE_H
1,057
351
#include "StableHeaders.h" #include "HoveringButtonsController.h" #include <QPushButton> #include <QMouseEvent> #include <QDebug> #include "RexLogicModule.h" namespace RexLogic { HoveringButtonsController::HoveringButtonsController() :text_padding_(10.0f) { Ui::HoveringButtonsWidget::setupUi(this); } HoveringButtonsController::~HoveringButtonsController() { } void HoveringButtonsController::ButtonPressed() { RexLogicModule::LogInfo( "Poke!" ); } void HoveringButtonsController::ForwardMouseClickEvent(float x, float y) { //To widgetspace float x_widgetspace = x*(float)this->width(); float y_widgetspace = y*(float)this->height(); QPoint pos(x_widgetspace,y_widgetspace); QMouseEvent e(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QApplication::sendEvent(this, &e); //Iterate through buttons and check if they are pressed for(int i = 0; i< layout()->count();i++) { QLayoutItem* item = layout()->itemAt(i); QAbstractButton *button = dynamic_cast<QAbstractButton*>(item->widget()); if(button) { if(button->rect().contains(button->mapFromParent(pos))) { QMouseEvent e(QEvent::MouseButtonPress, pos - button->pos(),pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QApplication::sendEvent(button, &e); } } } } void HoveringButtonsController::AddButton(QPushButton *button) { button->setParent(this); button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); button->setMaximumHeight(30); button->setMaximumWidth(60); QFont font(button->font()); QRect rect = button->fontMetrics().tightBoundingRect(button->text()); qreal scale = (button->maximumWidth() - text_padding_)/rect.width(); font.setPointSize(font.pointSizeF() * scale); button->setFont(font); QBoxLayout* layout = dynamic_cast<QBoxLayout*>(this->layout()); if(!layout) return; layout->insertWidget(0,button); QObject::connect(button, SIGNAL(pressed()), this, SLOT(ButtonPressed())); button->show(); } }
2,377
727
#include <string.h> #include "FrozenWasteland.hpp" #include "dsp/digital.hpp" #define NUM_RULERS 10 #define MAX_DIVISIONS 6 #define TRACK_COUNT 4 #define MAX_STEPS 18 #define sMIN(a,b) (((a)>(b))?(b):(a)) #define sMAX(a,b) (((a)>(b))?(a):(b)) namespace rack_plugin_FrozenWasteland { struct QuadEuclideanRhythm : Module { enum ParamIds { STEPS_1_PARAM, DIVISIONS_1_PARAM, OFFSET_1_PARAM, PAD_1_PARAM, ACCENTS_1_PARAM, ACCENT_ROTATE_1_PARAM, STEPS_2_PARAM, DIVISIONS_2_PARAM, OFFSET_2_PARAM, PAD_2_PARAM, ACCENTS_2_PARAM, ACCENT_ROTATE_2_PARAM, STEPS_3_PARAM, DIVISIONS_3_PARAM, OFFSET_3_PARAM, PAD_3_PARAM, ACCENTS_3_PARAM, ACCENT_ROTATE_3_PARAM, STEPS_4_PARAM, DIVISIONS_4_PARAM, OFFSET_4_PARAM, PAD_4_PARAM, ACCENTS_4_PARAM, ACCENT_ROTATE_4_PARAM, CHAIN_MODE_PARAM, CONSTANT_TIME_MODE_PARAM, NUM_PARAMS }; enum InputIds { STEPS_1_INPUT, DIVISIONS_1_INPUT, OFFSET_1_INPUT, PAD_1_INPUT, ACCENTS_1_INPUT, ACCENT_ROTATE_1_INPUT, START_1_INPUT, STEPS_2_INPUT, DIVISIONS_2_INPUT, OFFSET_2_INPUT, PAD_2_INPUT, ACCENTS_2_INPUT, ACCENT_ROTATE_2_INPUT, START_2_INPUT, STEPS_3_INPUT, DIVISIONS_3_INPUT, OFFSET_3_INPUT, PAD_3_INPUT, ACCENTS_3_INPUT, ACCENT_ROTATE_3_INPUT, START_3_INPUT, STEPS_4_INPUT, DIVISIONS_4_INPUT, OFFSET_4_INPUT, PAD_4_INPUT, ACCENTS_4_INPUT, ACCENT_ROTATE_4_INPUT, START_4_INPUT, CLOCK_INPUT, RESET_INPUT, MUTE_INPUT, NUM_INPUTS }; enum OutputIds { OUTPUT_1, ACCENT_OUTPUT_1, EOC_OUTPUT_1, OUTPUT_2, ACCENT_OUTPUT_2, EOC_OUTPUT_2, OUTPUT_3, ACCENT_OUTPUT_3, EOC_OUTPUT_3, OUTPUT_4, ACCENT_OUTPUT_4, EOC_OUTPUT_4, NUM_OUTPUTS }; enum LightIds { CHAIN_MODE_NONE_LIGHT, CHAIN_MODE_BOSS_LIGHT, CHAIN_MODE_EMPLOYEE_LIGHT, MUTED_LIGHT, CONSTANT_TIME_LIGHT, NUM_LIGHTS }; enum ChainModes { CHAIN_MODE_NONE, CHAIN_MODE_BOSS, CHAIN_MODE_EMPLOYEE }; bool beatMatrix[TRACK_COUNT][MAX_STEPS]; bool accentMatrix[TRACK_COUNT][MAX_STEPS]; int beatIndex[TRACK_COUNT]; int stepsCount[TRACK_COUNT]; float stepDuration[TRACK_COUNT]; float lastStepTime[TRACK_COUNT]; float maxStepCount; bool running[TRACK_COUNT]; int chainMode; bool initialized = false; bool muted = false; bool constantTime = false; float time = 0.0; float duration = 0.0; bool secondClockReceived = false; SchmittTrigger clockTrigger,resetTrigger,chainModeTrigger,constantTimeTrigger,muteTrigger,startTrigger[TRACK_COUNT]; PulseGenerator beatPulse[TRACK_COUNT],accentPulse[TRACK_COUNT],eocPulse[TRACK_COUNT]; QuadEuclideanRhythm() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS,NUM_LIGHTS) { for(unsigned i = 0; i < TRACK_COUNT; i++) { beatIndex[i] = 0; stepsCount[i] = MAX_STEPS; lastStepTime[i] = 0.0; stepDuration[i] = 0.0; running[i] = true; for(unsigned j = 0; j < MAX_STEPS; j++) { beatMatrix[i][j] = false; accentMatrix[i][j] = false; } } } void step() override; json_t *toJson() override { json_t *rootJ = json_object(); json_object_set_new(rootJ, "constantTime", json_integer((bool) constantTime)); json_object_set_new(rootJ, "chainMode", json_integer((int) chainMode)); json_object_set_new(rootJ, "muted", json_integer((bool) muted)); return rootJ; } void fromJson(json_t *rootJ) override { json_t *ctJ = json_object_get(rootJ, "constantTime"); if (ctJ) constantTime = json_integer_value(ctJ); json_t *cmJ = json_object_get(rootJ, "chainMode"); if (cmJ) chainMode = json_integer_value(cmJ); json_t *mutedJ = json_object_get(rootJ, "muted"); if (mutedJ) muted = json_integer_value(mutedJ); } void setRunningState() { for(int trackNumber=0;trackNumber<4;trackNumber++) { if(chainMode == CHAIN_MODE_EMPLOYEE && inputs[(trackNumber * 7) + 6].active) { //START Input needs to be active running[trackNumber] = false; } else { running[trackNumber] = true; } } } void advanceBeat(int trackNumber) { beatIndex[trackNumber]++; lastStepTime[trackNumber] = 0.0; //End of Cycle if(beatIndex[trackNumber] >= stepsCount[trackNumber]) { beatIndex[trackNumber] = 0; eocPulse[trackNumber].trigger(1e-3); //If in a chain mode, stop running until start trigger received if(chainMode != CHAIN_MODE_NONE && inputs[(trackNumber * 7) + 6].active) { //START Input needs to be active running[trackNumber] = false; } } } // For more advanced Module features, read Rack's engine.hpp header file // - onSampleRateChange: event triggered by a change of sample rate // - onReset, onRandomize, onCreate, onDelete: implements special behavior when user clicks these from the context menu }; void QuadEuclideanRhythm::step() { int levelArray[16]; int accentLevelArray[16]; int beatLocation[16]; //Set startup state if(!initialized) { setRunningState(); initialized = true; } // Modes if (constantTimeTrigger.process(params[CONSTANT_TIME_MODE_PARAM].value)) { constantTime = !constantTime; for(int trackNumber=0;trackNumber<4;trackNumber++) { beatIndex[trackNumber] = 0; } setRunningState(); } lights[CONSTANT_TIME_LIGHT].value = constantTime; if (chainModeTrigger.process(params[CHAIN_MODE_PARAM].value)) { chainMode = (chainMode + 1) % 3; setRunningState(); } lights[CHAIN_MODE_NONE_LIGHT].value = chainMode == CHAIN_MODE_NONE ? 1.0 : 0.0; lights[CHAIN_MODE_BOSS_LIGHT].value = chainMode == CHAIN_MODE_BOSS ? 1.0 : 0.0; lights[CHAIN_MODE_EMPLOYEE_LIGHT].value = chainMode == CHAIN_MODE_EMPLOYEE ? 1.0 : 0.0; lights[MUTED_LIGHT].value = muted ? 1.0 : 0.0; maxStepCount = 0; for(int trackNumber=0;trackNumber<4;trackNumber++) { //clear out the matrix and levels for(int j=0;j<16;j++) { beatMatrix[trackNumber][j] = false; accentMatrix[trackNumber][j] = false; levelArray[j] = 0; accentLevelArray[j] = 0; beatLocation[j] = 0; } float stepsCountf = params[trackNumber * 6].value; if(inputs[trackNumber * 7].active) { stepsCountf += inputs[trackNumber * 7].value; } stepsCountf = clamp(stepsCountf,0.0f,16.0f); float divisionf = params[(trackNumber * 6) + 1].value; if(inputs[(trackNumber * 7) + 1].active) { divisionf += inputs[(trackNumber * 7) + 1].value; } divisionf = clamp(divisionf,0.0f,stepsCountf); float offsetf = params[(trackNumber * 6) + 2].value; if(inputs[(trackNumber * 7) + 2].active) { offsetf += inputs[(trackNumber * 7) + 2].value; } offsetf = clamp(offsetf,0.0f,15.0f); float padf = params[trackNumber * 6 + 3].value; if(inputs[trackNumber * 7 + 3].active) { padf += inputs[trackNumber * 7 + 3].value; } padf = clamp(padf,0.0f,stepsCountf - divisionf); //Use this to reduce range of accent params/inputs so the range of motion of knob/modulation is more useful. float divisionScale = 1; if(stepsCountf > 0) { divisionScale = divisionf / stepsCountf; } float accentDivisionf = params[(trackNumber * 6) + 4].value * divisionScale; if(inputs[(trackNumber * 7) + 4].active) { accentDivisionf += inputs[(trackNumber * 7) + 4].value * divisionScale; } accentDivisionf = clamp(accentDivisionf,0.0f,divisionf); float accentRotationf = params[(trackNumber * 6) + 5].value * divisionScale; if(inputs[(trackNumber * 7) + 5].active) { accentRotationf += inputs[(trackNumber * 7) + 5].value * divisionScale; } if(divisionf > 0) { accentRotationf = clamp(accentRotationf,0.0f,divisionf-1); } else { accentRotationf = 0; } if(stepsCountf > maxStepCount) maxStepCount = stepsCountf; stepsCount[trackNumber] = int(stepsCountf); int division = int(divisionf); int offset = int(offsetf); int pad = int(padf); int accentDivision = int(accentDivisionf); int accentRotation = int(accentRotationf); if(stepsCount[trackNumber] > 0) { //Calculate Beats int level = 0; int restsLeft = sMAX(0,stepsCount[trackNumber]-division-pad); // just make sure no negatives do { levelArray[level] = sMIN(restsLeft,division); restsLeft = restsLeft - division; level += 1; } while (restsLeft > 0 && level < 16); int tempIndex =pad; int beatIndex = 0; for (int j = 0; j < division; j++) { beatMatrix[trackNumber][(tempIndex + offset) % stepsCount[trackNumber]] = true; beatLocation[beatIndex] = (tempIndex + offset) % stepsCount[trackNumber]; tempIndex++; beatIndex++; for (int k = 0; k < 16; k++) { if (levelArray[k] > j) { tempIndex++; } } } //Calculate Accents level = 0; restsLeft = sMAX(0,division-accentDivision); // just make sure no negatives do { accentLevelArray[level] = sMIN(restsLeft,accentDivision); restsLeft = restsLeft - accentDivision; level += 1; } while (restsLeft > 0 && level < 16); tempIndex =0; for (int j = 0; j < accentDivision; j++) { accentMatrix[trackNumber][beatLocation[(tempIndex + accentRotation) % division]] = true; tempIndex++; for (int k = 0; k < 16; k++) { if (accentLevelArray[k] > j) { tempIndex++; } } } } } if(inputs[RESET_INPUT].active) { if(resetTrigger.process(inputs[RESET_INPUT].value)) { for(int trackNumber=0;trackNumber<4;trackNumber++) { beatIndex[trackNumber] = 0; } setRunningState(); } } if(inputs[MUTE_INPUT].active) { if(muteTrigger.process(inputs[MUTE_INPUT].value)) { muted = !muted; } } //See if need to start up for(int trackNumber=0;trackNumber < 4;trackNumber++) { if(chainMode != CHAIN_MODE_NONE && inputs[(trackNumber * 7) + 6].active && !running[trackNumber]) { if(startTrigger[trackNumber].process(inputs[(trackNumber * 7) + 6].value)) { running[trackNumber] = true; } } } //Advance beat on trigger if not in constant time mode float timeAdvance =1.0 / engineGetSampleRate(); time += timeAdvance; if(inputs[CLOCK_INPUT].active) { if(clockTrigger.process(inputs[CLOCK_INPUT].value)) { if(secondClockReceived) { duration = time; } time = 0; secondClockReceived = true; for(int trackNumber=0;trackNumber < TRACK_COUNT;trackNumber++) { if(running[trackNumber]) { if(!constantTime) { advanceBeat(trackNumber); } } } } bool resyncAll = false; //For constant time, don't rely on clock trigger to advance beat, use time for(int trackNumber=0;trackNumber < TRACK_COUNT;trackNumber++) { if(stepsCount[trackNumber] > 0) stepDuration[trackNumber] = duration * maxStepCount / (float)stepsCount[trackNumber]; if(running[trackNumber]) { lastStepTime[trackNumber] +=timeAdvance; if(constantTime && stepDuration[trackNumber] > 0.0 && lastStepTime[trackNumber] >= stepDuration[trackNumber]) { advanceBeat(trackNumber); if(stepsCount[trackNumber] >= (int)maxStepCount && beatIndex[trackNumber] == 0) { resyncAll = true; } } } } if(resyncAll) { for(int trackNumber=0;trackNumber < TRACK_COUNT;trackNumber++) { lastStepTime[trackNumber] = 0; beatIndex[trackNumber] = 0; } } } // Set output to current state for(int trackNumber=0;trackNumber<TRACK_COUNT;trackNumber++) { float outputValue = (lastStepTime[trackNumber] < stepDuration[trackNumber] / 2) ? 10.0 : 0.0; //Send out beat if(beatMatrix[trackNumber][beatIndex[trackNumber]] == true && running[trackNumber] && !muted) { outputs[trackNumber * 3].value = outputValue; } else { outputs[trackNumber * 3].value = 0.0; } //send out accent if(accentMatrix[trackNumber][beatIndex[trackNumber]] == true && running[trackNumber] && !muted) { outputs[trackNumber * 3 + 1].value = outputValue; } else { outputs[trackNumber * 3 + 1].value = 0.0; } //Send out End of Cycle outputs[(trackNumber * 3) + 2].value = eocPulse[trackNumber].process(1.0 / engineGetSampleRate()) ? 10.0 : 0; } } struct QERBeatDisplay : TransparentWidget { QuadEuclideanRhythm *module; int frame = 0; std::shared_ptr<Font> font; QERBeatDisplay() { font = Font::load(assetPlugin(plugin, "res/fonts/Sudo.ttf")); } void drawBox(NVGcontext *vg, float stepNumber, float trackNumber,bool isBeat,bool isAccent,bool isCurrent) { //nvgSave(vg); //Rect b = Rect(Vec(0, 0), box.size); //nvgScissor(vg, b.pos.x, b.pos.y, b.size.x, b.size.y); nvgBeginPath(vg); float boxX = stepNumber * 22.5; float boxY = trackNumber * 22.5; float opacity = 0x80; // Testing using opacity for accents if(isAccent) { opacity = 0xff; } NVGcolor strokeColor = nvgRGBA(0xef, 0xe0, 0, 0xff); NVGcolor fillColor = nvgRGBA(0xef,0xe0,0,opacity); if(isCurrent) { strokeColor = nvgRGBA(0x2f, 0xf0, 0, 0xff); fillColor = nvgRGBA(0x2f,0xf0,0,opacity); } nvgStrokeColor(vg, strokeColor); nvgStrokeWidth(vg, 1.0); nvgRect(vg,boxX,boxY,21,21.0); if(isBeat) { nvgFillColor(vg, fillColor); nvgFill(vg); } nvgStroke(vg); } void draw(NVGcontext *vg) override { for(int trackNumber = 0;trackNumber < 4;trackNumber++) { for(int stepNumber = 0;stepNumber < module->stepsCount[trackNumber];stepNumber++) { bool isBeat = module->beatMatrix[trackNumber][stepNumber]; bool isAccent = module->accentMatrix[trackNumber][stepNumber]; bool isCurrent = module->beatIndex[trackNumber] == stepNumber && module->running[trackNumber]; drawBox(vg, float(stepNumber), float(trackNumber),isBeat,isAccent,isCurrent); } } } }; struct QuadEuclideanRhythmWidget : ModuleWidget { QuadEuclideanRhythmWidget(QuadEuclideanRhythm *module); }; QuadEuclideanRhythmWidget::QuadEuclideanRhythmWidget(QuadEuclideanRhythm *module) : ModuleWidget(module) { box.size = Vec(15*26, RACK_GRID_HEIGHT); { SVGPanel *panel = new SVGPanel(); panel->box.size = box.size; panel->setBackground(SVG::load(assetPlugin(plugin, "res/QuadEuclideanRhythm.svg"))); addChild(panel); } addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH - 12, 0))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH + 12, 0))); addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH - 12, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH + 12, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); { QERBeatDisplay *display = new QERBeatDisplay(); display->module = module; display->box.pos = Vec(16, 34); display->box.size = Vec(box.size.x-30, 135); addChild(display); } addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(22, 138), module, QuadEuclideanRhythm::STEPS_1_PARAM, 0.0, 16.2, 16.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(61, 138), module, QuadEuclideanRhythm::DIVISIONS_1_PARAM, 1.0, 16.2, 2.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(100, 138), module, QuadEuclideanRhythm::OFFSET_1_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(139, 138), module, QuadEuclideanRhythm::PAD_1_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(178, 138), module, QuadEuclideanRhythm::ACCENTS_1_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(217, 138), module, QuadEuclideanRhythm::ACCENT_ROTATE_1_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(22, 195), module, QuadEuclideanRhythm::STEPS_2_PARAM, 0.0, 16.0, 16.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(61, 195), module, QuadEuclideanRhythm::DIVISIONS_2_PARAM, 1.0, 16.2, 2.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(100, 195), module, QuadEuclideanRhythm::OFFSET_2_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(139, 195), module, QuadEuclideanRhythm::PAD_2_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(178, 195), module, QuadEuclideanRhythm::ACCENTS_2_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(217, 195), module, QuadEuclideanRhythm::ACCENT_ROTATE_2_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(22, 252), module, QuadEuclideanRhythm::STEPS_3_PARAM, 0.0, 16.2, 16.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(61, 252), module, QuadEuclideanRhythm::DIVISIONS_3_PARAM, 1.0, 16.2, 2.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(100, 252), module, QuadEuclideanRhythm::OFFSET_3_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(139, 252), module, QuadEuclideanRhythm::PAD_3_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(178, 252), module, QuadEuclideanRhythm::ACCENTS_3_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(217, 252), module, QuadEuclideanRhythm::ACCENT_ROTATE_3_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(22, 309), module, QuadEuclideanRhythm::STEPS_4_PARAM, 0.0, 16.2, 16.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(61, 309), module, QuadEuclideanRhythm::DIVISIONS_4_PARAM, 1.0, 16.2, 2.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(100, 309), module, QuadEuclideanRhythm::OFFSET_4_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(139, 309), module, QuadEuclideanRhythm::PAD_4_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(178, 309), module, QuadEuclideanRhythm::ACCENTS_4_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(217, 309), module, QuadEuclideanRhythm::ACCENT_ROTATE_4_PARAM, 0.0, 15.2, 0.0)); addParam(ParamWidget::create<CKD6>(Vec(250, 285), module, QuadEuclideanRhythm::CHAIN_MODE_PARAM, 0.0, 1.0, 0.0)); addParam(ParamWidget::create<CKD6>(Vec(335, 285), module, QuadEuclideanRhythm::CONSTANT_TIME_MODE_PARAM, 0.0, 1.0, 0.0)); addInput(Port::create<PJ301MPort>(Vec(23, 163), Port::INPUT, module, QuadEuclideanRhythm::STEPS_1_INPUT)); addInput(Port::create<PJ301MPort>(Vec(62, 163), Port::INPUT, module, QuadEuclideanRhythm::DIVISIONS_1_INPUT)); addInput(Port::create<PJ301MPort>(Vec(101, 163), Port::INPUT, module, QuadEuclideanRhythm::OFFSET_1_INPUT)); addInput(Port::create<PJ301MPort>(Vec(140, 163), Port::INPUT, module, QuadEuclideanRhythm::PAD_1_INPUT)); addInput(Port::create<PJ301MPort>(Vec(179, 163), Port::INPUT, module, QuadEuclideanRhythm::ACCENTS_1_INPUT)); addInput(Port::create<PJ301MPort>(Vec(218, 163), Port::INPUT, module, QuadEuclideanRhythm::ACCENT_ROTATE_1_INPUT)); addInput(Port::create<PJ301MPort>(Vec(23, 220), Port::INPUT, module, QuadEuclideanRhythm::STEPS_2_INPUT)); addInput(Port::create<PJ301MPort>(Vec(62, 220), Port::INPUT, module, QuadEuclideanRhythm::DIVISIONS_2_INPUT)); addInput(Port::create<PJ301MPort>(Vec(101, 220), Port::INPUT, module, QuadEuclideanRhythm::OFFSET_2_INPUT)); addInput(Port::create<PJ301MPort>(Vec(140, 220), Port::INPUT, module, QuadEuclideanRhythm::PAD_2_INPUT)); addInput(Port::create<PJ301MPort>(Vec(179, 220), Port::INPUT, module, QuadEuclideanRhythm::ACCENTS_2_INPUT)); addInput(Port::create<PJ301MPort>(Vec(218, 220), Port::INPUT, module, QuadEuclideanRhythm::ACCENT_ROTATE_2_INPUT)); addInput(Port::create<PJ301MPort>(Vec(23, 277), Port::INPUT, module, QuadEuclideanRhythm::STEPS_3_INPUT)); addInput(Port::create<PJ301MPort>(Vec(62, 277), Port::INPUT, module, QuadEuclideanRhythm::DIVISIONS_3_INPUT)); addInput(Port::create<PJ301MPort>(Vec(101, 277), Port::INPUT, module, QuadEuclideanRhythm::OFFSET_3_INPUT)); addInput(Port::create<PJ301MPort>(Vec(140, 277), Port::INPUT, module, QuadEuclideanRhythm::PAD_3_INPUT)); addInput(Port::create<PJ301MPort>(Vec(179, 277), Port::INPUT, module, QuadEuclideanRhythm::ACCENTS_3_INPUT)); addInput(Port::create<PJ301MPort>(Vec(218, 277), Port::INPUT, module, QuadEuclideanRhythm::ACCENT_ROTATE_3_INPUT)); addInput(Port::create<PJ301MPort>(Vec(23, 334), Port::INPUT, module, QuadEuclideanRhythm::STEPS_4_INPUT)); addInput(Port::create<PJ301MPort>(Vec(62, 334), Port::INPUT, module, QuadEuclideanRhythm::DIVISIONS_4_INPUT)); addInput(Port::create<PJ301MPort>(Vec(101, 334), Port::INPUT, module, QuadEuclideanRhythm::OFFSET_4_INPUT)); addInput(Port::create<PJ301MPort>(Vec(140, 334), Port::INPUT, module, QuadEuclideanRhythm::PAD_4_INPUT)); addInput(Port::create<PJ301MPort>(Vec(179, 334), Port::INPUT, module, QuadEuclideanRhythm::ACCENTS_4_INPUT)); addInput(Port::create<PJ301MPort>(Vec(218, 334), Port::INPUT, module, QuadEuclideanRhythm::ACCENT_ROTATE_4_INPUT)); addInput(Port::create<PJ301MPort>(Vec(262, 343), Port::INPUT, module, QuadEuclideanRhythm::CLOCK_INPUT)); addInput(Port::create<PJ301MPort>(Vec(302, 343), Port::INPUT, module, QuadEuclideanRhythm::RESET_INPUT)); addInput(Port::create<PJ301MPort>(Vec(335, 343), Port::INPUT, module, QuadEuclideanRhythm::MUTE_INPUT)); addInput(Port::create<PJ301MPort>(Vec(322, 145), Port::INPUT, module, QuadEuclideanRhythm::START_1_INPUT)); addInput(Port::create<PJ301MPort>(Vec(322, 175), Port::INPUT, module, QuadEuclideanRhythm::START_2_INPUT)); addInput(Port::create<PJ301MPort>(Vec(322, 205), Port::INPUT, module, QuadEuclideanRhythm::START_3_INPUT)); addInput(Port::create<PJ301MPort>(Vec(322, 235), Port::INPUT, module, QuadEuclideanRhythm::START_4_INPUT)); addOutput(Port::create<PJ301MPort>(Vec(255, 145), Port::OUTPUT, module, QuadEuclideanRhythm::OUTPUT_1)); addOutput(Port::create<PJ301MPort>(Vec(286, 145), Port::OUTPUT, module, QuadEuclideanRhythm::ACCENT_OUTPUT_1)); addOutput(Port::create<PJ301MPort>(Vec(354, 145), Port::OUTPUT, module, QuadEuclideanRhythm::EOC_OUTPUT_1)); addOutput(Port::create<PJ301MPort>(Vec(256, 175), Port::OUTPUT, module, QuadEuclideanRhythm::OUTPUT_2)); addOutput(Port::create<PJ301MPort>(Vec(286, 175), Port::OUTPUT, module, QuadEuclideanRhythm::ACCENT_OUTPUT_2)); addOutput(Port::create<PJ301MPort>(Vec(354, 175), Port::OUTPUT, module, QuadEuclideanRhythm::EOC_OUTPUT_2)); addOutput(Port::create<PJ301MPort>(Vec(256, 205), Port::OUTPUT, module, QuadEuclideanRhythm::OUTPUT_3)); addOutput(Port::create<PJ301MPort>(Vec(286, 205), Port::OUTPUT, module, QuadEuclideanRhythm::ACCENT_OUTPUT_3)); addOutput(Port::create<PJ301MPort>(Vec(354, 205), Port::OUTPUT, module, QuadEuclideanRhythm::EOC_OUTPUT_3)); addOutput(Port::create<PJ301MPort>(Vec(256, 235), Port::OUTPUT, module, QuadEuclideanRhythm::OUTPUT_4)); addOutput(Port::create<PJ301MPort>(Vec(286, 235), Port::OUTPUT, module, QuadEuclideanRhythm::ACCENT_OUTPUT_4)); addOutput(Port::create<PJ301MPort>(Vec(354, 235), Port::OUTPUT, module, QuadEuclideanRhythm::EOC_OUTPUT_4)); addChild(ModuleLightWidget::create<SmallLight<BlueLight>>(Vec(282, 285), module, QuadEuclideanRhythm::CHAIN_MODE_NONE_LIGHT)); addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(Vec(282, 300), module, QuadEuclideanRhythm::CHAIN_MODE_BOSS_LIGHT)); addChild(ModuleLightWidget::create<SmallLight<RedLight>>(Vec(282, 315), module, QuadEuclideanRhythm::CHAIN_MODE_EMPLOYEE_LIGHT)); addChild(ModuleLightWidget::create<LargeLight<RedLight>>(Vec(363, 347), module, QuadEuclideanRhythm::MUTED_LIGHT)); addChild(ModuleLightWidget::create<SmallLight<BlueLight>>(Vec(370, 295), module, QuadEuclideanRhythm::CONSTANT_TIME_LIGHT)); } } // namespace rack_plugin_FrozenWasteland using namespace rack_plugin_FrozenWasteland; RACK_PLUGIN_MODEL_INIT(FrozenWasteland, QuadEuclideanRhythm) { Model *modelQuadEuclideanRhythm = Model::create<QuadEuclideanRhythm, QuadEuclideanRhythmWidget>("Frozen Wasteland", "QuadEuclideanRhythm", "Quad Euclidean Rhythm", SEQUENCER_TAG); return modelQuadEuclideanRhythm; }
23,745
10,811
/* Desh, Salman Rahman: 13-23239-1 Amin, H.M. Ruhul: 13-23624-1 Hassan, Jahidul: 13-25373-1 Mahdi, Dewan Osman: 13-25368-3 */ #include <sstream> #include <stdio.h> #include <iostream> #include <windows.h> #include <GL/glut.h> #include <GL/freeglut.h> using namespace std; int viewY, viewX; int move_unit = 5; int m=0; int passAViewX=1, passBViewX=1; float passCViewX=1, passDViewX=1; void myInit (void) { glClearColor(0.0, 0.8, 1.0, 0.0); glPointSize(4.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 640.0, 0.0, 480.0); } /*Plane_Control_Keyboard*/ void keyboard(int key, int x, int y){ if (key == GLUT_KEY_UP){ viewY -= move_unit; cout<<"KEYBOARD_UP | "; } if (key == GLUT_KEY_DOWN){ viewY += move_unit; cout<<"KEYBOARD_DOWN | "; } if (key == GLUT_KEY_LEFT){ viewX -= move_unit; cout<<"KEYBOARD_LEFT | "; } if (key == GLUT_KEY_RIGHT){ viewX += move_unit; cout<<"KEYBOARD_RIGHT | "; } } void drawBitmapText(string caption, int score, float r, float g, float b, float x,float y,float z) { glColor3f(r,g,b); glRasterPos3f(x,y,z); stringstream strm; strm << caption << score; string text = strm.str(); for(string::iterator it = text.begin(); it != text.end(); ++it) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18 , *it); } } /*void viewScore(){ int s=0, m=10; do{ //drawBitmapText("Score: ", s, 255, 0 , 0, 550, 450, 0 ); drawBitmapText("Score: ", m, 255,0,0,100,400,0); //Sleep(1000); //s++; //system("CLS"); } while(s!=0); }*/ /*void print(int x, int y,int z, char *string) { //set the position of the text in the window using the x, y and z coordinates glRasterPos3f(x,y,z); //get the length of the string to display int len = (int) strlen(string); //loop to display character by character for(int f=0;f<10;f++){ for (int i = 0;i<len;i++) { glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24,string[i]); } } };*/ void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /******************************************/ /*------- custom code starts -------*/ drawBitmapText("Game Score: ", m, 255,255,255,530,450,0); /*plane_tail*/ glColor3ub (153, 76, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(10 + viewX, 330 - viewY); glVertex2i(15 + viewX, 330 - viewY); glVertex2i(35 + viewX, 310 - viewY); glVertex2i(15 + viewX, 290 - viewY); glEnd(); /*plane_wing_back*/ glColor3ub (204, 102, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(80 + viewX, 290 - viewY); glVertex2i(90 + viewX, 330 - viewY); glVertex2i(85 + viewX, 330 - viewY); glVertex2i(50 + viewX, 290 - viewY); glEnd(); /*plane_wing_design_back*/ glColor3ub (153, 76, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(80 + viewX, 290 - viewY); glVertex2i(90 + viewX, 330 - viewY); glVertex2i(88 + viewX, 330 - viewY); glVertex2i(55 + viewX, 290 - viewY); glEnd(); /*plane_body*/ glColor3ub (255, 128, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(90 + viewX, 280 - viewY); glVertex2i(30 + viewX, 280 - viewY); glVertex2i(15 + viewX, 290 - viewY); glVertex2i(35 + viewX, 310 - viewY); glVertex2i(80 + viewX, 310 - viewY); glVertex2i(90 + viewX, 300 - viewY); glEnd(); /*plane_body_design*/ glColor3ub(204, 102, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(90 + viewX, 295 - viewY); glVertex2i(30 + viewX, 295 - viewY); glVertex2i(30 + viewX, 300 - viewY); glVertex2i(90 + viewX, 300 - viewY); glEnd(); /*plane_front*/ glColor3ub (204, 102, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(90 + viewX, 280 - viewY); glVertex2i(90 + viewX, 300 - viewY); glVertex2i(100 + viewX, 285 - viewY); glVertex2i(100 + viewX, 280 - viewY); glEnd(); /*plane_pilot_glass*/ glColor3ub (204, 229, 255); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(90 + viewX, 300 - viewY); glVertex2i(80 + viewX, 310 - viewY); glVertex2i(75 + viewX, 305 - viewY); glVertex2i(75 + viewX, 300 - viewY); glEnd(); /*plane_wing*/ glColor3ub (204, 102, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(80 + viewX, 290 - viewY); glVertex2i(35 + viewX, 260 - viewY); glVertex2i(25 + viewX, 260 - viewY); glVertex2i(50 + viewX, 290 - viewY); glEnd(); /*plane_wing_design*/ glColor3ub (153, 76, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(80 + viewX, 290 - viewY); glVertex2i(35 + viewX, 260 - viewY); glVertex2i(30 + viewX, 260 - viewY); glVertex2i(55 + viewX, 290 - viewY); glEnd(); /*============DANGER_BOX_01===============================*/ /*main_box*/ glColor3ub (178, 190, 181); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(800 - passAViewX, 240); glVertex2i(770 - passAViewX, 240); glVertex2i(770 - passAViewX, 200); glVertex2i(800 - passAViewX, 200); glEnd(); /*--black*/ glColor3ub (0, 0 , 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passAViewX, 240); glVertex2i(780 - passAViewX, 240); glVertex2i(780 - passAViewX, 230); glVertex2i(790 - passAViewX, 230); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passAViewX, 230); glVertex2i(780 - passAViewX, 230); glVertex2i(780 - passAViewX, 220); glVertex2i(790 - passAViewX, 220); glEnd(); /*--black*/ glColor3ub (0, 0, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passAViewX, 220); glVertex2i(780 - passAViewX, 220); glVertex2i(780 - passAViewX, 210); glVertex2i(790 - passAViewX, 210); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passAViewX, 210); glVertex2i(780 - passAViewX, 210); glVertex2i(780 - passAViewX, 200); glVertex2i(790 - passAViewX, 200); glEnd(); /*============DANGER_BOX_02===============================*/ /*main_box*/ glColor3ub (178, 190, 181); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(800 - passBViewX, 140); glVertex2i(770 - passBViewX, 140); glVertex2i(770 - passBViewX, 100); glVertex2i(800 - passBViewX, 100); glEnd(); /*--black*/ glColor3ub (0, 0 , 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passBViewX, 140); glVertex2i(780 - passBViewX, 140); glVertex2i(780 - passBViewX, 130); glVertex2i(790 - passBViewX, 130); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passBViewX, 130); glVertex2i(780 - passBViewX, 130); glVertex2i(780 - passBViewX, 120); glVertex2i(790 - passBViewX, 120); glEnd(); /*--black*/ glColor3ub (0, 0, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passBViewX, 120); glVertex2i(780 - passBViewX, 120); glVertex2i(780 - passBViewX, 110); glVertex2i(790 - passBViewX, 110); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passBViewX, 110); glVertex2i(780 - passBViewX, 110); glVertex2i(780 - passBViewX, 100); glVertex2i(790 - passBViewX, 100); glEnd(); /*============DANGER_BOX_03===============================*/ /*main_box*/ glColor3ub (178, 190, 181); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(700 - passCViewX, 440); glVertex2i(670 - passCViewX, 440); glVertex2i(670 - passCViewX, 400); glVertex2i(700 - passCViewX, 400); glEnd(); /*--black*/ glColor3ub (0, 0 , 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passCViewX, 440); glVertex2i(680 - passCViewX, 440); glVertex2i(680 - passCViewX, 430); glVertex2i(690 - passCViewX, 430); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passCViewX, 430); glVertex2i(680 - passCViewX, 430); glVertex2i(680 - passCViewX, 420); glVertex2i(690 - passCViewX, 420); glEnd(); /*--black*/ glColor3ub (0, 0, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passCViewX, 420); glVertex2i(680 - passCViewX, 420); glVertex2i(680 - passCViewX, 410); glVertex2i(690 - passCViewX, 410); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passCViewX, 410); glVertex2i(680 - passCViewX, 410); glVertex2i(680 - passCViewX, 400); glVertex2i(690 - passCViewX, 400); glEnd(); /*============DANGER_BOX_04===============================*/ /*main_box*/ glColor3ub (178, 190, 181); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(700 - passDViewX, 340); glVertex2i(670 - passDViewX, 340); glVertex2i(670 - passDViewX, 300); glVertex2i(700 - passDViewX, 300); glEnd(); /*--black*/ glColor3ub (0, 0 , 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passDViewX, 340); glVertex2i(680 - passDViewX, 340); glVertex2i(680 - passDViewX, 330); glVertex2i(690 - passDViewX, 330); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passDViewX, 330); glVertex2i(680 - passDViewX, 330); glVertex2i(680 - passDViewX, 320); glVertex2i(690 - passDViewX, 320); glEnd(); /*--black*/ glColor3ub (0, 0, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passDViewX, 320); glVertex2i(680 - passDViewX, 320); glVertex2i(680 - passDViewX, 310); glVertex2i(690 - passDViewX, 310); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passDViewX, 310); glVertex2i(680 - passDViewX, 310); glVertex2i(680 - passDViewX, 300); glVertex2i(690 - passDViewX, 300); glEnd(); /*=====================LAND=========================*/ glColor3ub (43, 29 ,14); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(0, 0); glVertex2i(1000, 0); glVertex2i(1000, 35); glVertex2i(0, 35); glEnd(); glColor3ub (101, 101, 33); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(0, 35); glVertex2i(1000, 35); glVertex2i(1000, 45); glVertex2i(0, 45); glEnd(); glFlush (); /*------- custom code ends -------*/ /******************************************/ glutSwapBuffers(); glutPostRedisplay(); } /*Timer_Control_Object*/ void timerLoopA(int t1) { if (passAViewX >= 0) { passAViewX += 3; } if(passAViewX >= 1050) { passAViewX=0; m += 5; } glutPostRedisplay(); glutTimerFunc(15, timerLoopA, 0); } void timerLoopB(int t2) { if (passBViewX >= 0) { passBViewX += 2; } if(passBViewX >= 1050) { passBViewX=0; m += 5; } glutPostRedisplay(); glutTimerFunc(15, timerLoopB, 0); } void timerLoopC(int t3) { if (passCViewX >= 0) { passCViewX += 2.5; } if(passCViewX >= 1050) { passCViewX=0; m += 5; } glutPostRedisplay(); glutTimerFunc(15, timerLoopC, 0); } void timerLoopD(int t4) { if (passDViewX >= 0) { passDViewX += 2.75; } if(passDViewX >= 1050) { passDViewX=0; m += 5; } glutPostRedisplay(); glutTimerFunc(15, timerLoopD, 0); } /*void score(){ int s=0; for (;;){ system("CLS"); glRasterPos2f(400, 400); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, s); s++; Sleep(1000); } }*/ /*main_function*/ void main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(1208, 720); glutInitWindowPosition(0, 0); glutCreateWindow("Plane"); glutDisplayFunc(myDisplay); glutSpecialFunc(keyboard); glutTimerFunc(0, timerLoopA, 0); glutTimerFunc(0, timerLoopB, 0); glutTimerFunc(0, timerLoopC, 0); glutTimerFunc(0, timerLoopD, 0); myInit(); glutMainLoop(); }
11,296
5,691
#include<cstdio> #include<algorithm> using namespace std; int main(){ const int PRE_PROCESS_SIZE=40000; bool prime[PRE_PROCESS_SIZE]; fill(prime,prime+PRE_PROCESS_SIZE,true); prime[0]=prime[1]=false; for(int i=2;i<PRE_PROCESS_SIZE;i++) if(prime[i]) for(int j=2;i*j<PRE_PROCESS_SIZE;j++) prime[i*j]=false; while(true){ int n; scanf("%d",&n); if(n==0) break; int count=1; for(int i=2;i*i<=n;i++){ if(prime[i] && n%i==0){ count*=i-1; n/=i; while(n%i==0){ count*=i; n/=i; } } } if(n>1) count*=n-1; printf("%d\n",count); } return 0; }
637
355
// Paste me into the FileEdit configuration dialog #include <string> #include <vector> using namespace std; class $CLASSNAME$ { public: $RC$ $METHODNAME$( $METHODPARMS$ ) { } }; $BEGINCUT$ $TESTCODE$ $DEFAULTMAIN$ $ENDCUT$
252
106
// Time: O(n) // Space: O(n) class Solution { public: int maxProfit(int k, vector<int> &prices) { vector<int> profits; vector<pair<int, int>> v_p_stk; // mono stack, where v is increasing and p is strictly decreasing for (int v = -1, p = -1; p + 1 < size(prices);) { // at most O(n) peaks, so v_p_stk and profits are both at most O(n) space for (v = p + 1; v + 1 < size(prices); ++v) { if (prices[v] < prices[v + 1]) { break; } } for (p = v; p + 1 < size(prices); ++p) { if (prices[p] > prices[p + 1]) { break; } } while (!empty(v_p_stk) && (prices[v_p_stk.back().first] > prices[v])) { // not overlapped const auto [last_v, last_p] = move(v_p_stk.back()); v_p_stk.pop_back(); profits.emplace_back(prices[last_p] - prices[last_v]); // count [prices[last_v], prices[last_p]] interval } while (!empty(v_p_stk) && (prices[v_p_stk.back().second] <= prices[p])) { // overlapped // prices[last_v] <= prices[v] <= prices[last_p] <= prices[p], // treat overlapped as [prices[v], prices[last_p]], [prices[last_v], prices[p]] intervals due to invariant max profit const auto [last_v, last_p] = move(v_p_stk.back()); v_p_stk.pop_back(); profits.emplace_back(prices[last_p] - prices[v]); // count [prices[v], prices[last_p]] interval v = last_v; } v_p_stk.emplace_back(v, p); // keep [prices[last_v], prices[p]] interval to check overlapped } while (!empty(v_p_stk)) { const auto [last_v, last_p] = move(v_p_stk.back()); v_p_stk.pop_back(); profits.emplace_back(prices[last_p] - prices[last_v]); // count [prices[last_v], prices[last_p]] interval } if (k > size(profits)) { k = size(profits); } else { nth_element(begin(profits), begin(profits) + k - 1, end(profits), greater<int>()); } return accumulate(cbegin(profits), cbegin(profits) + k, 0); // top k profits of nonoverlapped intervals } };
2,265
802
#include "mkl.h" #include "../headers/calculations.h" int main(int _argc, char const *argv[]) { std::string filePath = argv[1]; //calculateRef(filePath); calculateImpl(filePath); return 0; }
209
79