hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0917f3eadd5ec51630c65b8da746d9d063c79f7a | 22,393 | cpp | C++ | mainwindow.cpp | mastercad/DBManager | aed1c515a6b3a3ad6d4ecbf42c2e8b44c9a41498 | [
"Libpng",
"Zlib"
] | null | null | null | mainwindow.cpp | mastercad/DBManager | aed1c515a6b3a3ad6d4ecbf42c2e8b44c9a41498 | [
"Libpng",
"Zlib"
] | null | null | null | mainwindow.cpp | mastercad/DBManager | aed1c515a6b3a3ad6d4ecbf42c2e8b44c9a41498 | [
"Libpng",
"Zlib"
] | null | null | null | #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(©Action, SIGNAL(triggered()), dbConnection, SLOT(copyResultViewSelection()));
menu->addAction(©Action);
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;
}
| 36.17609 | 268 | 0.663556 | mastercad |
091b507b80ac9b8007e71b48db5493edfad67ce8 | 88 | cpp | C++ | esl/economics/markets/ticker.cpp | rht/ESL | f883155a167d3c48e5ecdca91c8302fefc901c22 | [
"Apache-2.0"
] | 37 | 2019-10-13T12:23:32.000Z | 2022-03-19T10:40:29.000Z | esl/economics/markets/ticker.cpp | rht/ESL | f883155a167d3c48e5ecdca91c8302fefc901c22 | [
"Apache-2.0"
] | 3 | 2020-03-20T04:44:06.000Z | 2021-01-12T06:18:33.000Z | esl/economics/markets/ticker.cpp | vishalbelsare/ESL | cea6feda1e588d5f441742dbb1e4c5479b47d357 | [
"Apache-2.0"
] | 10 | 2019-11-06T15:59:06.000Z | 2021-08-09T17:28:24.000Z | //
// Created by Maarten on 23/06/2020.
//
#include <esl/economics/markets/ticker.hpp>
| 14.666667 | 43 | 0.693182 | rht |
091c3aa3ffe44824646d95909d3fa62068d0ab2e | 1,320 | hxx | C++ | client/default_colors.hxx | Drako/MPSnake | a22bd7156f79f9824ce689c54ac4a7ef085efd08 | [
"MIT"
] | null | null | null | client/default_colors.hxx | Drako/MPSnake | a22bd7156f79f9824ce689c54ac4a7ef085efd08 | [
"MIT"
] | null | null | null | client/default_colors.hxx | Drako/MPSnake | a22bd7156f79f9824ce689c54ac4a7ef085efd08 | [
"MIT"
] | null | null | null | #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
| 25.882353 | 83 | 0.689394 | Drako |
091f03ef4d78a125f2f72b6667e57c4fd3142e05 | 13,486 | cpp | C++ | FEM_CPP/main.cpp | ld-archer/E_FEM | 7db846a17f3c57e98b619d7a9c5860d3a71ccc1c | [
"MIT"
] | 2 | 2019-11-22T10:59:33.000Z | 2019-12-10T10:32:02.000Z | FEM_CPP/main.cpp | ld-archer/E_FEM | 7db846a17f3c57e98b619d7a9c5860d3a71ccc1c | [
"MIT"
] | 39 | 2019-11-22T10:39:07.000Z | 2022-03-21T15:32:18.000Z | FEM_CPP/main.cpp | ld-archer/E_FEM | 7db846a17f3c57e98b619d7a9c5860d3a71ccc1c | [
"MIT"
] | null | null | null |
#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();
}
| 30.442438 | 149 | 0.651787 | ld-archer |
092003d9cf0ba3280ca15da351c51ef13a4248ff | 6,742 | cpp | C++ | pomdog/experimental/gui/stack_panel.cpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 163 | 2015-03-16T08:42:32.000Z | 2022-01-11T21:40:22.000Z | pomdog/experimental/gui/stack_panel.cpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 17 | 2015-04-12T20:57:50.000Z | 2020-10-10T10:51:45.000Z | pomdog/experimental/gui/stack_panel.cpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 21 | 2015-04-12T20:45:11.000Z | 2022-01-14T20:50:16.000Z | // 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
| 29.060345 | 124 | 0.700979 | mogemimi |
09202c2533a6fc7dd34f1494ff33881ef3d60fa0 | 177,837 | cpp | C++ | External/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp | Sonicadvance1/FEX | d84b536c4a2f785870a714bd5ed9f914dff735a3 | [
"MIT"
] | 1 | 2020-05-24T22:00:46.000Z | 2020-05-24T22:00:46.000Z | External/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp | Sonicadvance1/FEX | d84b536c4a2f785870a714bd5ed9f914dff735a3 | [
"MIT"
] | null | null | null | External/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp | Sonicadvance1/FEX | d84b536c4a2f785870a714bd5ed9f914dff735a3 | [
"MIT"
] | null | null | null | #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);
}
}
| 35.868697 | 262 | 0.668764 | Sonicadvance1 |
09270f9b813223c4241a18d16d62e89f40aa4004 | 225 | cpp | C++ | Lists/ArrayList/main.cpp | coolzoa/Data-Structures | 623d0390ad4f5545f1456c3c4b441e37953b95c5 | [
"MIT"
] | null | null | null | Lists/ArrayList/main.cpp | coolzoa/Data-Structures | 623d0390ad4f5545f1456c3c4b441e37953b95c5 | [
"MIT"
] | null | null | null | Lists/ArrayList/main.cpp | coolzoa/Data-Structures | 623d0390ad4f5545f1456c3c4b441e37953b95c5 | [
"MIT"
] | null | null | null | #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;
} | 17.307692 | 29 | 0.555556 | coolzoa |
09277a46ea76f561b20269c505d93cdcdc85a7a7 | 6,443 | cc | C++ | src/openclx/program.cc | igankevich/openclx | 5063635392619eef84e536f24f8252ea41a5ffe6 | [
"Unlicense"
] | null | null | null | src/openclx/program.cc | igankevich/openclx | 5063635392619eef84e536f24f8252ea41a5ffe6 | [
"Unlicense"
] | null | null | null | src/openclx/program.cc | igankevich/openclx | 5063635392619eef84e536f24f8252ea41a5ffe6 | [
"Unlicense"
] | null | null | null | #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
| 27.185654 | 114 | 0.630141 | igankevich |
092902ce69874dd1af5f469fe42105021bd2cee6 | 104 | hpp | C++ | src/io/json.hpp | dbeurle/neon | 63cd2929a6eaaa0e1654c729cd35a9a52a706962 | [
"MIT"
] | 9 | 2018-07-12T17:06:33.000Z | 2021-11-20T23:13:26.000Z | src/io/json.hpp | dbeurle/neon | 63cd2929a6eaaa0e1654c729cd35a9a52a706962 | [
"MIT"
] | 119 | 2016-06-22T07:36:04.000Z | 2019-03-10T19:38:12.000Z | src/io/json.hpp | dbeurle/neon | 63cd2929a6eaaa0e1654c729cd35a9a52a706962 | [
"MIT"
] | 9 | 2017-10-08T16:51:38.000Z | 2021-03-15T08:08:04.000Z |
#pragma once
/// @file
#include "nlohmann/json.hpp"
namespace neon
{
using json = nlohmann::json;
}
| 8.666667 | 28 | 0.673077 | dbeurle |
092955dfd86ac62bd508fac2ae6bf3ffa3a3403f | 16,091 | cpp | C++ | QuantumGateLib/Network/Ping.cpp | kareldonk/QuantumGate | c6563b156c628ca0d32534680aa001d4eb820b73 | [
"MIT"
] | 87 | 2018-09-01T05:29:22.000Z | 2022-03-13T17:44:00.000Z | QuantumGateLib/Network/Ping.cpp | kareldonk/QuantumGate | c6563b156c628ca0d32534680aa001d4eb820b73 | [
"MIT"
] | 6 | 2019-01-30T14:48:17.000Z | 2022-03-14T21:10:56.000Z | QuantumGateLib/Network/Ping.cpp | kareldonk/QuantumGate | c6563b156c628ca0d32534680aa001d4eb820b73 | [
"MIT"
] | 16 | 2018-11-25T23:09:47.000Z | 2022-02-01T22:14:11.000Z | // 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;
}
} | 30.76673 | 119 | 0.651544 | kareldonk |
093679c0163ca70b4454aa3d90b2c27d2225a990 | 7,384 | cpp | C++ | FuegoUniversalComponent/fuego/smartgame/SgBoardConst.cpp | GSMgeeth/gameofgo | 51563fea15fbdca797afb7cf9a29773a313e5697 | [
"Apache-2.0"
] | 13 | 2016-09-09T13:45:42.000Z | 2021-12-17T08:42:28.000Z | FuegoUniversalComponent/fuego/smartgame/SgBoardConst.cpp | GSMgeeth/gameofgo | 51563fea15fbdca797afb7cf9a29773a313e5697 | [
"Apache-2.0"
] | 1 | 2016-06-18T05:19:58.000Z | 2016-09-15T18:21:54.000Z | FuegoUniversalComponent/fuego/smartgame/SgBoardConst.cpp | cbordeman/gameofgo | 51563fea15fbdca797afb7cf9a29773a313e5697 | [
"Apache-2.0"
] | 5 | 2016-11-19T03:05:12.000Z | 2022-01-31T12:20:40.000Z | //----------------------------------------------------------------------------
/** @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);
}
//----------------------------------------------------------------------------
| 34.666667 | 78 | 0.49052 | GSMgeeth |
093814bc4494041809d6e82965519e38a8997f49 | 5,551 | cc | C++ | tensorflow/contrib/lite/kernels/transpose.cc | tsesarrizqi/tflite2 | f48c1868e5f64f5fcdd1939a54cfad28a84be2b0 | [
"Apache-2.0"
] | 24 | 2018-02-01T15:49:22.000Z | 2021-01-11T16:31:18.000Z | tensorflow/contrib/lite/kernels/transpose.cc | tsesarrizqi/tflite2 | f48c1868e5f64f5fcdd1939a54cfad28a84be2b0 | [
"Apache-2.0"
] | 2 | 2018-09-09T07:29:07.000Z | 2019-03-11T07:14:45.000Z | tensorflow/contrib/lite/kernels/transpose.cc | tsesarrizqi/tflite2 | f48c1868e5f64f5fcdd1939a54cfad28a84be2b0 | [
"Apache-2.0"
] | 4 | 2018-10-29T18:43:22.000Z | 2020-09-28T07:19:52.000Z | /* 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
| 34.478261 | 80 | 0.693749 | tsesarrizqi |
09381fe49e8391ac4e2f21d6f2f73d9cbc0bde89 | 624 | hpp | C++ | src/musicpage.hpp | ToppleKek/pemdas | 713a8c3d1d3c634abf9624bd5456c80bdae47dd8 | [
"MIT"
] | null | null | null | src/musicpage.hpp | ToppleKek/pemdas | 713a8c3d1d3c634abf9624bd5456c80bdae47dd8 | [
"MIT"
] | null | null | null | src/musicpage.hpp | ToppleKek/pemdas | 713a8c3d1d3c634abf9624bd5456c80bdae47dd8 | [
"MIT"
] | null | null | null | #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
| 18.352941 | 69 | 0.725962 | ToppleKek |
093a8113eada610132a5d1abe25441eaac183cf0 | 891 | cpp | C++ | Codeforces/1093B - Letters Rearranging.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/1093B - Letters Rearranging.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/1093B - Letters Rearranging.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #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;
} | 21.731707 | 58 | 0.367003 | naimulcsx |
093c540701ca29415d0edf36b480f5f1b6e5952f | 1,764 | cpp | C++ | src/system.cpp | SusannaMaria/CppND-System-Monitor-Project-Updated | a07c51465107c38c51fb7ee12122b87068d9c7e0 | [
"MIT"
] | null | null | null | src/system.cpp | SusannaMaria/CppND-System-Monitor-Project-Updated | a07c51465107c38c51fb7ee12122b87068d9c7e0 | [
"MIT"
] | null | null | null | src/system.cpp | SusannaMaria/CppND-System-Monitor-Project-Updated | a07c51465107c38c51fb7ee12122b87068d9c7e0 | [
"MIT"
] | null | null | null | /**
* @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(); }
| 19.384615 | 80 | 0.693311 | SusannaMaria |
093e9ad8fcb60d97b9eca2301ed0150467597ca7 | 6,579 | hpp | C++ | lib/stub/s2sFunction.hpp | youelebr/assist | 9ccf862bf3350009fe9e42fbe45eecc7858a49dc | [
"BSD-2-Clause"
] | 1 | 2019-05-23T08:57:09.000Z | 2019-05-23T08:57:09.000Z | lib/stub/s2sFunction.hpp | youelebr/assist | 9ccf862bf3350009fe9e42fbe45eecc7858a49dc | [
"BSD-2-Clause"
] | null | null | null | lib/stub/s2sFunction.hpp | youelebr/assist | 9ccf862bf3350009fe9e42fbe45eecc7858a49dc | [
"BSD-2-Clause"
] | null | null | null | #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 | 32.25 | 164 | 0.680955 | youelebr |
0942279b2369324817dfc157913b91abbe964e33 | 288 | cxx | C++ | cacreader/swig-4.0.2/Examples/php/sync/example.cxx | kyletanyag/LL-Smartcard | 02abea9de5a13f8bae4d7832ab34cb7f0d9514c9 | [
"BSD-3-Clause"
] | 1,031 | 2015-01-02T14:08:47.000Z | 2022-03-29T02:25:27.000Z | cacreader/swig-4.0.2/Examples/php/sync/example.cxx | kyletanyag/LL-Smartcard | 02abea9de5a13f8bae4d7832ab34cb7f0d9514c9 | [
"BSD-3-Clause"
] | 240 | 2015-01-11T04:27:19.000Z | 2022-03-30T00:35:57.000Z | cacreader/swig-4.0.2/Examples/php/sync/example.cxx | kyletanyag/LL-Smartcard | 02abea9de5a13f8bae4d7832ab34cb7f0d9514c9 | [
"BSD-3-Clause"
] | 224 | 2015-01-05T06:13:54.000Z | 2022-02-25T14:39:51.000Z | #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);
}
| 20.571429 | 44 | 0.611111 | kyletanyag |
094299a1658096d8d4eeadf6e0d6f625f7853124 | 392 | cpp | C++ | ColorTribe/ColorLib_cpp/src/exception/CannotFindLutException.cpp | mikrosimage/OpenDisplayCalib | a8cc37aa72d378faedc4a44171bcb29a20394432 | [
"BSD-3-Clause"
] | 16 | 2015-02-25T22:35:54.000Z | 2021-12-14T19:59:30.000Z | ColorTribe/ColorLib_cpp/src/exception/CannotFindLutException.cpp | mikrosimage/OpenDisplayCalib | a8cc37aa72d378faedc4a44171bcb29a20394432 | [
"BSD-3-Clause"
] | 2 | 2015-04-02T13:43:01.000Z | 2015-06-01T13:42:00.000Z | ColorTribe/ColorLib_cpp/src/exception/CannotFindLutException.cpp | mikrosimage/OpenDisplayCalib | a8cc37aa72d378faedc4a44171bcb29a20394432 | [
"BSD-3-Clause"
] | 5 | 2016-03-02T16:08:49.000Z | 2019-11-29T11:16:54.000Z | #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;
}
| 18.666667 | 66 | 0.727041 | mikrosimage |
094341790a57445e146f7391e0e5b89a1af55780 | 498 | cpp | C++ | src/Render/GHParticleTransition.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | src/Render/GHParticleTransition.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | src/Render/GHParticleTransition.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | // 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);
}
| 21.652174 | 70 | 0.789157 | GoldenHammerSoftware |
0945337581c6729e64868ef5d73dd8b33d843ad3 | 10,869 | cpp | C++ | flume/planner/pass_manager.cpp | advancedxy/bigflow_python | 8a244b483404fde7afc42eee98bc964da8ae03e2 | [
"Apache-2.0"
] | 1 | 2021-02-18T20:13:34.000Z | 2021-02-18T20:13:34.000Z | flume/planner/pass_manager.cpp | advancedxy/bigflow_python | 8a244b483404fde7afc42eee98bc964da8ae03e2 | [
"Apache-2.0"
] | null | null | null | flume/planner/pass_manager.cpp | advancedxy/bigflow_python | 8a244b483404fde7afc42eee98bc964da8ae03e2 | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
*
* 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
| 31.780702 | 100 | 0.624528 | advancedxy |
0945bb1a48c0fdb819800dd3801d9e3b8a1453c8 | 1,159 | cc | C++ | complejo/src/complejo.cc | ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97 | d1dbcfb1ea8e478b869c10ae718cada45155a8ae | [
"MIT"
] | null | null | null | complejo/src/complejo.cc | ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97 | d1dbcfb1ea8e478b869c10ae718cada45155a8ae | [
"MIT"
] | null | null | null | complejo/src/complejo.cc | ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97 | d1dbcfb1ea8e478b869c10ae718cada45155a8ae | [
"MIT"
] | null | null | null | #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;
}
}
| 42.925926 | 122 | 0.679034 | ULL-ESIT-IB-2020-2021 |
0947fee693f8df3d85dcb154135b7b84edd64435 | 28,786 | cpp | C++ | lammps-master/src/KOKKOS/fix_langevin_kokkos.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/KOKKOS/fix_langevin_kokkos.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/KOKKOS/fix_langevin_kokkos.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | /* ----------------------------------------------------------------------
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
}
| 36.810742 | 91 | 0.603175 | rajkubp020 |
094974e1b7d804aa5eddef344cbe678d854ef481 | 890 | hpp | C++ | include/tex/dds_reader.hpp | magicmoremagic/bengine-texi | e7a6f476ccb85262db8958e39674bc9570956bbe | [
"MIT"
] | null | null | null | include/tex/dds_reader.hpp | magicmoremagic/bengine-texi | e7a6f476ccb85262db8958e39674bc9570956bbe | [
"MIT"
] | null | null | null | include/tex/dds_reader.hpp | magicmoremagic/bengine-texi | e7a6f476ccb85262db8958e39674bc9570956bbe | [
"MIT"
] | 1 | 2022-02-19T08:08:21.000Z | 2022-02-19T08:08:21.000Z | #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
| 30.689655 | 108 | 0.625843 | magicmoremagic |
094b339ddf9ab1ed589f5f6a731f557c9f64f6c9 | 2,834 | cpp | C++ | projects/lab3/code/lab3.cpp | MTBorg/D7045E | f4db7e066335facffbdc70efa9a47461792354b9 | [
"MIT"
] | null | null | null | projects/lab3/code/lab3.cpp | MTBorg/D7045E | f4db7e066335facffbdc70efa9a47461792354b9 | [
"MIT"
] | null | null | null | projects/lab3/code/lab3.cpp | MTBorg/D7045E | f4db7e066335facffbdc70efa9a47461792354b9 | [
"MIT"
] | null | null | null | #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();
}
}
| 27.25 | 79 | 0.628088 | MTBorg |
094bb1a34a8c78c867686a7674324aef4ffe0caa | 13,564 | cpp | C++ | test/MainWindow.cpp | benjamin-fukdawurld/FDQUI | 95ecc0ebd1ca2ba38865974035bbe7fd1486e16f | [
"Apache-2.0"
] | null | null | null | test/MainWindow.cpp | benjamin-fukdawurld/FDQUI | 95ecc0ebd1ca2ba38865974035bbe7fd1486e16f | [
"Apache-2.0"
] | null | null | null | test/MainWindow.cpp | benjamin-fukdawurld/FDQUI | 95ecc0ebd1ca2ba38865974035bbe7fd1486e16f | [
"Apache-2.0"
] | null | null | null | #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)));
}
| 30.897494 | 108 | 0.610071 | benjamin-fukdawurld |
094e6be65204707d09284e06d7369d77de998293 | 2,198 | hpp | C++ | src/application/tools/deepsort.hpp | hito0512/tensorRT_Pro | d577fbab615a3d84cb50824d2418655659fd61af | [
"MIT"
] | 537 | 2021-10-03T10:51:49.000Z | 2022-03-31T10:07:05.000Z | src/application/tools/deepsort.hpp | hito0512/tensorRT_Pro | d577fbab615a3d84cb50824d2418655659fd61af | [
"MIT"
] | 52 | 2021-10-04T09:05:35.000Z | 2022-03-31T07:35:22.000Z | src/application/tools/deepsort.hpp | hito0512/tensorRT_Pro | d577fbab615a3d84cb50824d2418655659fd61af | [
"MIT"
] | 146 | 2021-10-11T00:46:19.000Z | 2022-03-31T02:19:37.000Z |
#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 | 24.153846 | 110 | 0.66515 | hito0512 |
09502ca06e3792157dc7eea4aa784a6a649b07fd | 3,619 | cpp | C++ | exmathlib/exmathlib/exmath.cpp | IWeidl/ExMath-Library | ff809f4040c37003170f94bdb15f4edbf5bed1dd | [
"MIT"
] | 1 | 2016-04-07T18:20:42.000Z | 2016-04-07T18:20:42.000Z | exmathlib/exmathlib/exmath.cpp | Dasttann777/ExMath-Library | ff809f4040c37003170f94bdb15f4edbf5bed1dd | [
"MIT"
] | 4 | 2016-04-07T07:47:56.000Z | 2016-04-10T11:19:22.000Z | exmathlib/exmathlib/exmath.cpp | IWeidl/ExMath-Library | ff809f4040c37003170f94bdb15f4edbf5bed1dd | [
"MIT"
] | null | null | null | #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));
} | 20.919075 | 74 | 0.567284 | IWeidl |
095144bb72b0e7cbb18a532f52a9f0f5af4597a6 | 12,688 | cpp | C++ | src/cpu.cpp | aimktech/chip8 | 40f278e2638eb95abb2f7b979a4d8bfa69d2400b | [
"Apache-2.0"
] | 3 | 2021-01-20T21:26:30.000Z | 2021-12-17T10:09:54.000Z | src/cpu.cpp | aimktech/chip8 | 40f278e2638eb95abb2f7b979a4d8bfa69d2400b | [
"Apache-2.0"
] | null | null | null | src/cpu.cpp | aimktech/chip8 | 40f278e2638eb95abb2f7b979a4d8bfa69d2400b | [
"Apache-2.0"
] | null | null | null | /*
* 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;
}
| 31.562189 | 97 | 0.415747 | aimktech |
0953e163adba8e1dcc2205bcad313d08cf2c0b47 | 8,106 | cpp | C++ | src/command/FbxWriter.cpp | chadmv/dem-bones | bb4ea9f391c4be9abe4f85a407c2c47979bad959 | [
"BSD-3-Clause"
] | 584 | 2019-10-08T20:21:01.000Z | 2022-03-31T14:29:50.000Z | src/command/FbxWriter.cpp | chadmv/dem-bones | bb4ea9f391c4be9abe4f85a407c2c47979bad959 | [
"BSD-3-Clause"
] | 18 | 2019-12-13T22:19:08.000Z | 2021-09-18T07:09:50.000Z | src/command/FbxWriter.cpp | chadmv/dem-bones | bb4ea9f391c4be9abe4f85a407c2c47979bad959 | [
"BSD-3-Clause"
] | 112 | 2019-10-08T20:41:20.000Z | 2022-03-29T04:12:18.000Z | ///////////////////////////////////////////////////////////////////////////////
// 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;
}
| 38.417062 | 167 | 0.690846 | chadmv |
09544c622b32cf76b285717159c09e19842fc3d6 | 24,345 | cc | C++ | tests/unit/kernel/GaussianARDKernel_unittest.cc | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 1 | 2020-09-18T04:30:46.000Z | 2020-09-18T04:30:46.000Z | tests/unit/kernel/GaussianARDKernel_unittest.cc | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | null | null | null | tests/unit/kernel/GaussianARDKernel_unittest.cc | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | null | null | null | /*
* 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
}
| 33.258197 | 89 | 0.766852 | ShankarNara |
0956e2a4bab6585323216d41ada3347d3581f846 | 3,895 | cc | C++ | omaha/base/thread_pool.cc | Gunanekza/omaha | e73cb9edffaba24bb3b7515f5b48376f922b697e | [
"Apache-2.0"
] | 34 | 2019-11-01T04:26:40.000Z | 2022-03-29T03:00:40.000Z | omaha/base/thread_pool.cc | Wicked2303/omaha | 1b18ab3989b8cf503d5e46a351c44c9d2754caed | [
"Apache-2.0"
] | 1 | 2020-11-19T18:11:20.000Z | 2020-11-19T18:11:20.000Z | omaha/base/thread_pool.cc | Wicked2303/omaha | 1b18ab3989b8cf503d5e46a351c44c9d2754caed | [
"Apache-2.0"
] | 8 | 2019-11-01T04:27:53.000Z | 2022-03-16T22:17:12.000Z | // 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
| 28.639706 | 76 | 0.671374 | Gunanekza |
095740e3a488d46f7e5ec3601cd10175f17185cc | 843 | cpp | C++ | huffman_decode/main.cpp | 8alery/algorithms | 67cf12724f61cdae7eff1788062c1b7c26f98ca4 | [
"Apache-2.0"
] | null | null | null | huffman_decode/main.cpp | 8alery/algorithms | 67cf12724f61cdae7eff1788062c1b7c26f98ca4 | [
"Apache-2.0"
] | null | null | null | huffman_decode/main.cpp | 8alery/algorithms | 67cf12724f61cdae7eff1788062c1b7c26f98ca4 | [
"Apache-2.0"
] | null | null | null | #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;
} | 26.34375 | 53 | 0.572954 | 8alery |
09584380c68e4133ad79fe64e938763475562bcb | 456 | cpp | C++ | rrQt/Widgets/main.cpp | afoolsbag/rrCnCxx | 1e673bd4edac43d8406a0c726138cba194d17f48 | [
"Unlicense"
] | 2 | 2019-03-20T01:14:10.000Z | 2021-12-08T15:39:32.000Z | rrQt/Widgets/main.cpp | afoolsbag/rrCnCxx | 1e673bd4edac43d8406a0c726138cba194d17f48 | [
"Unlicense"
] | null | null | null | rrQt/Widgets/main.cpp | afoolsbag/rrCnCxx | 1e673bd4edac43d8406a0c726138cba194d17f48 | [
"Unlicense"
] | null | null | null | //===-- 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();
}
| 19.826087 | 80 | 0.425439 | afoolsbag |
095bf50d18ec9f3d72f735d509f483569ef4336a | 4,456 | hpp | C++ | include/latte_core_hook.hpp | iwatakeshi/latte | ec0c31092af3d9b42e757a6bb375d817ff522376 | [
"MIT"
] | 1 | 2019-03-05T02:24:32.000Z | 2019-03-05T02:24:32.000Z | include/latte_core_hook.hpp | iwatakeshi/latte | ec0c31092af3d9b42e757a6bb375d817ff522376 | [
"MIT"
] | null | null | null | include/latte_core_hook.hpp | iwatakeshi/latte | ec0c31092af3d9b42e757a6bb375d817ff522376 | [
"MIT"
] | null | null | null | #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 | 26.52381 | 93 | 0.665171 | iwatakeshi |
095ff73f993b2b888af47be86f5d2ecca7a1dab1 | 1,097 | cpp | C++ | Dev/SourcesEditor/Gugu/Editor/Modal/OpenProjectDialog.cpp | Legulysse/guguEngine | 889ba87f219d476169fab1072f3af1428df62d49 | [
"Zlib"
] | null | null | null | Dev/SourcesEditor/Gugu/Editor/Modal/OpenProjectDialog.cpp | Legulysse/guguEngine | 889ba87f219d476169fab1072f3af1428df62d49 | [
"Zlib"
] | null | null | null | Dev/SourcesEditor/Gugu/Editor/Modal/OpenProjectDialog.cpp | Legulysse/guguEngine | 889ba87f219d476169fab1072f3af1428df62d49 | [
"Zlib"
] | null | null | null | ////////////////////////////////////////////////////////////////
// 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
| 21.096154 | 101 | 0.523245 | Legulysse |
0960047ad988edff18eb60efaacccc5ed8242493 | 1,278 | cpp | C++ | SPOJ/FOXLINGS.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | SPOJ/FOXLINGS.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | SPOJ/FOXLINGS.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | #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;
} | 18 | 81 | 0.535994 | ggml1 |
8233058ea508b6fd482d8bf8d92c3430bde28c21 | 59,480 | cpp | C++ | modules/space/rendering/renderablestars.cpp | agarwalutkarsh554/OpenSpace | 5b3f2f10d33121ed40bb9833d79197897f13a857 | [
"MIT"
] | null | null | null | modules/space/rendering/renderablestars.cpp | agarwalutkarsh554/OpenSpace | 5b3f2f10d33121ed40bb9833d79197897f13a857 | [
"MIT"
] | null | null | null | modules/space/rendering/renderablestars.cpp | agarwalutkarsh554/OpenSpace | 5b3f2f10d33121ed40bb9833d79197897f13a857 | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* 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
| 34.865182 | 90 | 0.598016 | agarwalutkarsh554 |
82333857610bd2e88ed0e5fe28cfb310cafb7f85 | 2,245 | cpp | C++ | unittests/tPerf.cpp | hungptit/graph | 8f39e8af1ea3bd3ad36190559553da5c55648aae | [
"MIT"
] | null | null | null | unittests/tPerf.cpp | hungptit/graph | 8f39e8af1ea3bd3ad36190559553da5c55648aae | [
"MIT"
] | null | null | null | unittests/tPerf.cpp | hungptit/graph | 8f39e8af1ea3bd3ad36190559553da5c55648aae | [
"MIT"
] | null | null | null | #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>());
}
| 32.536232 | 95 | 0.716704 | hungptit |
823454aee78a322877f0fb27b8c1b900beb18445 | 527 | cpp | C++ | src/OrbitAccessibility/AccessibleInterface.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 1,847 | 2020-03-24T19:01:42.000Z | 2022-03-31T13:18:57.000Z | src/OrbitAccessibility/AccessibleInterface.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 1,100 | 2020-03-24T19:41:13.000Z | 2022-03-31T14:27:09.000Z | src/OrbitAccessibility/AccessibleInterface.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 228 | 2020-03-25T05:32:08.000Z | 2022-03-31T11:27:39.000Z | // 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);
}
| 32.9375 | 73 | 0.798861 | tufeigunchu |
82368801a5da131d0f1f214fc9506ea345c34e48 | 1,224 | cpp | C++ | lib/Util/Printing.cpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 7 | 2018-06-25T12:06:13.000Z | 2022-01-18T09:20:13.000Z | lib/Util/Printing.cpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 20 | 2016-12-01T23:46:12.000Z | 2019-08-11T02:41:04.000Z | lib/Util/Printing.cpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 1 | 2020-10-19T03:20:05.000Z | 2020-10-19T03:20:05.000Z | //===- 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
| 23.09434 | 80 | 0.41585 | seec-team |
823827870e220b665ee8fe8fd891e70eab0bfb00 | 20,441 | cc | C++ | hoomd/md/test/test_fenebond_force.cc | kmoskovtsev/HOOMD-Blue-fork | 99560563a5ba9e082b513764bae51a84f48fdc70 | [
"BSD-3-Clause"
] | null | null | null | hoomd/md/test/test_fenebond_force.cc | kmoskovtsev/HOOMD-Blue-fork | 99560563a5ba9e082b513764bae51a84f48fdc70 | [
"BSD-3-Clause"
] | null | null | null | hoomd/md/test/test_fenebond_force.cc | kmoskovtsev/HOOMD-Blue-fork | 99560563a5ba9e082b513764bae51a84f48fdc70 | [
"BSD-3-Clause"
] | null | null | null | // 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
| 47.871194 | 158 | 0.659116 | kmoskovtsev |
8239639e48f02e5fc500243b82d78fdfaefe5453 | 23,567 | cpp | C++ | Source/src/ezcard/util/list_multi_map.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 5 | 2019-10-30T06:10:10.000Z | 2020-04-25T16:52:06.000Z | Source/src/ezcard/util/list_multi_map.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | null | null | null | Source/src/ezcard/util/list_multi_map.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 2 | 2019-11-27T23:47:54.000Z | 2020-01-13T16:36:03.000Z | //
// 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;
// }
// }
// }
//}
| 32.868898 | 138 | 0.494378 | ProtonMail |
823ac36b895eca5dbaf950d4f69cd100618e568b | 4,593 | cpp | C++ | src/irrlicht/game-scene/irr-entity/IrrEntity.cpp | Gegel85/IndieStudio | 63e58c61416b3c16885d35d75d126e3db5ed3cc8 | [
"MIT"
] | null | null | null | src/irrlicht/game-scene/irr-entity/IrrEntity.cpp | Gegel85/IndieStudio | 63e58c61416b3c16885d35d75d126e3db5ed3cc8 | [
"MIT"
] | 12 | 2019-05-22T12:22:44.000Z | 2019-06-15T17:31:04.000Z | src/irrlicht/game-scene/irr-entity/IrrEntity.cpp | Gegel85/IndieStudio | 63e58c61416b3c16885d35d75d126e3db5ed3cc8 | [
"MIT"
] | 1 | 2019-06-18T15:53:48.000Z | 2019-06-18T15:53:48.000Z | //
// 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));
}
| 31.675862 | 129 | 0.576747 | Gegel85 |
823cffedb5057a24e643e4a0a82e42bb63b1c49c | 23,104 | cpp | C++ | SevenZip/CPP/7zip/Compress/LzfseDecoder.cpp | SammyEnigma/NanaZip | dd20989c0b5cdd0175346bed252c142587a10d95 | [
"BSD-3-Clause"
] | 1,855 | 2021-09-08T02:53:41.000Z | 2022-03-31T15:31:23.000Z | SevenZip/CPP/7zip/Compress/LzfseDecoder.cpp | SammyEnigma/NanaZip | dd20989c0b5cdd0175346bed252c142587a10d95 | [
"BSD-3-Clause"
] | 106 | 2021-09-26T07:00:57.000Z | 2022-03-29T19:10:16.000Z | SevenZip/CPP/7zip/Compress/LzfseDecoder.cpp | SammyEnigma/NanaZip | dd20989c0b5cdd0175346bed252c142587a10d95 | [
"BSD-3-Clause"
] | 80 | 2021-09-23T00:54:33.000Z | 2022-03-28T07:53:16.000Z | // 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; }
}
}}
| 24.950324 | 142 | 0.58254 | SammyEnigma |
823daeb71466bb7e38cdcb396fa91e5491d4cd73 | 13,685 | cpp | C++ | src/upcore/test/random.cpp | upcaste/upcaste | 8174a2f40e7fde022806f8d1565bb4a415ecb210 | [
"MIT"
] | 1 | 2018-09-17T20:50:14.000Z | 2018-09-17T20:50:14.000Z | src/upcore/test/random.cpp | jwtowner/upcaste | 8174a2f40e7fde022806f8d1565bb4a415ecb210 | [
"MIT"
] | null | null | null | src/upcore/test/random.cpp | jwtowner/upcaste | 8174a2f40e7fde022806f8d1565bb4a415ecb210 | [
"MIT"
] | null | null | null | //
// 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);
}
}
| 35.179949 | 122 | 0.51129 | upcaste |
823ec2c4c7a57c4d5b51e558af1530eb875b1c97 | 390 | cpp | C++ | assets/docs/samples/events.cpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | 2 | 2021-02-12T13:05:02.000Z | 2021-02-22T14:25:00.000Z | assets/docs/samples/events.cpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | null | null | null | assets/docs/samples/events.cpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | null | null | null | #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;
} | 27.857143 | 88 | 0.584615 | mariusvn |
824489ea9f7b731c51e7e6e4a7fa2031863d45eb | 406 | hpp | C++ | include/Regiment.hpp | a276me/MilSim | b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea | [
"MIT"
] | null | null | null | include/Regiment.hpp | a276me/MilSim | b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea | [
"MIT"
] | null | null | null | include/Regiment.hpp | a276me/MilSim | b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea | [
"MIT"
] | null | null | null | #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);
}; | 11.6 | 24 | 0.679803 | a276me |
82453b175b65a5b303fe610c2be21f920d323376 | 889 | cpp | C++ | test.cpp | ReflectMun/DataStructureQuizArchive | 6805179e17391e854d7495ef8f3db2d3acb84dfb | [
"MIT"
] | null | null | null | test.cpp | ReflectMun/DataStructureQuizArchive | 6805179e17391e854d7495ef8f3db2d3acb84dfb | [
"MIT"
] | null | null | null | test.cpp | ReflectMun/DataStructureQuizArchive | 6805179e17391e854d7495ef8f3db2d3acb84dfb | [
"MIT"
] | null | null | null | #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;
}
| 25.4 | 77 | 0.537683 | ReflectMun |
8247af56903b9186975fc4777fea860b0d95e097 | 1,075 | cpp | C++ | skia/docs/examples/Picture_MakePlaceholder.cpp | jiangkang/renderer-dog | 8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85 | [
"MIT"
] | 1 | 2019-03-25T15:37:48.000Z | 2019-03-25T15:37:48.000Z | docs/examples/Picture_MakePlaceholder.cpp | bryphe/esy-skia | 9810a02f28270535de10b584bffc536182224c83 | [
"BSD-3-Clause"
] | 1 | 2020-09-13T11:08:17.000Z | 2020-09-13T11:08:17.000Z | skia/docs/examples/Picture_MakePlaceholder.cpp | jiangkang/renderer-dog | 8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85 | [
"MIT"
] | null | null | null | // 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
| 37.068966 | 100 | 0.691163 | jiangkang |
8247bd45df73446b58eb106cfaa242b4c80e48d0 | 20,802 | cxx | C++ | core/sqf/monitor/test/procCreate.cxx | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 1 | 2021-02-05T08:44:55.000Z | 2021-02-05T08:44:55.000Z | core/sqf/monitor/test/procCreate.cxx | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | null | null | null | core/sqf/monitor/test/procCreate.cxx | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 1 | 2021-09-01T08:45:30.000Z | 2021-09-01T08:45:30.000Z | ///////////////////////////////////////////////////////////////////////////////
//
// @@@ 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);
}
| 37.548736 | 105 | 0.448563 | CoderSong2015 |
8247c8c14ae3c4f5ee0836814f2b1425f5cbc19f | 844 | hpp | C++ | messungen/SNR_opencl_multi/SNR_opencl_multi/CPUModelResults.hpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | 16 | 2021-04-10T16:28:00.000Z | 2021-12-12T10:15:23.000Z | messungen/SNR_opencl_multi_17/SNR_opencl_multi/CPUModelResults.hpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | null | null | null | messungen/SNR_opencl_multi_17/SNR_opencl_multi/CPUModelResults.hpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | 2 | 2021-04-10T16:32:36.000Z | 2021-04-11T14:13:45.000Z | //
// 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 */
| 24.823529 | 103 | 0.731043 | tihmstar |
82488d96edb3a732a7fe4c1390ad312e45b8882a | 8,884 | cpp | C++ | src/libraries/dynamicMesh/topoChangerFvMesh/mixerFvMesh/mixerFvMesh.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/dynamicMesh/topoChangerFvMesh/mixerFvMesh/mixerFvMesh.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/dynamicMesh/topoChangerFvMesh/mixerFvMesh/mixerFvMesh.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
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;
}
// ************************************************************************* //
| 23.62766 | 80 | 0.537371 | MrAwesomeRocks |
8248f2257ae4f9df7c7d04ff6892071437d5d512 | 7,612 | cpp | C++ | lammps-master/src/USER-INTEL/npair_halffull_newton_intel.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/USER-INTEL/npair_halffull_newton_intel.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/USER-INTEL/npair_halffull_newton_intel.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | /* ----------------------------------------------------------------------
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);
}
}
}
| 32.529915 | 78 | 0.572254 | rajkubp020 |
8249ca08605691ed6332c02640b45b30eb87b79c | 1,584 | hpp | C++ | VSDataReduction/VSSimCoordTransform.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSDataReduction/VSSimCoordTransform.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSDataReduction/VSSimCoordTransform.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-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
| 25.548387 | 79 | 0.640152 | sfegan |
824e717c4a58d13ad2d91ed111fac33a3307c6de | 5,526 | hpp | C++ | source/NanairoCore/Material/SurfaceModel/Surface/microfacet-inl.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 30 | 2015-09-06T03:14:29.000Z | 2021-06-18T11:00:19.000Z | source/NanairoCore/Material/SurfaceModel/Surface/microfacet-inl.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 31 | 2016-01-14T14:50:34.000Z | 2018-06-25T13:21:48.000Z | source/NanairoCore/Material/SurfaceModel/Surface/microfacet-inl.hpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 6 | 2017-04-09T13:07:47.000Z | 2021-05-29T21:17:34.000Z | /*!
\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
| 30.196721 | 83 | 0.647666 | byzin |
824f2874943ec9626a9f9dfba120884bc862effc | 6,104 | cpp | C++ | external/OpenGP/apps/glfwviewer_raw/main.cpp | MessCoder/CSC-305 | 71d64472dcac1eac6402a2650ec37e15b5643312 | [
"MIT"
] | null | null | null | external/OpenGP/apps/glfwviewer_raw/main.cpp | MessCoder/CSC-305 | 71d64472dcac1eac6402a2650ec37e15b5643312 | [
"MIT"
] | null | null | null | external/OpenGP/apps/glfwviewer_raw/main.cpp | MessCoder/CSC-305 | 71d64472dcac1eac6402a2650ec37e15b5643312 | [
"MIT"
] | null | null | null | #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;
}
| 36.118343 | 118 | 0.615826 | MessCoder |
825111ac05fe2fe1f38ced0580c139aed27cd0c2 | 2,224 | cpp | C++ | aws-cpp-sdk-chime-sdk-identity/source/model/EndpointStatusReason.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-chime-sdk-identity/source/model/EndpointStatusReason.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-chime-sdk-identity/source/model/EndpointStatusReason.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* 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
| 31.323944 | 102 | 0.657374 | perfectrecall |
825151d898939313b549de0a5529a6c7a79cb96c | 4,016 | cc | C++ | mf/matrix/io/ioProjected_impl.cc | Hui-Li/DSGDPP | 0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e | [
"Apache-2.0"
] | 14 | 2017-01-10T11:39:39.000Z | 2021-11-02T23:03:55.000Z | mf/matrix/io/ioProjected_impl.cc | Hui-Li/DSGDPP | 0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e | [
"Apache-2.0"
] | null | null | null | mf/matrix/io/ioProjected_impl.cc | Hui-Li/DSGDPP | 0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e | [
"Apache-2.0"
] | 6 | 2017-10-27T18:40:47.000Z | 2021-10-05T15:10:56.000Z | // 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());
}
}
| 33.466667 | 117 | 0.731823 | Hui-Li |
8253a14e6837b10f7fa743f21a28f328d071080e | 11,233 | cpp | C++ | crashfix_service/libdumper/PdbCompilandStream.cpp | jsonzilla/crashfix | 278a0dfb94f815709067bef61e64f1b290f17fa0 | [
"BSD-3-Clause"
] | 3 | 2019-01-07T20:55:30.000Z | 2019-04-10T10:04:16.000Z | crashfix_service/libdumper/PdbCompilandStream.cpp | 0um/crashfix | f283498b92efbaf150f6f09251d4bd69d8335a6b | [
"BSD-3-Clause"
] | 9 | 2020-04-04T13:33:00.000Z | 2020-04-04T13:33:18.000Z | crashfix_service/libdumper/PdbCompilandStream.cpp | jsonzilla/crashfix | 278a0dfb94f815709067bef61e64f1b290f17fa0 | [
"BSD-3-Clause"
] | 1 | 2021-04-25T14:26:27.000Z | 2021-04-25T14:26:27.000Z | //! \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;
}
| 32.002849 | 166 | 0.589958 | jsonzilla |
825414d4a8546f6b41026f70e7245be1b1a06c11 | 10,277 | cpp | C++ | ContextUI/src/cu_cellnaming.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | ContextUI/src/cu_cellnaming.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | ContextUI/src/cu_cellnaming.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | // 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);
}
| 31.332317 | 108 | 0.730661 | crutchwalkfactory |
825420cd67a1680f842f1d598407a22f6bdcc590 | 2,055 | cpp | C++ | compiler/mir/src/Shape.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 1 | 2020-05-22T13:53:40.000Z | 2020-05-22T13:53:40.000Z | compiler/mir/src/Shape.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 1 | 2020-09-23T23:12:23.000Z | 2020-09-23T23:20:34.000Z | compiler/mir/src/Shape.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 1 | 2021-07-22T11:02:43.000Z | 2021-07-22T11:02:43.000Z | /*
* 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
| 23.352273 | 98 | 0.63455 | periannath |
8254fd24e943bbb2aa0ae99803b2fe1807b2215c | 71 | cpp | C++ | src/playground.cpp | salonmor/blog | 1c51d1c6143d3688c30dda907df55dd6ba955a55 | [
"0BSD"
] | null | null | null | src/playground.cpp | salonmor/blog | 1c51d1c6143d3688c30dda907df55dd6ba955a55 | [
"0BSD"
] | null | null | null | src/playground.cpp | salonmor/blog | 1c51d1c6143d3688c30dda907df55dd6ba955a55 | [
"0BSD"
] | null | null | null | #include "I.hpp"
#include "T.hpp"
using namespace std;
int main()
{
}
| 8.875 | 20 | 0.647887 | salonmor |
82555430a96d157fb09eec653fcfc5723aa3e57a | 17 | cpp | C++ | PokittoLibraryPrototype/FileSystems/File.cpp | Pharap/PokittoLibraryPrototype | f8efcbc693090d7cf3fe364272f6c9c2d3e30c1f | [
"BSD-3-Clause"
] | 23 | 2018-12-30T21:04:47.000Z | 2022-01-30T05:12:26.000Z | PokittoLibraryPrototype/FileSystems/File.cpp | Pharap/PokittoLibraryPrototype | f8efcbc693090d7cf3fe364272f6c9c2d3e30c1f | [
"BSD-3-Clause"
] | 4 | 2019-01-01T21:30:56.000Z | 2022-02-24T17:44:37.000Z | PokittoLibraryPrototype/FileSystems/File.cpp | Pharap/PokittoLibraryPrototype | f8efcbc693090d7cf3fe364272f6c9c2d3e30c1f | [
"BSD-3-Clause"
] | 3 | 2019-06-12T19:25:53.000Z | 2022-01-11T23:46:34.000Z | #include "File.h" | 17 | 17 | 0.705882 | Pharap |
825610ec33ec066781f205bab30bf7cd74934b13 | 656 | cpp | C++ | FroggerObjects/Utilities/ResetableObject.cpp | RicardoEPRodrigues/FroggerOpenGL | dc02437dfe14203e9bdb39f160e4877b44363c42 | [
"MIT"
] | null | null | null | FroggerObjects/Utilities/ResetableObject.cpp | RicardoEPRodrigues/FroggerOpenGL | dc02437dfe14203e9bdb39f160e4877b44363c42 | [
"MIT"
] | 1 | 2016-12-31T15:43:29.000Z | 2016-12-31T15:43:29.000Z | FroggerObjects/Utilities/ResetableObject.cpp | RicardoEPRodrigues/FroggerOpenGL | dc02437dfe14203e9bdb39f160e4877b44363c42 | [
"MIT"
] | null | null | null | /*
* 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--;
}
| 17.72973 | 44 | 0.655488 | RicardoEPRodrigues |
825774a51d730677917f6c9321ad7fc6dc533b2d | 2,767 | cpp | C++ | source/tests.cpp | saJonMR/programmiersprachen-raytracer-1 | 6f2345a9f1b255e0c02b2b11a4d33247f78d8fe7 | [
"MIT"
] | null | null | null | source/tests.cpp | saJonMR/programmiersprachen-raytracer-1 | 6f2345a9f1b255e0c02b2b11a4d33247f78d8fe7 | [
"MIT"
] | null | null | null | source/tests.cpp | saJonMR/programmiersprachen-raytracer-1 | 6f2345a9f1b255e0c02b2b11a4d33247f78d8fe7 | [
"MIT"
] | null | null | null | #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);
}
| 28.525773 | 97 | 0.642212 | saJonMR |
825f3c3890893b99d7be27d32a2fd7c80670dbb8 | 1,655 | cpp | C++ | tests/src/count.cpp | pinam45/dynamic_bitset | 6d19b2da9b69b8c77d7b86b453c757cd5fa8711f | [
"MIT"
] | 98 | 2019-03-31T20:18:58.000Z | 2022-03-15T12:58:19.000Z | tests/src/count.cpp | pinam45/dynamic_bitset | 6d19b2da9b69b8c77d7b86b453c757cd5fa8711f | [
"MIT"
] | 7 | 2019-07-09T15:16:53.000Z | 2021-05-30T17:38:42.000Z | tests/src/count.cpp | pinam45/dynamic_bitset | 6d19b2da9b69b8c77d7b86b453c757cd5fa8711f | [
"MIT"
] | 12 | 2019-05-20T13:57:15.000Z | 2022-02-06T09:43:13.000Z | //
// 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);
}
}
}
| 22.066667 | 80 | 0.685196 | pinam45 |
82612d49cf8ae9f11abadced0b556bc995db20ba | 942 | cpp | C++ | datasets/github_cpp_10/8/16.cpp | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T19:27:45.000Z | 2019-05-03T19:27:45.000Z | datasets/github_cpp_10/8/16.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | datasets/github_cpp_10/8/16.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null |
#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;
} | 15.966102 | 75 | 0.45966 | yijunyu |
8266ef0c94bb05f329179d851d2a834cd51e899b | 4,577 | cpp | C++ | src/state_machine.cpp | mairas/sailor-hat-firmware | 48390bbc3226b046b294d804ca5c266797b5cb2e | [
"BSD-3-Clause"
] | null | null | null | src/state_machine.cpp | mairas/sailor-hat-firmware | 48390bbc3226b046b294d804ca5c266797b5cb2e | [
"BSD-3-Clause"
] | null | null | null | src/state_machine.cpp | mairas/sailor-hat-firmware | 48390bbc3226b046b294d804ca5c266797b5cb2e | [
"BSD-3-Clause"
] | 1 | 2021-04-21T08:38:27.000Z | 2021-04-21T08:38:27.000Z | #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?
}
}
| 22.546798 | 75 | 0.687787 | mairas |
826db133c6e83f060c8f139633347a860f1f3fee | 554 | cpp | C++ | Opium/src/Renderer/UniformBuffer.cpp | yatiyr/Opium | ed6e7a08ee23bc353bcc6b943fa3e1a13b2f2d41 | [
"MIT"
] | null | null | null | Opium/src/Renderer/UniformBuffer.cpp | yatiyr/Opium | ed6e7a08ee23bc353bcc6b943fa3e1a13b2f2d41 | [
"MIT"
] | null | null | null | Opium/src/Renderer/UniformBuffer.cpp | yatiyr/Opium | ed6e7a08ee23bc353bcc6b943fa3e1a13b2f2d41 | [
"MIT"
] | null | null | null | #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;
}
} | 27.7 | 121 | 0.752708 | yatiyr |
8270e873c80be56abaedfea4658898ef1fb46030 | 16,783 | cpp | C++ | test/unit/math/mix/prob/ordered_logistic_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 1 | 2020-06-14T14:33:37.000Z | 2020-06-14T14:33:37.000Z | test/unit/math/mix/prob/ordered_logistic_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 2 | 2019-07-23T12:45:30.000Z | 2020-05-01T20:43:03.000Z | test/unit/math/mix/prob/ordered_logistic_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 1 | 2020-05-10T12:55:07.000Z | 2020-05-10T12:55:07.000Z | #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);
}
| 30.185252 | 73 | 0.645415 | LaudateCorpus1 |
82710ab65cb15b0991a59e7971e3967c9f4a80b0 | 10,923 | cpp | C++ | Source/TitaniumKit/src/Media/AudioPlayer.cpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 20 | 2015-04-02T06:55:30.000Z | 2022-03-29T04:27:30.000Z | Source/TitaniumKit/src/Media/AudioPlayer.cpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 692 | 2015-04-01T21:05:49.000Z | 2020-03-10T10:11:57.000Z | Source/TitaniumKit/src/Media/AudioPlayer.cpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 22 | 2015-04-01T20:57:51.000Z | 2022-01-18T17:33:15.000Z | /**
* 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
| 36.654362 | 112 | 0.802161 | garymathews |
82716f4273626effe6da40ce822d1deef0f771df | 853 | cpp | C++ | cf/Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1) /b.cpp | emengdeath/acmcode | cc1b0e067464e754d125856004a991d6eb92a2cd | [
"MIT"
] | null | null | null | cf/Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1) /b.cpp | emengdeath/acmcode | cc1b0e067464e754d125856004a991d6eb92a2cd | [
"MIT"
] | null | null | null | cf/Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1) /b.cpp | emengdeath/acmcode | cc1b0e067464e754d125856004a991d6eb92a2cd | [
"MIT"
] | null | null | null | #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;
}
| 17.770833 | 67 | 0.444314 | emengdeath |
82723434da1211aa81174067f18498925e905cd1 | 7,228 | hpp | C++ | SFML-1.6/Game/marchand.hpp | Krozark/Dethroned-God | 0e677bea1e5b4c96a31f1188a4e43b900d92f532 | [
"BSD-2-Clause"
] | null | null | null | SFML-1.6/Game/marchand.hpp | Krozark/Dethroned-God | 0e677bea1e5b4c96a31f1188a4e43b900d92f532 | [
"BSD-2-Clause"
] | null | null | null | SFML-1.6/Game/marchand.hpp | Krozark/Dethroned-God | 0e677bea1e5b4c96a31f1188a4e43b900d92f532 | [
"BSD-2-Clause"
] | null | null | null | #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
| 33.618605 | 77 | 0.325955 | Krozark |
8274f3d59b23eed11b55b6b7d93f543a57919b27 | 5,449 | cpp | C++ | world_item_observer/src/ItemObserver.cpp | GT-RAIL/spatial_temporal_learning | 7935b361909a159873e6589e994f0d0d5fb5fe49 | [
"BSD-3-Clause"
] | null | null | null | world_item_observer/src/ItemObserver.cpp | GT-RAIL/spatial_temporal_learning | 7935b361909a159873e6589e994f0d0d5fb5fe49 | [
"BSD-3-Clause"
] | null | null | null | world_item_observer/src/ItemObserver.cpp | GT-RAIL/spatial_temporal_learning | 7935b361909a159873e6589e994f0d0d5fb5fe49 | [
"BSD-3-Clause"
] | 1 | 2021-08-01T17:45:13.000Z | 2021-08-01T17:45:13.000Z | /*!
* \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);
}
}
| 37.57931 | 118 | 0.679207 | GT-RAIL |
8276695a0e71d627f1ec862c350340047bcd766b | 49,066 | cpp | C++ | mergeBathy/grid.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | 4 | 2017-05-04T15:50:48.000Z | 2020-07-30T03:52:07.000Z | mergeBathy/grid.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | null | null | null | mergeBathy/grid.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | 2 | 2017-01-11T09:53:26.000Z | 2020-07-30T03:52:09.000Z | /**********************************************************************
* 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 | 39.98859 | 250 | 0.541149 | Sammie-Jo |
8278100f1e02979ae43e62c28dac6e1b4078e5ba | 1,224 | cpp | C++ | src/object/mgr.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/object/mgr.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/object/mgr.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | #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>();
}
}
| 24.48 | 138 | 0.573529 | degarashi |
8278d3ab731c5a2aecfa7e879d12431b0e0b3e59 | 4,874 | hpp | C++ | modules/core/include/glpp/core/render/renderer.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | 16 | 2019-12-10T19:44:17.000Z | 2022-01-04T03:16:19.000Z | modules/core/include/glpp/core/render/renderer.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | null | null | null | modules/core/include/glpp/core/render/renderer.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | 3 | 2021-06-04T21:56:55.000Z | 2022-03-03T06:47:56.000Z | #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());
}
}
| 33.156463 | 147 | 0.787033 | lenamueller |
827a12a4901f3eb22852e3a264c7980242ee0197 | 966 | cpp | C++ | N64 Sound Tool/N64SoundListToolUpdated/N64SoundLibrary/DecompressClayfighter.cpp | Raspberryfloof/N64-Tools | 96738d434ce3922dec0168cdd42f8e7ca131d0c5 | [
"Unlicense"
] | 1 | 2022-02-21T03:01:00.000Z | 2022-02-21T03:01:00.000Z | N64 Sound Tool/N64SoundListToolUpdated/N64SoundLibrary/DecompressClayfighter.cpp | Raspberryfloof/N64-Tools | 96738d434ce3922dec0168cdd42f8e7ca131d0c5 | [
"Unlicense"
] | null | null | null | N64 Sound Tool/N64SoundListToolUpdated/N64SoundLibrary/DecompressClayfighter.cpp | Raspberryfloof/N64-Tools | 96738d434ce3922dec0168cdd42f8e7ca131d0c5 | [
"Unlicense"
] | null | null | null | #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;
} | 20.125 | 65 | 0.568323 | Raspberryfloof |
827b174cd67919159e166af7f99b41b40f3f4abd | 1,579 | hpp | C++ | source/Estrutura_de_dados/Lista_adjacencia.hpp | AmandaACLucio/GraphLibrary | 518b610045e6f359588264644d0bd9f70e41b14d | [
"MIT"
] | null | null | null | source/Estrutura_de_dados/Lista_adjacencia.hpp | AmandaACLucio/GraphLibrary | 518b610045e6f359588264644d0bd9f70e41b14d | [
"MIT"
] | null | null | null | source/Estrutura_de_dados/Lista_adjacencia.hpp | AmandaACLucio/GraphLibrary | 518b610045e6f359588264644d0bd9f70e41b14d | [
"MIT"
] | null | null | null | #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
| 22.557143 | 89 | 0.61368 | AmandaACLucio |
827b8cd12246fcf20532ef276d85d0e6527aabb7 | 1,057 | hpp | C++ | peopleextractor_interface_sma/src/SceneframeQueue.hpp | fbredius/IMOVE | 912b4d0696e88acfc0ce7bc556eecf8fc423c4d3 | [
"MIT"
] | 3 | 2018-04-24T10:04:37.000Z | 2018-05-11T08:27:03.000Z | peopleextractor_interface_sma/src/SceneframeQueue.hpp | fbredius/IMOVE | 912b4d0696e88acfc0ce7bc556eecf8fc423c4d3 | [
"MIT"
] | null | null | null | peopleextractor_interface_sma/src/SceneframeQueue.hpp | fbredius/IMOVE | 912b4d0696e88acfc0ce7bc556eecf8fc423c4d3 | [
"MIT"
] | 3 | 2018-05-16T08:44:19.000Z | 2020-12-04T16:04:32.000Z | #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
| 44.041667 | 160 | 0.835383 | fbredius |
827d67e18b8f7f974cb10ec126f2ce505eee08c1 | 2,377 | cpp | C++ | RexLogicModule/EntityComponent/HoveringButtonsController.cpp | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | 1 | 2018-04-02T15:38:10.000Z | 2018-04-02T15:38:10.000Z | RexLogicModule/EntityComponent/HoveringButtonsController.cpp | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | null | null | null | RexLogicModule/EntityComponent/HoveringButtonsController.cpp | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | null | null | null | #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();
}
}
| 28.987805 | 133 | 0.612958 | mattire |
827d87a61c89e0dbdd02056494907d85f5ea162d | 23,745 | cpp | C++ | plugins/community/repos/FrozenWasteland/src/QuadEuclideanRhythm.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/FrozenWasteland/src/QuadEuclideanRhythm.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/FrozenWasteland/src/QuadEuclideanRhythm.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z | #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;
}
| 37.992 | 182 | 0.717962 | guillaume-plantevin |
827e173e708ac980282c7a271edb5fe592253724 | 11,296 | cpp | C++ | 2d_plane_move_animation_not_fully_complted_game/2DPlaneGame.cpp | quang-vn26/Computer-Graphics--OpenGL-GLUT | 581ee34aee63c60069f9029861fcc92d5b7ef002 | [
"MIT"
] | 19 | 2017-02-06T07:18:07.000Z | 2021-07-01T18:25:52.000Z | 2d_plane_move_animation_not_fully_complted_game/2DPlaneGame.cpp | Shifath472533/Computer-Graphics--OpenGL-GLUT | 0c44b5d94ff0182db72ae7e99e63f88e0d3aa9c6 | [
"MIT"
] | null | null | null | 2d_plane_move_animation_not_fully_complted_game/2DPlaneGame.cpp | Shifath472533/Computer-Graphics--OpenGL-GLUT | 0c44b5d94ff0182db72ae7e99e63f88e0d3aa9c6 | [
"MIT"
] | 36 | 2016-11-19T11:17:47.000Z | 2021-11-29T01:14:07.000Z | /*
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();
}
| 58.833333 | 7,532 | 0.652443 | quang-vn26 |
827f167147a810e89a1ba8ee85df3d023cd0481a | 637 | cpp | C++ | 2407/5414965_AC_0MS_168K.cpp | vandreas19/POJ_sol | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 18 | 2017-08-14T07:34:42.000Z | 2022-01-29T14:20:29.000Z | 2407/5414965_AC_0MS_168K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | null | null | null | 2407/5414965_AC_0MS_168K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 14 | 2016-12-21T23:37:22.000Z | 2021-07-24T09:38:57.000Z | #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;
} | 17.694444 | 42 | 0.546311 | vandreas19 |
827ff691aea0c1d644e56b7c68dc752920ded987 | 252 | cpp | C++ | TopCoder/Plugin/moj_4/template.cpp | vios-fish/CompetitiveProgramming | 6953f024e4769791225c57ed852cb5efc03eb94b | [
"MIT"
] | null | null | null | TopCoder/Plugin/moj_4/template.cpp | vios-fish/CompetitiveProgramming | 6953f024e4769791225c57ed852cb5efc03eb94b | [
"MIT"
] | null | null | null | TopCoder/Plugin/moj_4/template.cpp | vios-fish/CompetitiveProgramming | 6953f024e4769791225c57ed852cb5efc03eb94b | [
"MIT"
] | null | null | null | // Paste me into the FileEdit configuration dialog
#include <string>
#include <vector>
using namespace std;
class $CLASSNAME$ {
public:
$RC$ $METHODNAME$( $METHODPARMS$ ) {
}
};
$BEGINCUT$
$TESTCODE$
$DEFAULTMAIN$
$ENDCUT$
| 13.263158 | 51 | 0.634921 | vios-fish |
82828aaf2a72e1e22729ae93936a2525175825e0 | 2,265 | cpp | C++ | C++/best-time-to-buy-and-sell-stock-iv.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/best-time-to-buy-and-sell-stock-iv.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/best-time-to-buy-and-sell-stock-iv.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // 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
}
};
| 50.333333 | 133 | 0.525828 | Priyansh2 |
828b7339b36cd74b8b5b4eb120f9ec9abb663a3b | 209 | cpp | C++ | sources/main.cpp | Mitrius/Multicore | f0b0ef11124975ec534c20523ed1f01110118bd0 | [
"MIT"
] | null | null | null | sources/main.cpp | Mitrius/Multicore | f0b0ef11124975ec534c20523ed1f01110118bd0 | [
"MIT"
] | null | null | null | sources/main.cpp | Mitrius/Multicore | f0b0ef11124975ec534c20523ed1f01110118bd0 | [
"MIT"
] | null | null | null | #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;
}
| 17.416667 | 39 | 0.650718 | Mitrius |
8291a742c3635163474558213adaba98cff1107e | 1,875 | cpp | C++ | hiro/core/widget/combo-button.cpp | mp-lee/higan | c38a771f2272c3ee10fcb99f031e982989c08c60 | [
"Intel",
"ISC"
] | 38 | 2018-04-05T05:00:05.000Z | 2022-02-06T00:02:02.000Z | hiro/core/widget/combo-button.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 1 | 2018-04-29T19:45:14.000Z | 2018-04-29T19:45:14.000Z | hiro/core/widget/combo-button.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 8 | 2018-04-16T22:37:46.000Z | 2021-02-10T07:37:03.000Z | #if defined(Hiro_ComboButton)
auto mComboButton::allocate() -> pObject* {
return new pComboButton(*this);
}
auto mComboButton::destruct() -> void {
for(auto& item : state.items) item->destruct();
mWidget::destruct();
}
//
auto mComboButton::append(sComboButtonItem item) -> type& {
if(!state.items) item->state.selected = true;
state.items.append(item);
item->setParent(this, itemCount() - 1);
signal(append, item);
return *this;
}
auto mComboButton::doChange() const -> void {
if(state.onChange) return state.onChange();
}
auto mComboButton::item(unsigned position) const -> ComboButtonItem {
if(position < itemCount()) return state.items[position];
return {};
}
auto mComboButton::itemCount() const -> unsigned {
return state.items.size();
}
auto mComboButton::items() const -> vector<ComboButtonItem> {
vector<ComboButtonItem> items;
for(auto& item : state.items) items.append(item);
return items;
}
auto mComboButton::onChange(const function<void ()>& callback) -> type& {
state.onChange = callback;
return *this;
}
auto mComboButton::remove(sComboButtonItem item) -> type& {
signal(remove, item);
state.items.remove(item->offset());
for(auto n : range(item->offset(), itemCount())) {
state.items[n]->adjustOffset(-1);
}
item->setParent();
return *this;
}
auto mComboButton::reset() -> type& {
signal(reset);
for(auto& item : state.items) item->setParent();
state.items.reset();
return *this;
}
auto mComboButton::selected() const -> ComboButtonItem {
for(auto& item : state.items) {
if(item->selected()) return item;
}
return {};
}
auto mComboButton::setParent(mObject* parent, signed offset) -> type& {
for(auto& item : state.items) item->destruct();
mObject::setParent(parent, offset);
for(auto& item : state.items) item->setParent(this, item->offset());
return *this;
}
#endif
| 24.038462 | 73 | 0.6816 | mp-lee |
8294af14be5df43cb4c26411ef116d3853524cb4 | 13,057 | cpp | C++ | applications/mne_matching_pursuit/release/moc_enhancededitorwindow.cpp | ChunmingGu/mne-cpp-master | 36f21b3ab0c65a133027da83fa8e2a652acd1485 | [
"BSD-3-Clause"
] | null | null | null | applications/mne_matching_pursuit/release/moc_enhancededitorwindow.cpp | ChunmingGu/mne-cpp-master | 36f21b3ab0c65a133027da83fa8e2a652acd1485 | [
"BSD-3-Clause"
] | null | null | null | applications/mne_matching_pursuit/release/moc_enhancededitorwindow.cpp | ChunmingGu/mne-cpp-master | 36f21b3ab0c65a133027da83fa8e2a652acd1485 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'enhancededitorwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../enhancededitorwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'enhancededitorwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.10.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_Enhancededitorwindow_t {
QByteArrayData data[36];
char stringdata0[986];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Enhancededitorwindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Enhancededitorwindow_t qt_meta_stringdata_Enhancededitorwindow = {
{
QT_MOC_LITERAL(0, 0, 20), // "Enhancededitorwindow"
QT_MOC_LITERAL(1, 21, 10), // "dict_saved"
QT_MOC_LITERAL(2, 32, 0), // ""
QT_MOC_LITERAL(3, 33, 26), // "on_chb_allCombined_toggled"
QT_MOC_LITERAL(4, 60, 7), // "checked"
QT_MOC_LITERAL(5, 68, 37), // "on_cb_AtomFormula_currentInde..."
QT_MOC_LITERAL(6, 106, 4), // "arg1"
QT_MOC_LITERAL(7, 111, 28), // "on_sb_Atomcount_valueChanged"
QT_MOC_LITERAL(8, 140, 28), // "on_btt_DeleteFormula_clicked"
QT_MOC_LITERAL(9, 169, 33), // "on_sb_SampleCount_editingFini..."
QT_MOC_LITERAL(10, 203, 30), // "on_dsb_StepVauleA_valueChanged"
QT_MOC_LITERAL(11, 234, 30), // "on_dsb_StepVauleB_valueChanged"
QT_MOC_LITERAL(12, 265, 30), // "on_dsb_StepVauleC_valueChanged"
QT_MOC_LITERAL(13, 296, 30), // "on_dsb_StepVauleD_valueChanged"
QT_MOC_LITERAL(14, 327, 30), // "on_dsb_StepVauleE_valueChanged"
QT_MOC_LITERAL(15, 358, 30), // "on_dsb_StepVauleF_valueChanged"
QT_MOC_LITERAL(16, 389, 30), // "on_dsb_StepVauleG_valueChanged"
QT_MOC_LITERAL(17, 420, 30), // "on_dsb_StepVauleH_valueChanged"
QT_MOC_LITERAL(18, 451, 31), // "on_dsb_StartValueA_valueChanged"
QT_MOC_LITERAL(19, 483, 31), // "on_dsb_StartValueB_valueChanged"
QT_MOC_LITERAL(20, 515, 31), // "on_dsb_StartValueC_valueChanged"
QT_MOC_LITERAL(21, 547, 31), // "on_dsb_StartValueD_valueChanged"
QT_MOC_LITERAL(22, 579, 31), // "on_dsb_StartValueE_valueChanged"
QT_MOC_LITERAL(23, 611, 31), // "on_dsb_StartValueF_valueChanged"
QT_MOC_LITERAL(24, 643, 31), // "on_dsb_StartValueG_valueChanged"
QT_MOC_LITERAL(25, 675, 31), // "on_dsb_StartValueH_valueChanged"
QT_MOC_LITERAL(26, 707, 29), // "on_dsb_EndValueA_valueChanged"
QT_MOC_LITERAL(27, 737, 29), // "on_dsb_EndValueB_valueChanged"
QT_MOC_LITERAL(28, 767, 29), // "on_dsb_EndValueC_valueChanged"
QT_MOC_LITERAL(29, 797, 29), // "on_dsb_EndValueD_valueChanged"
QT_MOC_LITERAL(30, 827, 29), // "on_dsb_EndValueE_valueChanged"
QT_MOC_LITERAL(31, 857, 29), // "on_dsb_EndValueF_valueChanged"
QT_MOC_LITERAL(32, 887, 29), // "on_dsb_EndValueG_valueChanged"
QT_MOC_LITERAL(33, 917, 29), // "on_dsb_EndValueH_valueChanged"
QT_MOC_LITERAL(34, 947, 21), // "on_pushButton_clicked"
QT_MOC_LITERAL(35, 969, 16) // "on_formula_saved"
},
"Enhancededitorwindow\0dict_saved\0\0"
"on_chb_allCombined_toggled\0checked\0"
"on_cb_AtomFormula_currentIndexChanged\0"
"arg1\0on_sb_Atomcount_valueChanged\0"
"on_btt_DeleteFormula_clicked\0"
"on_sb_SampleCount_editingFinished\0"
"on_dsb_StepVauleA_valueChanged\0"
"on_dsb_StepVauleB_valueChanged\0"
"on_dsb_StepVauleC_valueChanged\0"
"on_dsb_StepVauleD_valueChanged\0"
"on_dsb_StepVauleE_valueChanged\0"
"on_dsb_StepVauleF_valueChanged\0"
"on_dsb_StepVauleG_valueChanged\0"
"on_dsb_StepVauleH_valueChanged\0"
"on_dsb_StartValueA_valueChanged\0"
"on_dsb_StartValueB_valueChanged\0"
"on_dsb_StartValueC_valueChanged\0"
"on_dsb_StartValueD_valueChanged\0"
"on_dsb_StartValueE_valueChanged\0"
"on_dsb_StartValueF_valueChanged\0"
"on_dsb_StartValueG_valueChanged\0"
"on_dsb_StartValueH_valueChanged\0"
"on_dsb_EndValueA_valueChanged\0"
"on_dsb_EndValueB_valueChanged\0"
"on_dsb_EndValueC_valueChanged\0"
"on_dsb_EndValueD_valueChanged\0"
"on_dsb_EndValueE_valueChanged\0"
"on_dsb_EndValueF_valueChanged\0"
"on_dsb_EndValueG_valueChanged\0"
"on_dsb_EndValueH_valueChanged\0"
"on_pushButton_clicked\0on_formula_saved"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Enhancededitorwindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
32, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 174, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 1, 175, 2, 0x08 /* Private */,
5, 1, 178, 2, 0x08 /* Private */,
7, 1, 181, 2, 0x08 /* Private */,
8, 0, 184, 2, 0x08 /* Private */,
9, 0, 185, 2, 0x08 /* Private */,
10, 1, 186, 2, 0x08 /* Private */,
11, 1, 189, 2, 0x08 /* Private */,
12, 1, 192, 2, 0x08 /* Private */,
13, 1, 195, 2, 0x08 /* Private */,
14, 1, 198, 2, 0x08 /* Private */,
15, 1, 201, 2, 0x08 /* Private */,
16, 1, 204, 2, 0x08 /* Private */,
17, 1, 207, 2, 0x08 /* Private */,
18, 1, 210, 2, 0x08 /* Private */,
19, 1, 213, 2, 0x08 /* Private */,
20, 1, 216, 2, 0x08 /* Private */,
21, 1, 219, 2, 0x08 /* Private */,
22, 1, 222, 2, 0x08 /* Private */,
23, 1, 225, 2, 0x08 /* Private */,
24, 1, 228, 2, 0x08 /* Private */,
25, 1, 231, 2, 0x08 /* Private */,
26, 1, 234, 2, 0x08 /* Private */,
27, 1, 237, 2, 0x08 /* Private */,
28, 1, 240, 2, 0x08 /* Private */,
29, 1, 243, 2, 0x08 /* Private */,
30, 1, 246, 2, 0x08 /* Private */,
31, 1, 249, 2, 0x08 /* Private */,
32, 1, 252, 2, 0x08 /* Private */,
33, 1, 255, 2, 0x08 /* Private */,
34, 0, 258, 2, 0x08 /* Private */,
35, 0, 259, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
// slots: parameters
QMetaType::Void, QMetaType::Bool, 4,
QMetaType::Void, QMetaType::QString, 6,
QMetaType::Void, QMetaType::Int, 6,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void, QMetaType::Double, 6,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void Enhancededitorwindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Enhancededitorwindow *_t = static_cast<Enhancededitorwindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->dict_saved(); break;
case 1: _t->on_chb_allCombined_toggled((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 2: _t->on_cb_AtomFormula_currentIndexChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 3: _t->on_sb_Atomcount_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: _t->on_btt_DeleteFormula_clicked(); break;
case 5: _t->on_sb_SampleCount_editingFinished(); break;
case 6: _t->on_dsb_StepVauleA_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 7: _t->on_dsb_StepVauleB_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 8: _t->on_dsb_StepVauleC_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 9: _t->on_dsb_StepVauleD_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 10: _t->on_dsb_StepVauleE_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 11: _t->on_dsb_StepVauleF_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 12: _t->on_dsb_StepVauleG_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 13: _t->on_dsb_StepVauleH_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 14: _t->on_dsb_StartValueA_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 15: _t->on_dsb_StartValueB_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 16: _t->on_dsb_StartValueC_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 17: _t->on_dsb_StartValueD_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 18: _t->on_dsb_StartValueE_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 19: _t->on_dsb_StartValueF_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 20: _t->on_dsb_StartValueG_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 21: _t->on_dsb_StartValueH_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 22: _t->on_dsb_EndValueA_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 23: _t->on_dsb_EndValueB_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 24: _t->on_dsb_EndValueC_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 25: _t->on_dsb_EndValueD_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 26: _t->on_dsb_EndValueE_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 27: _t->on_dsb_EndValueF_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 28: _t->on_dsb_EndValueG_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 29: _t->on_dsb_EndValueH_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 30: _t->on_pushButton_clicked(); break;
case 31: _t->on_formula_saved(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
typedef void (Enhancededitorwindow::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Enhancededitorwindow::dict_saved)) {
*result = 0;
return;
}
}
}
}
const QMetaObject Enhancededitorwindow::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_Enhancededitorwindow.data,
qt_meta_data_Enhancededitorwindow, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *Enhancededitorwindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Enhancededitorwindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_Enhancededitorwindow.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int Enhancededitorwindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 32)
qt_static_metacall(this, _c, _id, _a);
_id -= 32;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 32)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 32;
}
return _id;
}
// SIGNAL 0
void Enhancededitorwindow::dict_saved()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 45.179931 | 112 | 0.650303 | ChunmingGu |
8295fef074b48792fcdef82a94baab6c90c24b58 | 57,365 | cc | C++ | sql/sql_db.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | sql/sql_db.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | sql/sql_db.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
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 St, Fifth Floor, Boston, MA 02110-1301 USA */
/* create and drop of databases */
#include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */
#include "sql_priv.h"
#include "unireg.h"
#include "sql_db.h"
#include "sql_cache.h" // query_cache_*
#include "lock.h" // lock_schema_name
#include "sql_table.h" // build_table_filename,
// filename_to_tablename
#include "sql_rename.h" // mysql_rename_tables
#include "sql_acl.h" // SELECT_ACL, DB_ACLS,
// acl_get, check_grant_db
#include "log_event.h" // Query_log_event
#include "sql_base.h" // lock_table_names, tdc_remove_table
#include "sql_handler.h" // mysql_ha_rm_tables
#include <mysys_err.h>
#include "sp.h"
#include "events.h"
#include <my_dir.h>
#include <m_ctype.h>
#include "log.h"
#include "binlog.h" // mysql_bin_log
#include "log_event.h"
#ifdef __WIN__
#include <direct.h>
#endif
#include "debug_sync.h"
#define MAX_DROP_TABLE_Q_LEN 1024
const char *del_exts[]= {".frm", ".BAK", ".TMD", ".opt", ".OLD", NullS};
static TYPELIB deletable_extentions=
{array_elements(del_exts)-1,"del_exts", del_exts, NULL};
static bool find_db_tables_and_rm_known_files(THD *thd, MY_DIR *dirp,
const char *db,
const char *path,
TABLE_LIST **tables,
bool *found_other_files);
long mysql_rm_arc_files(THD *thd, MY_DIR *dirp, const char *org_path);
static my_bool rm_dir_w_symlink(const char *org_path, my_bool send_error);
static void mysql_change_db_impl(THD *thd,
LEX_STRING *new_db_name,
ulong new_db_access,
const CHARSET_INFO *new_db_charset);
/* Database options hash */
static HASH dboptions;
static my_bool dboptions_init= 0;
static mysql_rwlock_t LOCK_dboptions;
/* Structure for database options */
typedef struct my_dbopt_st
{
char *name; /* Database name */
uint name_length; /* Database length name */
const CHARSET_INFO *charset; /* Database default character set */
} my_dbopt_t;
/*
Function we use in the creation of our hash to get key.
*/
extern "C" uchar* dboptions_get_key(my_dbopt_t *opt, size_t *length,
my_bool not_used);
uchar* dboptions_get_key(my_dbopt_t *opt, size_t *length,
my_bool not_used __attribute__((unused)))
{
*length= opt->name_length;
return (uchar*) opt->name;
}
/*
Helper function to write a query to binlog used by mysql_rm_db()
*/
static inline int write_to_binlog(THD *thd, char *query, uint q_len,
char *db, uint db_len)
{
Query_log_event qinfo(thd, query, q_len, FALSE, TRUE, FALSE, 0);
qinfo.db= db;
qinfo.db_len= db_len;
return mysql_bin_log.write_event(&qinfo);
}
/*
Function to free dboptions hash element
*/
extern "C" void free_dbopt(void *dbopt);
void free_dbopt(void *dbopt)
{
my_free(dbopt);
}
#ifdef HAVE_PSI_INTERFACE
static PSI_rwlock_key key_rwlock_LOCK_dboptions;
static PSI_rwlock_info all_database_names_rwlocks[]=
{
{ &key_rwlock_LOCK_dboptions, "LOCK_dboptions", PSI_FLAG_GLOBAL}
};
static void init_database_names_psi_keys(void)
{
const char* category= "sql";
int count;
count= array_elements(all_database_names_rwlocks);
mysql_rwlock_register(category, all_database_names_rwlocks, count);
}
#endif
/**
Initialize database option cache.
@note Must be called before any other database function is called.
@retval 0 ok
@retval 1 Fatal error
*/
bool my_dboptions_cache_init(void)
{
#ifdef HAVE_PSI_INTERFACE
init_database_names_psi_keys();
#endif
bool error= 0;
mysql_rwlock_init(key_rwlock_LOCK_dboptions, &LOCK_dboptions);
if (!dboptions_init)
{
dboptions_init= 1;
error= my_hash_init(&dboptions, lower_case_table_names ?
&my_charset_bin : system_charset_info,
32, 0, 0, (my_hash_get_key) dboptions_get_key,
free_dbopt,0);
}
return error;
}
/**
Free database option hash and locked databases hash.
*/
void my_dboptions_cache_free(void)
{
if (dboptions_init)
{
dboptions_init= 0;
my_hash_free(&dboptions);
mysql_rwlock_destroy(&LOCK_dboptions);
}
}
/**
Cleanup cached options.
*/
void my_dbopt_cleanup(void)
{
mysql_rwlock_wrlock(&LOCK_dboptions);
my_hash_free(&dboptions);
my_hash_init(&dboptions, lower_case_table_names ?
&my_charset_bin : system_charset_info,
32, 0, 0, (my_hash_get_key) dboptions_get_key,
free_dbopt,0);
mysql_rwlock_unlock(&LOCK_dboptions);
}
/*
Find database options in the hash.
DESCRIPTION
Search a database options in the hash, usings its path.
Fills "create" on success.
RETURN VALUES
0 on success.
1 on error.
*/
static my_bool get_dbopt(const char *dbname, HA_CREATE_INFO *create)
{
my_dbopt_t *opt;
uint length;
my_bool error= 1;
length= (uint) strlen(dbname);
mysql_rwlock_rdlock(&LOCK_dboptions);
if ((opt= (my_dbopt_t*) my_hash_search(&dboptions, (uchar*) dbname, length)))
{
create->default_table_charset= opt->charset;
error= 0;
}
mysql_rwlock_unlock(&LOCK_dboptions);
return error;
}
/*
Writes database options into the hash.
DESCRIPTION
Inserts database options into the hash, or updates
options if they are already in the hash.
RETURN VALUES
0 on success.
1 on error.
*/
static my_bool put_dbopt(const char *dbname, HA_CREATE_INFO *create)
{
my_dbopt_t *opt;
uint length;
my_bool error= 0;
DBUG_ENTER("put_dbopt");
length= (uint) strlen(dbname);
mysql_rwlock_wrlock(&LOCK_dboptions);
if (!(opt= (my_dbopt_t*) my_hash_search(&dboptions, (uchar*) dbname,
length)))
{
/* Options are not in the hash, insert them */
char *tmp_name;
if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
&opt, (uint) sizeof(*opt), &tmp_name, (uint) length+1,
NullS))
{
error= 1;
goto end;
}
opt->name= tmp_name;
strmov(opt->name, dbname);
opt->name_length= length;
if ((error= my_hash_insert(&dboptions, (uchar*) opt)))
{
my_free(opt);
goto end;
}
}
/* Update / write options in hash */
opt->charset= create->default_table_charset;
end:
mysql_rwlock_unlock(&LOCK_dboptions);
DBUG_RETURN(error);
}
/*
Deletes database options from the hash.
*/
static void del_dbopt(const char *path)
{
my_dbopt_t *opt;
mysql_rwlock_wrlock(&LOCK_dboptions);
if ((opt= (my_dbopt_t *)my_hash_search(&dboptions, (const uchar*) path,
strlen(path))))
my_hash_delete(&dboptions, (uchar*) opt);
mysql_rwlock_unlock(&LOCK_dboptions);
}
/*
Create database options file:
DESCRIPTION
Currently database default charset is only stored there.
RETURN VALUES
0 ok
1 Could not create file or write to it. Error sent through my_error()
*/
static bool write_db_opt(THD *thd, const char *path, HA_CREATE_INFO *create)
{
register File file;
char buf[256]; // Should be enough for one option
bool error=1;
if (!create->default_table_charset)
create->default_table_charset= thd->variables.collation_server;
if (put_dbopt(path, create))
return 1;
if ((file= mysql_file_create(key_file_dbopt, path, CREATE_MODE,
O_RDWR | O_TRUNC, MYF(MY_WME))) >= 0)
{
ulong length;
length= (ulong) (strxnmov(buf, sizeof(buf)-1, "default-character-set=",
create->default_table_charset->csname,
"\ndefault-collation=",
create->default_table_charset->name,
"\n", NullS) - buf);
/* Error is written by mysql_file_write */
if (!mysql_file_write(file, (uchar*) buf, length, MYF(MY_NABP+MY_WME)))
error=0;
mysql_file_close(file, MYF(0));
}
return error;
}
/*
Load database options file
load_db_opt()
path Path for option file
create Where to store the read options
DESCRIPTION
RETURN VALUES
0 File found
1 No database file or could not open it
*/
bool load_db_opt(THD *thd, const char *path, HA_CREATE_INFO *create)
{
File file;
char buf[256];
DBUG_ENTER("load_db_opt");
bool error=1;
uint nbytes;
memset(create, 0, sizeof(*create));
create->default_table_charset= thd->variables.collation_server;
/* Check if options for this database are already in the hash */
if (!get_dbopt(path, create))
DBUG_RETURN(0);
/* Otherwise, load options from the .opt file */
if ((file= mysql_file_open(key_file_dbopt,
path, O_RDONLY | O_SHARE, MYF(0))) < 0)
goto err1;
IO_CACHE cache;
if (init_io_cache(&cache, file, IO_SIZE, READ_CACHE, 0, 0, MYF(0)))
goto err2;
while ((int) (nbytes= my_b_gets(&cache, (char*) buf, sizeof(buf))) > 0)
{
char *pos= buf+nbytes-1;
/* Remove end space and control characters */
while (pos > buf && !my_isgraph(&my_charset_latin1, pos[-1]))
pos--;
*pos=0;
if ((pos= strchr(buf, '=')))
{
if (!strncmp(buf,"default-character-set", (pos-buf)))
{
/*
Try character set name, and if it fails
try collation name, probably it's an old
4.1.0 db.opt file, which didn't have
separate default-character-set and
default-collation commands.
*/
if (!(create->default_table_charset=
get_charset_by_csname(pos+1, MY_CS_PRIMARY, MYF(0))) &&
!(create->default_table_charset=
get_charset_by_name(pos+1, MYF(0))))
{
sql_print_error("Error while loading database options: '%s':",path);
sql_print_error(ER(ER_UNKNOWN_CHARACTER_SET),pos+1);
create->default_table_charset= default_charset_info;
}
}
else if (!strncmp(buf,"default-collation", (pos-buf)))
{
if (!(create->default_table_charset= get_charset_by_name(pos+1,
MYF(0))))
{
sql_print_error("Error while loading database options: '%s':",path);
sql_print_error(ER(ER_UNKNOWN_COLLATION),pos+1);
create->default_table_charset= default_charset_info;
}
}
}
}
/*
Put the loaded value into the hash.
Note that another thread could've added the same
entry to the hash after we called get_dbopt(),
but it's not an error, as put_dbopt() takes this
possibility into account.
*/
error= put_dbopt(path, create);
end_io_cache(&cache);
err2:
mysql_file_close(file, MYF(0));
err1:
DBUG_RETURN(error);
}
/*
Retrieve database options by name. Load database options file or fetch from
cache.
SYNOPSIS
load_db_opt_by_name()
db_name Database name
db_create_info Where to store the database options
DESCRIPTION
load_db_opt_by_name() is a shortcut for load_db_opt().
NOTE
Although load_db_opt_by_name() (and load_db_opt()) returns status of
the operation, it is useless usually and should be ignored. The problem
is that there are 1) system databases ("mysql") and 2) virtual
databases ("information_schema"), which do not contain options file.
So, load_db_opt[_by_name]() returns FALSE for these databases, but this
is not an error.
load_db_opt[_by_name]() clears db_create_info structure in any case, so
even on failure it contains valid data. So, common use case is just
call load_db_opt[_by_name]() without checking return value and use
db_create_info right after that.
RETURN VALUES (read NOTE!)
FALSE Success
TRUE Failed to retrieve options
*/
bool load_db_opt_by_name(THD *thd, const char *db_name,
HA_CREATE_INFO *db_create_info)
{
char db_opt_path[FN_REFLEN + 1];
/*
Pass an empty file name, and the database options file name as extension
to avoid table name to file name encoding.
*/
(void) build_table_filename(db_opt_path, sizeof(db_opt_path) - 1,
db_name, "", MY_DB_OPT_FILE, 0);
return load_db_opt(thd, db_opt_path, db_create_info);
}
/**
Return default database collation.
@param thd Thread context.
@param db_name Database name.
@return CHARSET_INFO object. The operation always return valid character
set, even if the database does not exist.
*/
const CHARSET_INFO *get_default_db_collation(THD *thd, const char *db_name)
{
HA_CREATE_INFO db_info;
if (thd->db != NULL && strcmp(db_name, thd->db) == 0)
return thd->db_charset;
load_db_opt_by_name(thd, db_name, &db_info);
/*
NOTE: even if load_db_opt_by_name() fails,
db_info.default_table_charset contains valid character set
(collation_server). We should not fail if load_db_opt_by_name() fails,
because it is valid case. If a database has been created just by
"mkdir", it does not contain db.opt file, but it is valid database.
*/
return db_info.default_table_charset;
}
/*
Create a database
SYNOPSIS
mysql_create_db()
thd Thread handler
db Name of database to create
Function assumes that this is already validated.
create_info Database create options (like character set)
silent Used by replication when internally creating a database.
In this case the entry should not be logged.
SIDE-EFFECTS
1. Report back to client that command succeeded (my_ok)
2. Report errors to client
3. Log event to binary log
(The 'silent' flags turns off 1 and 3.)
RETURN VALUES
FALSE ok
TRUE Error
*/
int mysql_create_db(THD *thd, char *db, HA_CREATE_INFO *create_info,
bool silent)
{
char path[FN_REFLEN+16];
char tmp_query[FN_REFLEN+16];
long result= 1;
int error= 0;
MY_STAT stat_info;
uint create_options= create_info ? create_info->options : 0;
uint path_len;
bool was_truncated;
DBUG_ENTER("mysql_create_db");
/* do not create 'information_schema' db */
if (is_infoschema_db(db))
{
my_error(ER_DB_CREATE_EXISTS, MYF(0), db);
DBUG_RETURN(-1);
}
if (lock_schema_name(thd, db))
DBUG_RETURN(-1);
/* Check directory */
path_len= build_table_filename(path, sizeof(path) - 1, db, "", "", 0,
&was_truncated);
if (was_truncated)
{
my_error(ER_IDENT_CAUSES_TOO_LONG_PATH, MYF(0), sizeof(path)-1, path);
DBUG_RETURN(-1);
}
path[path_len-1]= 0; // Remove last '/' from path
if (mysql_file_stat(key_file_misc, path, &stat_info, MYF(0)))
{
if (!(create_options & HA_LEX_CREATE_IF_NOT_EXISTS))
{
my_error(ER_DB_CREATE_EXISTS, MYF(0), db);
error= -1;
goto exit;
}
push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
ER_DB_CREATE_EXISTS, ER(ER_DB_CREATE_EXISTS), db);
error= 0;
goto not_silent;
}
else
{
if (my_errno != ENOENT)
{
char errbuf[MYSYS_STRERROR_SIZE];
my_error(EE_STAT, MYF(0), path,
my_errno, my_strerror(errbuf, sizeof(errbuf), my_errno));
goto exit;
}
if (my_mkdir(path,0777,MYF(0)) < 0)
{
my_error(ER_CANT_CREATE_DB, MYF(0), db, my_errno);
error= -1;
goto exit;
}
}
path[path_len-1]= FN_LIBCHAR;
strmake(path+path_len, MY_DB_OPT_FILE, sizeof(path)-path_len-1);
if (write_db_opt(thd, path, create_info))
{
/*
Could not create options file.
Restore things to beginning.
*/
path[path_len]= 0;
if (rmdir(path) >= 0)
{
error= -1;
goto exit;
}
/*
We come here when we managed to create the database, but not the option
file. In this case it's best to just continue as if nothing has
happened. (This is a very unlikely senario)
*/
thd->clear_error();
}
not_silent:
if (!silent)
{
char *query;
uint query_length;
char db_name_quoted[2 * FN_REFLEN + sizeof("create database ") + 2];
int id_len= 0;
if (!thd->query()) // Only in replication
{
id_len= my_strmov_quoted_identifier(thd, (char *) db_name_quoted, db,
0);
db_name_quoted[id_len]= '\0';
query= tmp_query;
query_length= (uint) (strxmov(tmp_query,"create database ",
db_name_quoted, NullS) - tmp_query);
}
else
{
query= thd->query();
query_length= thd->query_length();
}
ha_binlog_log_query(thd, 0, LOGCOM_CREATE_DB,
query, query_length,
db, "");
if (mysql_bin_log.is_open())
{
int errcode= query_error_code(thd, TRUE);
Query_log_event qinfo(thd, query, query_length, FALSE, TRUE,
/* suppress_use */ TRUE, errcode);
/*
Write should use the database being created as the "current
database" and not the threads current database, which is the
default. If we do not change the "current database" to the
database being created, the CREATE statement will not be
replicated when using --binlog-do-db to select databases to be
replicated.
An example (--binlog-do-db=sisyfos):
CREATE DATABASE bob; # Not replicated
USE bob; # 'bob' is the current database
CREATE DATABASE sisyfos; # Not replicated since 'bob' is
# current database.
USE sisyfos; # Will give error on slave since
# database does not exist.
*/
qinfo.db = db;
qinfo.db_len = strlen(db);
thd->add_to_binlog_accessed_dbs(db);
/*
These DDL methods and logging are protected with the exclusive
metadata lock on the schema
*/
if (mysql_bin_log.write_event(&qinfo))
{
error= -1;
goto exit;
}
}
my_ok(thd, result);
}
exit:
DBUG_RETURN(error);
}
/* db-name is already validated when we come here */
bool mysql_alter_db(THD *thd, const char *db, HA_CREATE_INFO *create_info)
{
char path[FN_REFLEN+16];
long result=1;
int error= 0;
DBUG_ENTER("mysql_alter_db");
if (lock_schema_name(thd, db))
DBUG_RETURN(TRUE);
/*
Recreate db options file: /dbpath/.db.opt
We pass MY_DB_OPT_FILE as "extension" to avoid
"table name to file name" encoding.
*/
build_table_filename(path, sizeof(path) - 1, db, "", MY_DB_OPT_FILE, 0);
if ((error=write_db_opt(thd, path, create_info)))
goto exit;
/* Change options if current database is being altered. */
if (thd->db && !strcmp(thd->db,db))
{
thd->db_charset= create_info->default_table_charset ?
create_info->default_table_charset :
thd->variables.collation_server;
thd->variables.collation_database= thd->db_charset;
}
ha_binlog_log_query(thd, 0, LOGCOM_ALTER_DB,
thd->query(), thd->query_length(),
db, "");
if (mysql_bin_log.is_open())
{
int errcode= query_error_code(thd, TRUE);
Query_log_event qinfo(thd, thd->query(), thd->query_length(), FALSE, TRUE,
/* suppress_use */ TRUE, errcode);
/*
Write should use the database being created as the "current
database" and not the threads current database, which is the
default.
*/
qinfo.db = db;
qinfo.db_len = strlen(db);
/*
These DDL methods and logging are protected with the exclusive
metadata lock on the schema.
*/
if ((error= mysql_bin_log.write_event(&qinfo)))
goto exit;
}
my_ok(thd, result);
exit:
DBUG_RETURN(error);
}
/**
Drop all tables, routines and events in a database and the database itself.
@param thd Thread handle
@param db Database name in the case given by user
It's already validated and set to lower case
(if needed) when we come here
@param if_exists Don't give error if database doesn't exists
@param silent Don't write the statement to the binary log and don't
send ok packet to the client
@retval false OK (Database dropped)
@retval true Error
*/
bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent)
{
ulong deleted_tables= 0;
bool error= true;
char path[2 * FN_REFLEN + 16];
MY_DIR *dirp;
uint length;
bool found_other_files= false;
TABLE_LIST *tables= NULL;
TABLE_LIST *table;
Drop_table_error_handler err_handler;
DBUG_ENTER("mysql_rm_db");
if (lock_schema_name(thd, db))
DBUG_RETURN(true);
length= build_table_filename(path, sizeof(path) - 1, db, "", "", 0);
strmov(path+length, MY_DB_OPT_FILE); // Append db option file name
del_dbopt(path); // Remove dboption hash entry
path[length]= '\0'; // Remove file name
/* See if the directory exists */
if (!(dirp= my_dir(path,MYF(MY_DONT_SORT))))
{
if (!if_exists)
{
my_error(ER_DB_DROP_EXISTS, MYF(0), db);
DBUG_RETURN(true);
}
else
{
push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
ER_DB_DROP_EXISTS, ER(ER_DB_DROP_EXISTS), db);
error= false;
goto update_binlog;
}
}
if (find_db_tables_and_rm_known_files(thd, dirp, db, path, &tables,
&found_other_files))
goto exit;
/*
Disable drop of enabled log tables, must be done before name locking.
This check is only needed if we are dropping the "mysql" database.
*/
if ((my_strcasecmp(system_charset_info, MYSQL_SCHEMA_NAME.str, db) == 0))
{
for (table= tables; table; table= table->next_local)
{
if (check_if_log_table(table->db_length, table->db,
table->table_name_length, table->table_name, true))
{
my_error(ER_BAD_LOG_STATEMENT, MYF(0), "DROP");
goto exit;
}
}
}
/* Lock all tables and stored routines about to be dropped. */
if (lock_table_names(thd, tables, NULL, thd->variables.lock_wait_timeout, 0) ||
lock_db_routines(thd, db))
goto exit;
/* mysql_ha_rm_tables() requires a non-null TABLE_LIST. */
if (tables)
mysql_ha_rm_tables(thd, tables);
for (table= tables; table; table= table->next_local)
{
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table->db, table->table_name,
false);
deleted_tables++;
}
thd->push_internal_handler(&err_handler);
if (!thd->killed &&
!(tables &&
mysql_rm_table_no_locks(thd, tables, true, false, true, true)))
{
/*
We temporarily disable the binary log while dropping the objects
in the database. Since the DROP DATABASE statement is always
replicated as a statement, execution of it will drop all objects
in the database on the slave as well, so there is no need to
replicate the removal of the individual objects in the database
as well.
This is more of a safety precaution, since normally no objects
should be dropped while the database is being cleaned, but in
the event that a change in the code to remove other objects is
made, these drops should still not be logged.
Notice that the binary log have to be enabled over the call to
ha_drop_database(), since NDB otherwise detects the binary log
as disabled and will not log the drop database statement on any
other connected server.
*/
ha_drop_database(path);
tmp_disable_binlog(thd);
query_cache_invalidate1(db);
(void) sp_drop_db_routines(thd, db); /* @todo Do not ignore errors */
#ifdef HAVE_EVENT_SCHEDULER
Events::drop_schema_events(thd, db);
#endif
reenable_binlog(thd);
/*
If the directory is a symbolic link, remove the link first, then
remove the directory the symbolic link pointed at
*/
if (found_other_files)
my_error(ER_DB_DROP_RMDIR, MYF(0), path, EEXIST);
else
error= rm_dir_w_symlink(path, true);
}
thd->pop_internal_handler();
update_binlog:
if (!silent && !error)
{
const char *query;
ulong query_length;
// quoted db name + wraping quote
char buffer_temp [2 * FN_REFLEN + 2];
int id_len= 0;
if (!thd->query())
{
/* The client used the old obsolete mysql_drop_db() call */
query= path;
id_len= my_strmov_quoted_identifier(thd, buffer_temp, db, strlen(db));
buffer_temp[id_len] ='\0';
query_length= (uint) (strxmov(path, "DROP DATABASE ", buffer_temp, "",
NullS) - path);
}
else
{
query= thd->query();
query_length= thd->query_length();
}
if (mysql_bin_log.is_open())
{
int errcode= query_error_code(thd, TRUE);
Query_log_event qinfo(thd, query, query_length, FALSE, TRUE,
/* suppress_use */ TRUE, errcode);
/*
Write should use the database being created as the "current
database" and not the threads current database, which is the
default.
*/
qinfo.db = db;
qinfo.db_len = strlen(db);
/*
These DDL methods and logging are protected with the exclusive
metadata lock on the schema.
*/
if (mysql_bin_log.write_event(&qinfo))
{
error= true;
goto exit;
}
}
thd->clear_error();
thd->server_status|= SERVER_STATUS_DB_DROPPED;
my_ok(thd, deleted_tables);
}
else if (mysql_bin_log.is_open() && !silent)
{
char *query, *query_pos, *query_end, *query_data_start;
char temp_identifier[ 2 * FN_REFLEN + 2];
TABLE_LIST *tbl;
uint db_len, id_length=0;
if (!(query= (char*) thd->alloc(MAX_DROP_TABLE_Q_LEN)))
goto exit; /* not much else we can do */
query_pos= query_data_start= strmov(query,"DROP TABLE IF EXISTS ");
query_end= query + MAX_DROP_TABLE_Q_LEN;
db_len= strlen(db);
for (tbl= tables; tbl; tbl= tbl->next_local)
{
uint tbl_name_len;
bool exists;
// Only write drop table to the binlog for tables that no longer exist.
if (check_if_table_exists(thd, tbl, 0, &exists))
{
error= true;
goto exit;
}
if (exists)
continue;
/* 3 for the quotes and the comma*/
tbl_name_len= strlen(tbl->table_name) + 3;
if (query_pos + tbl_name_len + 1 >= query_end)
{
/*
These DDL methods and logging are protected with the exclusive
metadata lock on the schema.
*/
if (write_to_binlog(thd, query, query_pos -1 - query, db, db_len))
{
error= true;
goto exit;
}
query_pos= query_data_start;
}
id_length= my_strmov_quoted_identifier(thd, (char *)temp_identifier,
tbl->table_name, 0);
temp_identifier[id_length]= '\0';
query_pos= strmov(query_pos,(char *)&temp_identifier);
*query_pos++ = ',';
}
if (query_pos != query_data_start)
{
thd->add_to_binlog_accessed_dbs(db);
/*
These DDL methods and logging are protected with the exclusive
metadata lock on the schema.
*/
if (write_to_binlog(thd, query, query_pos -1 - query, db, db_len))
{
error= true;
goto exit;
}
}
}
exit:
/*
If this database was the client's selected database, we silently
change the client's selected database to nothing (to have an empty
SELECT DATABASE() in the future). For this we free() thd->db and set
it to 0.
*/
if (thd->db && !strcmp(thd->db, db) && !error)
mysql_change_db_impl(thd, NULL, 0, thd->variables.collation_server);
my_dirend(dirp);
DBUG_RETURN(error);
}
static bool find_db_tables_and_rm_known_files(THD *thd, MY_DIR *dirp,
const char *db,
const char *path,
TABLE_LIST **tables,
bool *found_other_files)
{
char filePath[FN_REFLEN];
TABLE_LIST *tot_list=0, **tot_list_next_local, **tot_list_next_global;
DBUG_ENTER("find_db_tables_and_rm_known_files");
DBUG_PRINT("enter",("path: %s", path));
TYPELIB *known_extensions= ha_known_exts();
tot_list_next_local= tot_list_next_global= &tot_list;
for (uint idx=0 ;
idx < (uint) dirp->number_off_files && !thd->killed ;
idx++)
{
FILEINFO *file=dirp->dir_entry+idx;
char *extension;
DBUG_PRINT("info",("Examining: %s", file->name));
/* skiping . and .. */
if (file->name[0] == '.' && (!file->name[1] ||
(file->name[1] == '.' && !file->name[2])))
continue;
if (file->name[0] == 'a' && file->name[1] == 'r' &&
file->name[2] == 'c' && file->name[3] == '\0')
{
/* .frm archive:
Those archives are obsolete, but following code should
exist to remove existent "arc" directories.
*/
char newpath[FN_REFLEN];
MY_DIR *new_dirp;
strxmov(newpath, path, "/", "arc", NullS);
(void) unpack_filename(newpath, newpath);
if ((new_dirp = my_dir(newpath, MYF(MY_DONT_SORT))))
{
DBUG_PRINT("my",("Archive subdir found: %s", newpath));
if ((mysql_rm_arc_files(thd, new_dirp, newpath)) < 0)
DBUG_RETURN(true);
continue;
}
*found_other_files= true;
continue;
}
if (!(extension= strrchr(file->name, '.')))
extension= strend(file->name);
if (find_type(extension, &deletable_extentions, FIND_TYPE_NO_PREFIX) <= 0)
{
if (find_type(extension, known_extensions, FIND_TYPE_NO_PREFIX) <= 0)
*found_other_files= true;
continue;
}
/* just for safety we use files_charset_info */
if (db && !my_strcasecmp(files_charset_info,
extension, reg_ext))
{
/* Drop the table nicely */
*extension= 0; // Remove extension
TABLE_LIST *table_list=(TABLE_LIST*)
thd->calloc(sizeof(*table_list) +
strlen(db) + 1 +
MYSQL50_TABLE_NAME_PREFIX_LENGTH +
strlen(file->name) + 1);
if (!table_list)
DBUG_RETURN(true);
table_list->db= (char*) (table_list+1);
table_list->db_length= strmov(table_list->db, db) - table_list->db;
table_list->table_name= table_list->db + table_list->db_length + 1;
table_list->table_name_length= filename_to_tablename(file->name,
table_list->table_name,
MYSQL50_TABLE_NAME_PREFIX_LENGTH +
strlen(file->name) + 1);
table_list->open_type= OT_BASE_ONLY;
/* To be able to correctly look up the table in the table cache. */
if (lower_case_table_names)
table_list->table_name_length= my_casedn_str(files_charset_info,
table_list->table_name);
table_list->alias= table_list->table_name; // If lower_case_table_names=2
table_list->internal_tmp_table= is_prefix(file->name, tmp_file_prefix);
table_list->mdl_request.init(MDL_key::TABLE, table_list->db,
table_list->table_name, MDL_EXCLUSIVE,
MDL_TRANSACTION);
/* Link into list */
(*tot_list_next_local)= table_list;
(*tot_list_next_global)= table_list;
tot_list_next_local= &table_list->next_local;
tot_list_next_global= &table_list->next_global;
}
else
{
strxmov(filePath, path, "/", file->name, NullS);
/*
We ignore ENOENT error in order to skip files that was deleted
by concurrently running statement like REAPIR TABLE ...
*/
if (my_delete_with_symlink(filePath, MYF(0)) &&
my_errno != ENOENT)
{
char errbuf[MYSYS_STRERROR_SIZE];
my_error(EE_DELETE, MYF(0), filePath,
my_errno, my_strerror(errbuf, sizeof(errbuf), my_errno));
DBUG_RETURN(true);
}
}
}
*tables= tot_list;
DBUG_RETURN(false);
}
/*
Remove directory with symlink
SYNOPSIS
rm_dir_w_symlink()
org_path path of derictory
send_error send errors
RETURN
0 OK
1 ERROR
*/
static my_bool rm_dir_w_symlink(const char *org_path, my_bool send_error)
{
char tmp_path[FN_REFLEN], *pos;
char *path= tmp_path;
DBUG_ENTER("rm_dir_w_symlink");
unpack_filename(tmp_path, org_path);
#ifdef HAVE_READLINK
int error;
char tmp2_path[FN_REFLEN];
/* Remove end FN_LIBCHAR as this causes problem on Linux in readlink */
pos= strend(path);
if (pos > path && pos[-1] == FN_LIBCHAR)
*--pos=0;
if ((error= my_readlink(tmp2_path, path, MYF(MY_WME))) < 0)
DBUG_RETURN(1);
if (!error)
{
if (mysql_file_delete(key_file_misc, path, MYF(send_error ? MY_WME : 0)))
{
DBUG_RETURN(send_error);
}
/* Delete directory symbolic link pointed at */
path= tmp2_path;
}
#endif
/* Remove last FN_LIBCHAR to not cause a problem on OS/2 */
pos= strend(path);
if (pos > path && pos[-1] == FN_LIBCHAR)
*--pos=0;
if (rmdir(path) < 0 && send_error)
{
my_error(ER_DB_DROP_RMDIR, MYF(0), path, errno);
DBUG_RETURN(1);
}
DBUG_RETURN(0);
}
/*
Remove .frm archives from directory
SYNOPSIS
thd thread handler
dirp list of files in archive directory
db data base name
org_path path of archive directory
RETURN
> 0 number of removed files
-1 error
NOTE
A support of "arc" directories is obsolete, however this
function should exist to remove existent "arc" directories.
*/
long mysql_rm_arc_files(THD *thd, MY_DIR *dirp, const char *org_path)
{
long deleted= 0;
ulong found_other_files= 0;
char filePath[FN_REFLEN];
DBUG_ENTER("mysql_rm_arc_files");
DBUG_PRINT("enter", ("path: %s", org_path));
for (uint idx=0 ;
idx < (uint) dirp->number_off_files && !thd->killed ;
idx++)
{
FILEINFO *file=dirp->dir_entry+idx;
char *extension, *revision;
DBUG_PRINT("info",("Examining: %s", file->name));
/* skiping . and .. */
if (file->name[0] == '.' && (!file->name[1] ||
(file->name[1] == '.' && !file->name[2])))
continue;
extension= fn_ext(file->name);
if (extension[0] != '.' ||
extension[1] != 'f' || extension[2] != 'r' ||
extension[3] != 'm' || extension[4] != '-')
{
found_other_files++;
continue;
}
revision= extension+5;
while (*revision && my_isdigit(system_charset_info, *revision))
revision++;
if (*revision)
{
found_other_files++;
continue;
}
strxmov(filePath, org_path, "/", file->name, NullS);
if (mysql_file_delete_with_symlink(key_file_misc, filePath, MYF(MY_WME)))
{
goto err;
}
deleted++;
}
if (thd->killed)
goto err;
my_dirend(dirp);
/*
If the directory is a symbolic link, remove the link first, then
remove the directory the symbolic link pointed at
*/
if (!found_other_files &&
rm_dir_w_symlink(org_path, 0))
DBUG_RETURN(-1);
DBUG_RETURN(deleted);
err:
my_dirend(dirp);
DBUG_RETURN(-1);
}
/**
@brief Internal implementation: switch current database to a valid one.
@param thd Thread context.
@param new_db_name Name of the database to switch to. The function will
take ownership of the name (the caller must not free
the allocated memory). If the name is NULL, we're
going to switch to NULL db.
@param new_db_access Privileges of the new database.
@param new_db_charset Character set of the new database.
*/
static void mysql_change_db_impl(THD *thd,
LEX_STRING *new_db_name,
ulong new_db_access,
const CHARSET_INFO *new_db_charset)
{
/* 1. Change current database in THD. */
if (new_db_name == NULL)
{
/*
THD::set_db() does all the job -- it frees previous database name and
sets the new one.
*/
thd->set_db(NULL, 0);
}
else if (new_db_name == &INFORMATION_SCHEMA_NAME)
{
/*
Here we must use THD::set_db(), because we want to copy
INFORMATION_SCHEMA_NAME constant.
*/
thd->set_db(INFORMATION_SCHEMA_NAME.str, INFORMATION_SCHEMA_NAME.length);
}
else
{
/*
Here we already have a copy of database name to be used in THD. So,
we just call THD::reset_db(). Since THD::reset_db() does not releases
the previous database name, we should do it explicitly.
*/
mysql_mutex_lock(&thd->LOCK_thd_data);
if (thd->db)
my_free(thd->db);
DEBUG_SYNC(thd, "after_freeing_thd_db");
thd->reset_db(new_db_name->str, new_db_name->length);
mysql_mutex_unlock(&thd->LOCK_thd_data);
}
/* 2. Update security context. */
#ifndef NO_EMBEDDED_ACCESS_CHECKS
thd->security_ctx->db_access= new_db_access;
#endif
/* 3. Update db-charset environment variables. */
thd->db_charset= new_db_charset;
thd->variables.collation_database= new_db_charset;
}
/**
Backup the current database name before switch.
@param[in] thd thread handle
@param[in, out] saved_db_name IN: "str" points to a buffer where to store
the old database name, "length" contains the
buffer size
OUT: if the current (default) database is
not NULL, its name is copied to the
buffer pointed at by "str"
and "length" is updated accordingly.
Otherwise "str" is set to NULL and
"length" is set to 0.
*/
static void backup_current_db_name(THD *thd,
LEX_STRING *saved_db_name)
{
if (!thd->db)
{
/* No current (default) database selected. */
saved_db_name->str= NULL;
saved_db_name->length= 0;
}
else
{
strmake(saved_db_name->str, thd->db, saved_db_name->length - 1);
saved_db_name->length= thd->db_length;
}
}
/**
Return TRUE if db1_name is equal to db2_name, FALSE otherwise.
The function allows to compare database names according to the MySQL
rules. The database names db1 and db2 are equal if:
- db1 is NULL and db2 is NULL;
or
- db1 is not-NULL, db2 is not-NULL, db1 is equal (ignoring case) to
db2 in system character set (UTF8).
*/
static inline bool
cmp_db_names(const char *db1_name,
const char *db2_name)
{
return
/* db1 is NULL and db2 is NULL */
(!db1_name && !db2_name) ||
/* db1 is not-NULL, db2 is not-NULL, db1 == db2. */
(db1_name && db2_name &&
my_strcasecmp(system_charset_info, db1_name, db2_name) == 0);
}
/**
@brief Change the current database and its attributes unconditionally.
@param thd thread handle
@param new_db_name database name
@param force_switch if force_switch is FALSE, then the operation will fail if
- new_db_name is NULL or empty;
- OR new database name is invalid
(check_db_name() failed);
- OR user has no privilege on the new database;
- OR new database does not exist;
if force_switch is TRUE, then
- if new_db_name is NULL or empty, the current
database will be NULL, @@collation_database will
be set to @@collation_server, the operation will
succeed.
- if new database name is invalid
(check_db_name() failed), the current database
will be NULL, @@collation_database will be set to
@@collation_server, but the operation will fail;
- user privileges will not be checked
(THD::db_access however is updated);
TODO: is this really the intention?
(see sp-security.test).
- if new database does not exist,the current database
will be NULL, @@collation_database will be set to
@@collation_server, a warning will be thrown, the
operation will succeed.
@details The function checks that the database name corresponds to a
valid and existent database, checks access rights and changes the current
database with database attributes (@@collation_database session variable,
THD::db_access).
This function is not the only way to switch the database that is
currently employed. When the replication slave thread switches the
database before executing a query, it calls thd->set_db directly.
However, if the query, in turn, uses a stored routine, the stored routine
will use this function, even if it's run on the slave.
This function allocates the name of the database on the system heap: this
is necessary to be able to uniformly change the database from any module
of the server. Up to 5.0 different modules were using different memory to
store the name of the database, and this led to memory corruption:
a stack pointer set by Stored Procedures was used by replication after
the stack address was long gone.
@return Operation status
@retval FALSE Success
@retval TRUE Error
*/
bool mysql_change_db(THD *thd, const LEX_STRING *new_db_name, bool force_switch)
{
LEX_STRING new_db_file_name;
Security_context *sctx= thd->security_ctx;
ulong db_access= sctx->db_access;
const CHARSET_INFO *db_default_cl;
DBUG_ENTER("mysql_change_db");
DBUG_PRINT("enter",("name: '%s'", new_db_name->str));
if (new_db_name == NULL ||
new_db_name->length == 0)
{
if (force_switch)
{
/*
This can happen only if we're switching the current database back
after loading stored program. The thing is that loading of stored
program can happen when there is no current database.
TODO: actually, new_db_name and new_db_name->str seem to be always
non-NULL. In case of stored program, new_db_name->str == "" and
new_db_name->length == 0.
*/
mysql_change_db_impl(thd, NULL, 0, thd->variables.collation_server);
DBUG_RETURN(FALSE);
}
else
{
my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
DBUG_RETURN(TRUE);
}
}
if (is_infoschema_db(new_db_name->str, new_db_name->length))
{
/* Switch the current database to INFORMATION_SCHEMA. */
mysql_change_db_impl(thd, &INFORMATION_SCHEMA_NAME, SELECT_ACL,
system_charset_info);
DBUG_RETURN(FALSE);
}
/*
Now we need to make a copy because check_db_name requires a
non-constant argument. Actually, it takes database file name.
TODO: fix check_db_name().
*/
new_db_file_name.str= my_strndup(new_db_name->str, new_db_name->length,
MYF(MY_WME));
new_db_file_name.length= new_db_name->length;
if (new_db_file_name.str == NULL)
DBUG_RETURN(TRUE); /* the error is set */
/*
NOTE: if check_db_name() fails, we should throw an error in any case,
even if we are called from sp_head::execute().
It's next to impossible however to get this error when we are called
from sp_head::execute(). But let's switch the current database to NULL
in this case to be sure.
*/
if (check_and_convert_db_name(&new_db_file_name, FALSE) != IDENT_NAME_OK)
{
my_free(new_db_file_name.str);
if (force_switch)
mysql_change_db_impl(thd, NULL, 0, thd->variables.collation_server);
DBUG_RETURN(TRUE);
}
DBUG_PRINT("info",("Use database: %s", new_db_file_name.str));
#ifndef NO_EMBEDDED_ACCESS_CHECKS
db_access=
test_all_bits(sctx->master_access, DB_ACLS) ?
DB_ACLS :
acl_get(sctx->get_host()->ptr(),
sctx->get_ip()->ptr(),
sctx->priv_user,
new_db_file_name.str,
FALSE) | sctx->master_access;
if (!force_switch &&
!(db_access & DB_ACLS) &&
check_grant_db(thd, new_db_file_name.str))
{
my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
sctx->priv_user,
sctx->priv_host,
new_db_file_name.str);
general_log_print(thd, COM_INIT_DB, ER(ER_DBACCESS_DENIED_ERROR),
sctx->priv_user, sctx->priv_host, new_db_file_name.str);
my_free(new_db_file_name.str);
DBUG_RETURN(TRUE);
}
#endif
DEBUG_SYNC(thd, "before_db_dir_check");
if (check_db_dir_existence(new_db_file_name.str))
{
if (force_switch)
{
/* Throw a warning and free new_db_file_name. */
push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
ER_BAD_DB_ERROR, ER(ER_BAD_DB_ERROR),
new_db_file_name.str);
my_free(new_db_file_name.str);
/* Change db to NULL. */
mysql_change_db_impl(thd, NULL, 0, thd->variables.collation_server);
/* The operation succeed. */
DBUG_RETURN(FALSE);
}
else
{
/* Report an error and free new_db_file_name. */
my_error(ER_BAD_DB_ERROR, MYF(0), new_db_file_name.str);
my_free(new_db_file_name.str);
/* The operation failed. */
DBUG_RETURN(TRUE);
}
}
/*
NOTE: in mysql_change_db_impl() new_db_file_name is assigned to THD
attributes and will be freed in THD::~THD().
*/
db_default_cl= get_default_db_collation(thd, new_db_file_name.str);
mysql_change_db_impl(thd, &new_db_file_name, db_access, db_default_cl);
DBUG_RETURN(FALSE);
}
/**
Change the current database and its attributes if needed.
@param thd thread handle
@param new_db_name database name
@param[in, out] saved_db_name IN: "str" points to a buffer where to store
the old database name, "length" contains the
buffer size
OUT: if the current (default) database is
not NULL, its name is copied to the
buffer pointed at by "str"
and "length" is updated accordingly.
Otherwise "str" is set to NULL and
"length" is set to 0.
@param force_switch @see mysql_change_db()
@param[out] cur_db_changed out-flag to indicate whether the current
database has been changed (valid only if
the function suceeded)
*/
bool mysql_opt_change_db(THD *thd,
const LEX_STRING *new_db_name,
LEX_STRING *saved_db_name,
bool force_switch,
bool *cur_db_changed)
{
*cur_db_changed= !cmp_db_names(thd->db, new_db_name->str);
if (!*cur_db_changed)
return FALSE;
backup_current_db_name(thd, saved_db_name);
return mysql_change_db(thd, new_db_name, force_switch);
}
/**
Upgrade a 5.0 database.
This function is invoked whenever an ALTER DATABASE UPGRADE query is executed:
ALTER DATABASE 'olddb' UPGRADE DATA DIRECTORY NAME.
If we have managed to rename (move) tables to the new database
but something failed on a later step, then we store the
RENAME DATABASE event in the log. mysql_rename_db() is atomic in
the sense that it will rename all or none of the tables.
@param thd Current thread
@param old_db 5.0 database name, in #mysql50#name format
@return 0 on success, 1 on error
*/
bool mysql_upgrade_db(THD *thd, LEX_STRING *old_db)
{
int error= 0, change_to_newdb= 0;
char path[FN_REFLEN+16];
uint length;
HA_CREATE_INFO create_info;
MY_DIR *dirp;
TABLE_LIST *table_list;
SELECT_LEX *sl= thd->lex->current_select;
LEX_STRING new_db;
DBUG_ENTER("mysql_upgrade_db");
if ((old_db->length <= MYSQL50_TABLE_NAME_PREFIX_LENGTH) ||
(strncmp(old_db->str,
MYSQL50_TABLE_NAME_PREFIX,
MYSQL50_TABLE_NAME_PREFIX_LENGTH) != 0))
{
my_error(ER_WRONG_USAGE, MYF(0),
"ALTER DATABASE UPGRADE DATA DIRECTORY NAME",
"name");
DBUG_RETURN(1);
}
/* `#mysql50#<name>` converted to encoded `<name>` */
new_db.str= old_db->str + MYSQL50_TABLE_NAME_PREFIX_LENGTH;
new_db.length= old_db->length - MYSQL50_TABLE_NAME_PREFIX_LENGTH;
/* Lock the old name, the new name will be locked by mysql_create_db().*/
if (lock_schema_name(thd, old_db->str))
DBUG_RETURN(-1);
/*
Let's remember if we should do "USE newdb" afterwards.
thd->db will be cleared in mysql_rename_db()
*/
if (thd->db && !strcmp(thd->db, old_db->str))
change_to_newdb= 1;
build_table_filename(path, sizeof(path)-1,
old_db->str, "", MY_DB_OPT_FILE, 0);
if ((load_db_opt(thd, path, &create_info)))
create_info.default_table_charset= thd->variables.collation_server;
length= build_table_filename(path, sizeof(path)-1, old_db->str, "", "", 0);
if (length && path[length-1] == FN_LIBCHAR)
path[length-1]=0; // remove ending '\'
if ((error= my_access(path,F_OK)))
{
my_error(ER_BAD_DB_ERROR, MYF(0), old_db->str);
goto exit;
}
/* Step1: Create the new database */
if ((error= mysql_create_db(thd, new_db.str, &create_info, 1)))
goto exit;
/* Step2: Move tables to the new database */
if ((dirp = my_dir(path,MYF(MY_DONT_SORT))))
{
uint nfiles= (uint) dirp->number_off_files;
for (uint idx=0 ; idx < nfiles && !thd->killed ; idx++)
{
FILEINFO *file= dirp->dir_entry + idx;
char *extension, tname[FN_REFLEN + 1];
LEX_STRING table_str;
DBUG_PRINT("info",("Examining: %s", file->name));
/* skiping non-FRM files */
if (my_strcasecmp(files_charset_info,
(extension= fn_rext(file->name)), reg_ext))
continue;
/* A frm file found, add the table info rename list */
*extension= '\0';
table_str.length= filename_to_tablename(file->name,
tname, sizeof(tname)-1);
table_str.str= (char*) sql_memdup(tname, table_str.length + 1);
Table_ident *old_ident= new Table_ident(thd, *old_db, table_str, 0);
Table_ident *new_ident= new Table_ident(thd, new_db, table_str, 0);
if (!old_ident || !new_ident ||
!sl->add_table_to_list(thd, old_ident, NULL,
TL_OPTION_UPDATING, TL_IGNORE,
MDL_EXCLUSIVE) ||
!sl->add_table_to_list(thd, new_ident, NULL,
TL_OPTION_UPDATING, TL_IGNORE,
MDL_EXCLUSIVE))
{
error= 1;
my_dirend(dirp);
goto exit;
}
}
my_dirend(dirp);
}
if ((table_list= thd->lex->query_tables) &&
(error= mysql_rename_tables(thd, table_list, 1)))
{
/*
Failed to move all tables from the old database to the new one.
In the best case mysql_rename_tables() moved all tables back to the old
database. In the worst case mysql_rename_tables() moved some tables
to the new database, then failed, then started to move the tables back,
and then failed again. In this situation we have some tables in the
old database and some tables in the new database.
Let's delete the option file, and then the new database directory.
If some tables were left in the new directory, rmdir() will fail.
It garantees we never loose any tables.
*/
build_table_filename(path, sizeof(path)-1,
new_db.str,"",MY_DB_OPT_FILE, 0);
mysql_file_delete(key_file_dbopt, path, MYF(MY_WME));
length= build_table_filename(path, sizeof(path)-1, new_db.str, "", "", 0);
if (length && path[length-1] == FN_LIBCHAR)
path[length-1]=0; // remove ending '\'
rmdir(path);
goto exit;
}
/*
Step3: move all remaining files to the new db's directory.
Skip db opt file: it's been created by mysql_create_db() in
the new directory, and will be dropped by mysql_rm_db() in the old one.
Trigger TRN and TRG files are be moved as regular files at the moment,
without any special treatment.
Triggers without explicit database qualifiers in table names work fine:
use d1;
create trigger trg1 before insert on t2 for each row set @a:=1
rename database d1 to d2;
TODO: Triggers, having the renamed database explicitely written
in the table qualifiers.
1. when the same database is renamed:
create trigger d1.trg1 before insert on d1.t1 for each row set @a:=1;
rename database d1 to d2;
Problem: After database renaming, the trigger's body
still points to the old database d1.
2. when another database is renamed:
create trigger d3.trg1 before insert on d3.t1 for each row
insert into d1.t1 values (...);
rename database d1 to d2;
Problem: After renaming d1 to d2, the trigger's body
in the database d3 still points to database d1.
*/
if ((dirp = my_dir(path,MYF(MY_DONT_SORT))))
{
uint nfiles= (uint) dirp->number_off_files;
for (uint idx=0 ; idx < nfiles ; idx++)
{
FILEINFO *file= dirp->dir_entry + idx;
char oldname[FN_REFLEN + 1], newname[FN_REFLEN + 1];
DBUG_PRINT("info",("Examining: %s", file->name));
/* skiping . and .. and MY_DB_OPT_FILE */
if ((file->name[0] == '.' &&
(!file->name[1] || (file->name[1] == '.' && !file->name[2]))) ||
!my_strcasecmp(files_charset_info, file->name, MY_DB_OPT_FILE))
continue;
/* pass empty file name, and file->name as extension to avoid encoding */
build_table_filename(oldname, sizeof(oldname)-1,
old_db->str, "", file->name, 0);
build_table_filename(newname, sizeof(newname)-1,
new_db.str, "", file->name, 0);
mysql_file_rename(key_file_misc, oldname, newname, MYF(MY_WME));
}
my_dirend(dirp);
}
/*
Step7: drop the old database.
query_cache_invalidate(olddb) is done inside mysql_rm_db(), no need
to execute them again.
mysql_rm_db() also "unuses" if we drop the current database.
*/
error= mysql_rm_db(thd, old_db->str, 0, 1);
/* Step8: logging */
if (mysql_bin_log.is_open())
{
int errcode= query_error_code(thd, TRUE);
Query_log_event qinfo(thd, thd->query(), thd->query_length(),
FALSE, TRUE, TRUE, errcode);
thd->clear_error();
error|= mysql_bin_log.write_event(&qinfo);
}
/* Step9: Let's do "use newdb" if we renamed the current database */
if (change_to_newdb)
error|= mysql_change_db(thd, & new_db, FALSE);
exit:
DBUG_RETURN(error);
}
/*
Check if there is directory for the database name.
SYNOPSIS
check_db_dir_existence()
db_name database name
RETURN VALUES
FALSE There is directory for the specified database name.
TRUE The directory does not exist.
*/
bool check_db_dir_existence(const char *db_name)
{
char db_dir_path[FN_REFLEN + 1];
uint db_dir_path_len;
db_dir_path_len= build_table_filename(db_dir_path, sizeof(db_dir_path) - 1,
db_name, "", "", 0);
if (db_dir_path_len && db_dir_path[db_dir_path_len - 1] == FN_LIBCHAR)
db_dir_path[db_dir_path_len - 1]= 0;
/* Check access. */
return my_access(db_dir_path, F_OK);
}
| 30.335801 | 81 | 0.619995 | hervewenjie |
82975711f45a5ce8804471a2f43e00dadc3516b1 | 441 | cpp | C++ | 10_smart_pointers/10_02_unique_ptr_as_raii/10_02_00_unique_ptr_as_raii.cpp | pAbogn/cpp_courses | 6ffa7da5cc440af3327139a38cfdefcfaae1ebed | [
"MIT"
] | 13 | 2020-09-01T14:57:21.000Z | 2021-11-24T06:00:26.000Z | 10_smart_pointers/10_02_unique_ptr_as_raii/10_02_00_unique_ptr_as_raii.cpp | pAbogn/cpp_courses | 6ffa7da5cc440af3327139a38cfdefcfaae1ebed | [
"MIT"
] | 5 | 2020-06-11T14:13:00.000Z | 2021-07-14T05:27:53.000Z | 10_smart_pointers/10_02_unique_ptr_as_raii/10_02_00_unique_ptr_as_raii.cpp | pAbogn/cpp_courses | 6ffa7da5cc440af3327139a38cfdefcfaae1ebed | [
"MIT"
] | 10 | 2021-03-22T07:54:36.000Z | 2021-09-15T04:03:32.000Z | // Smart pointer with unique ownership
#include <memory>
#include <cassert>
int main() {
std::unique_ptr<int> uptr1(new int(1));
int val = *uptr1;
std::unique_ptr<int> uptr2 = uptr1; // Fail
std::unique_ptr<int> uptr3 = std::move(uptr1); // OK
assert(uptr3);
assert(uptr1);
uptr3.reset(new int(2)); // Object 1 is destroyed, uptr3 points to object 2
// When ~uptr3 is called - object 2 is destroyed
}
| 20.045455 | 79 | 0.637188 | pAbogn |
829938fcbfbf99683931febb7557abde852381af | 2,147 | cpp | C++ | ccm/demo/HelloWorld/src/StdHelloWorldDll.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | 2 | 2020-01-06T07:43:30.000Z | 2020-07-11T20:53:53.000Z | ccm/demo/HelloWorld/src/StdHelloWorldDll.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | null | null | null | ccm/demo/HelloWorld/src/StdHelloWorldDll.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | null | null | null | // **********************************************************************
//
// Generated by the IDL3 Translator
//
// Copyright (c) 2001-2004
// StarMiddleware Group
// www.StarMiddleware.net
//
// All Rights Reserved
//
// Author: Huang Jie huangjie@email.com
// Author: Chang Junsheng cjs7908@163.com
// Author: Zhen Xianrong
//
// **********************************************************************
#include <CORBA.h>
#include <CCM_HelloWorld_impl.h>
#include <HelloWorld_ValueType_impl.h>
#ifdef WIN32
#ifdef ORBacus
JTCInitialize* pJTCInitialize;
#endif
#ifdef StarBus
MTLInitialize* pMTLInitialize;
#endif
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD reason,
LPVOID lpReserved)
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
#ifdef ORBacus
pJTCInitialize = new JTCInitialize();
#endif
#ifdef StarBus
pMTLInitialize = new MTLInitialize();
#endif
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
#ifdef ORBacus
delete pJTCInitialize;
#endif
#ifdef StarBus
delete pMTLInitialize;
#endif
break;
}
return TRUE;
}
extern "C"
{
};
#else
extern "C"
{
};
#endif
// **********************************************************************
//
// Generated by the CIDL Translator
//
// Copyright (c) 2001-2004
// StarMiddleware Group
// www.StarMiddleware.net
//
// All Rights Reserved
//
// Author: Huang Jie huangjie@email.com
// Author: Chang Junsheng cjs7908@163.com
// Author: Zhen Xianrong
//
// **********************************************************************
#ifdef WIN32
extern "C"
{
__declspec(dllexport) Components::HomeExecutorBase*
createHelloWorldPersonImplCCM_PersonHome_impl();
};
#else
extern "C"
{
Components::HomeExecutorBase*
createHelloWorldPersonImplCCM_PersonHome_impl();
};
#endif
Components::HomeExecutorBase*
createHelloWorldPersonImplCCM_PersonHome_impl()
{
return new HelloWorld::PersonImpl::CCM_PersonHome_impl();
}
| 18.669565 | 73 | 0.571029 | anjingbin |
8299d9d868c2aad80d0a7bfd0a65cab89922584a | 2,471 | cpp | C++ | Demos3/bullet2/ConstraintDemo/ConstraintPhysicsSetup.cpp | jackoalan/bullet3 | 4276b2f06aa652a00b798666ae68013fc6c950e3 | [
"Zlib"
] | null | null | null | Demos3/bullet2/ConstraintDemo/ConstraintPhysicsSetup.cpp | jackoalan/bullet3 | 4276b2f06aa652a00b798666ae68013fc6c950e3 | [
"Zlib"
] | null | null | null | Demos3/bullet2/ConstraintDemo/ConstraintPhysicsSetup.cpp | jackoalan/bullet3 | 4276b2f06aa652a00b798666ae68013fc6c950e3 | [
"Zlib"
] | null | null | null | #include "ConstraintPhysicsSetup.h"
ConstraintPhysicsSetup::ConstraintPhysicsSetup()
{
}
ConstraintPhysicsSetup::~ConstraintPhysicsSetup()
{
}
btScalar val;
btHingeAccumulatedAngleConstraint* spDoorHinge=0;
void ConstraintPhysicsSetup::stepSimulation(float deltaTime)
{
val=spDoorHinge->getAccumulatedHingeAngle()*SIMD_DEGS_PER_RAD;// spDoorHinge->getHingeAngle()*SIMD_DEGS_PER_RAD;
if (m_dynamicsWorld)
{
m_dynamicsWorld->stepSimulation(deltaTime);
}
}
void ConstraintPhysicsSetup::initPhysics(GraphicsPhysicsBridge& gfxBridge)
{
gfxBridge.setUpAxis(1);
createEmptyDynamicsWorld();
gfxBridge.createPhysicsDebugDrawer(m_dynamicsWorld);
int mode = btIDebugDraw::DBG_DrawWireframe
+btIDebugDraw::DBG_DrawConstraints
+btIDebugDraw::DBG_DrawConstraintLimits;
m_dynamicsWorld->getDebugDrawer()->setDebugMode(mode);
val=1.f;
SliderParams slider("hinge angle",&val);
slider.m_minVal=-720;
slider.m_maxVal=720;
gfxBridge.getParameterInterface()->registerSliderFloatParameter(slider);
{ // create a door using hinge constraint attached to the world
btCollisionShape* pDoorShape = new btBoxShape(btVector3(2.0f, 5.0f, 0.2f));
m_collisionShapes.push_back(pDoorShape);
btTransform doorTrans;
doorTrans.setIdentity();
doorTrans.setOrigin(btVector3(-5.0f, -2.0f, 0.0f));
btRigidBody* pDoorBody = createRigidBody( 1.0, doorTrans, pDoorShape);
pDoorBody->setActivationState(DISABLE_DEACTIVATION);
const btVector3 btPivotA(10.f + 2.1f, -2.0f, 0.0f ); // right next to the door slightly outside
btVector3 btAxisA( 0.0f, 1.0f, 0.0f ); // pointing upwards, aka Y-axis
spDoorHinge = new btHingeAccumulatedAngleConstraint( *pDoorBody, btPivotA, btAxisA );
// spDoorHinge->setLimit( 0.0f, SIMD_PI_2 );
// test problem values
// spDoorHinge->setLimit( -SIMD_PI, SIMD_PI*0.8f);
// spDoorHinge->setLimit( 1.f, -1.f);
// spDoorHinge->setLimit( -SIMD_PI*0.8f, SIMD_PI);
// spDoorHinge->setLimit( -SIMD_PI*0.8f, SIMD_PI, 0.9f, 0.3f, 0.0f);
// spDoorHinge->setLimit( -SIMD_PI*0.8f, SIMD_PI, 0.9f, 0.01f, 0.0f); // "sticky limits"
// spDoorHinge->setLimit( -SIMD_PI * 0.25f, SIMD_PI * 0.25f );
// spDoorHinge->setLimit( 0.0f, 0.0f );
m_dynamicsWorld->addConstraint(spDoorHinge);
spDoorHinge->setDbgDrawSize(btScalar(5.f));
//doorTrans.setOrigin(btVector3(-5.0f, 2.0f, 0.0f));
//btRigidBody* pDropBody = localCreateRigidBody( 10.0, doorTrans, shape);
}
} | 34.319444 | 114 | 0.730473 | jackoalan |
8299e8bbef89bb086c2f5153fbf9a281e009a0d7 | 106 | cpp | C++ | CPP/CPPASTL/Day01/index.cpp | wolflion/Code2018 | 352ec55527602eb592b1936ec9d4c7d3a2368bb8 | [
"Apache-2.0"
] | null | null | null | CPP/CPPASTL/Day01/index.cpp | wolflion/Code2018 | 352ec55527602eb592b1936ec9d4c7d3a2368bb8 | [
"Apache-2.0"
] | null | null | null | CPP/CPPASTL/Day01/index.cpp | wolflion/Code2018 | 352ec55527602eb592b1936ec9d4c7d3a2368bb8 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
#define MAX 1024
int main()
{
cout << MAX << endl;
return 0;
} | 10.6 | 21 | 0.660377 | wolflion |
8299f4ed8b13761148537ce51959a8ffaacb9d93 | 834 | cpp | C++ | Arrays/Two Sum.cpp | nitishkalra/Coding-Problems-Solved | 3f5944a2bfb78f2ad7992c6224ef3c1099566fc8 | [
"MIT"
] | 2 | 2020-11-05T07:34:14.000Z | 2020-11-05T07:47:15.000Z | Arrays/Two Sum.cpp | nitishkalra/Coding-Problems-Solved | 3f5944a2bfb78f2ad7992c6224ef3c1099566fc8 | [
"MIT"
] | null | null | null | Arrays/Two Sum.cpp | nitishkalra/Coding-Problems-Solved | 3f5944a2bfb78f2ad7992c6224ef3c1099566fc8 | [
"MIT"
] | 1 | 2020-11-05T07:34:16.000Z | 2020-11-05T07:34:16.000Z | Leetcode - Two Sum
//Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
//You may assume that each input would have exactly one solution, and you may not use the same element twice.
//You can return the answer in any order.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hm;
vector<int> result;
for(int i=0;i<nums.size();i++){
hm[nums[i]] = i;
}
for(int i=0;i<nums.size();i++){
if(hm.find(target-nums[i])!=hm.end()){
if(hm[target-nums[i]]==i) continue;
result.push_back(i);
result.push_back(hm[target-nums[i]]);
break;
}
}
return result;
}
}; | 30.888889 | 123 | 0.567146 | nitishkalra |
829d673ae0e3c44c0ebdcc70919f77a3678ae37f | 3,488 | cpp | C++ | na/na06.cpp | tao-j/hw | f6723e703a950c2a8e930938d133a69fa816d72d | [
"Apache-2.0"
] | null | null | null | na/na06.cpp | tao-j/hw | f6723e703a950c2a8e930938d133a69fa816d72d | [
"Apache-2.0"
] | null | null | null | na/na06.cpp | tao-j/hw | f6723e703a950c2a8e930938d133a69fa816d72d | [
"Apache-2.0"
] | 1 | 2015-01-08T00:23:02.000Z | 2015-01-08T00:23:02.000Z | #include <stdio.h>
#define MAX_N 20
void Cubic_Spline(int n, double x[], double f[], int Type, double s0, double sn,
double a[], double b[], double c[], double d[]);
double S(double t, double Fmax,
int n, double x[], double a[], double b[], double c[], double d[]);
int main() {
freopen("in6.txt", "r", stdin);
int n, Type, m, i;
double x[MAX_N], f[MAX_N], a[MAX_N], b[MAX_N], c[MAX_N], d[MAX_N];
double s0, sn, Fmax, t0, tm, h, t;
while (scanf("%d", &n) != EOF) {
for (i = 0; i <= n; i++)
scanf("%lf", &x[i]);
for (i = 0; i <= n; i++)
scanf("%lf", &f[i]);
scanf("%d %lf %lf %lf", &Type, &s0, &sn, &Fmax);
Cubic_Spline(n, x, f, Type, s0, sn, a, b, c, d);
for (i = 1; i <= n; i++)
printf("%12.8e %12.8e %12.8e %12.8e \n", a[i], b[i], c[i], d[i]);
scanf("%lf %lf %d", &t0, &tm, &m);
h = (tm - t0) / (double)m;
for (i = 0; i <= m; i++) {
t = t0 + h*(double)i;
printf("f(%12.8e) = %12.8e\n", t, S(t, Fmax, n, x, a, b, c, d));
}
printf("\n");
}
return 0;
}
void Cubic_Spline(int n, double x[], double f[], int Type, double s0, double sn,
double a[], double b[], double c[], double d[]) {
double h[MAX_N + 1];
double alpha[MAX_N + 1], l[MAX_N + 1], miu[MAX_N + 1], z[MAX_N + 1];
double FPO = s0; double FPN = sn;
for (int i = 0; i <= n; ++i) a[i] = f[i]; //input
if (Type == 2) { //natural spline
for (int i = 0; i <= n - 1; ++i) h[i] = x[i + 1] - x[i]; //step1
for (int i = 1; i <= n - 1; ++i) alpha[i] = 3.0 * (a[i + 1] - a[i]) / h[i] - 3.0*(a[i] - a[i - 1]) / h[i - 1]; //step2
l[0] = 1; miu[0] = z[0] = 0; //step 3
for (int i = 1; i <= n - 1; ++i) {
l[i] = 2.0 * (x[i + 1] - x[i - 1]) - h[i - 1] * miu[i - 1];
miu[i] = h[i] / l[i];
z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / l[i];
} //step 4
l[n] = 1; z[n] = 0; c[n] = 0; //step 5
for (int j = n - 1; j >= 0; --j) {
c[j] = z[j] - miu[j] * c[j + 1];
b[j] = (a[j + 1] - a[j]) / h[j] - h[j] * (c[j + 1] + 2.0*c[j]) / 3.0;
d[j] = (c[j + 1] - c[j]) / 3.0 / h[j];
} // step 6
}
if (Type == 1) { //clamp
for (int i = 0; i <= n - 1; ++i) h[i] = x[i + 1] - x[i]; //step1
alpha[0] = 3.0 * (a[1] - a[0]) / h[0] - 3.0*FPO;
alpha[n] = 3.0*FPN - 3.0 *(a[n] - a[n - 1]) / h[n - 1]; //step 2
for (int i = 1; i <= n - 1; ++i) alpha[i] = 3.0 * (a[i + 1] - a[i]) / h[i] - 3.0*(a[i] - a[i - 1]) / h[i - 1]; //step 3
l[0] = 2.0*h[0]; miu[0] = 0.5; z[0] = alpha[0] / l[0]; //step 4
for (int i = 1; i <= n - 1; ++i) {
l[i] = 2.0 * (x[i + 1] - x[i - 1]) - h[i - 1] * miu[i - 1];
miu[i] = h[i] / l[i];
z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / l[i];
} //step 5
l[n] = h[n - 1] * (2.0 - miu[n - 1]); z[n] = (alpha[n] - h[n - 1] * z[n - 1]) / l[n]; c[n] = z[n]; //step 6
for (int j = n - 1; j >= 0; --j) {
c[j] = z[j] - miu[j] * c[j + 1];
b[j] = (a[j + 1] - a[j]) / h[j] - h[j] * (c[j + 1] + 2.0*c[j]) / 3.0;
d[j] = (c[j + 1] - c[j]) / 3.0 / h[j];
} // step 7
}
for (int i = n; i >= 0; i--) {
a[i + 1] = a[i];
b[i + 1] = b[i];
c[i + 1] = c[i];
d[i + 1] = d[i];
}
return;
}
double S(double t, double Fmax,
int n, double x[], double aa[], double bb[], double cc[], double dd[]) {
double *a = aa + 1;
double *b = bb + 1;
double *c = cc + 1;
double *d = dd + 1;
if (t < x[0] || t > x[n]) return Fmax;
for (int i = 0; i < n; i++) {
if (t == x[i]) return a[i];
if (t > x[i] && t < x[i + 1]) return a[i] + b[i] * (t - x[i]) + c[i] * (t - x[i])*(t - x[i]) + d[i] * (t - x[i])*(t - x[i])*(t - x[i]);
}
return a[n];
}
| 34.534653 | 137 | 0.416571 | tao-j |
82a2f97f7f86bd49726350724b83b2b0ac4beba9 | 4,188 | cc | C++ | tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/poplin/weights_transpose_chans_flip_xy.cc | DebeshJha/tensorflow-1 | 2b5a225c49d25273532d11c424d37ce394d7579a | [
"Apache-2.0"
] | 2 | 2021-03-08T23:32:06.000Z | 2022-01-13T03:43:49.000Z | tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/poplin/weights_transpose_chans_flip_xy.cc | DebeshJha/tensorflow-1 | 2b5a225c49d25273532d11c424d37ce394d7579a | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/poplin/weights_transpose_chans_flip_xy.cc | DebeshJha/tensorflow-1 | 2b5a225c49d25273532d11c424d37ce394d7579a | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/plugin/poplar/driver/tools/custom_ops/weights_transpose_chans_flip_xy.h"
#include "tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/poplar_ops.h"
#include "tensorflow/compiler/plugin/poplar/driver/tensor.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/conv_poplar_util.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
namespace xla {
namespace poplarplugin {
namespace {
class WeightsTransposeChansFlipXYOp : public PoplarOpDef {
StatusOr<poplar::program::Program> Creator(poplar::Graph& graph,
CompilerResources& res,
const HloInstruction* inst,
const xla::Shape& output_shape,
TensorMap& tensor_map) override {
poplar::program::Sequence seq;
TF_ASSIGN_OR_RETURN(poplar::Tensor in_weights,
FindInstructionInput(tensor_map, res, inst, 0, seq));
const HloWeightsTransposeChansFlipXYInstruction* weights_transpose_inst =
Cast<HloWeightsTransposeChansFlipXYInstruction>(inst);
const ConvolutionDimensionNumbers& conv_dimension_numbers =
weights_transpose_inst->convolution_dimension_numbers();
in_weights = ShuffleConvolutionWeightsToPoplar(conv_dimension_numbers,
in_weights, true);
const std::vector<size_t>& conv_input_shape =
weights_transpose_inst->ConvInputShape();
const std::vector<size_t>& conv_output_shape =
weights_transpose_inst->ConvOutputShape();
TF_ASSIGN_OR_RETURN(
poplin::ConvParams conv_params,
GetConvolutionParametersForWeightsTranspose(
weights_transpose_inst, conv_input_shape, conv_output_shape));
in_weights = AddGroupsDimensionToWeights(conv_params, in_weights, true);
const std::string debug_prefix = GetDebugName(inst);
auto func = [&graph, &res, conv_dimension_numbers, conv_params,
debug_prefix](std::vector<poplar::Tensor>& args,
poplar::program::Sequence& prog) {
poplar::Tensor in_weights_f = args[0];
poplar::Tensor out_weights_f = poplin::createWeights(
graph, conv_params, absl::StrCat(debug_prefix, "/CreateWeights"));
poplin::weightsTransposeChansFlipXY(
graph, in_weights_f, out_weights_f, prog,
absl::StrCat(debug_prefix, "/WeightsTransposeChansFlipXY"));
out_weights_f =
RemoveGroupsDimensionFromWeights(conv_params, out_weights_f);
out_weights_f = ShuffleConvolutionWeightsToTensorflow(
conv_dimension_numbers, out_weights_f);
args[1] = out_weights_f;
};
poplar::Tensor out_weights;
std::vector<poplar::Tensor> args = {in_weights, out_weights};
poputil::graphfn::Signature signature = {
poputil::graphfn::input(in_weights, "in_weights"),
poputil::graphfn::created("out_weights")};
TF_RETURN_IF_ERROR(res.graph_cache.ExecuteCached(
inst, graph, res, seq, func, signature, args,
weights_transpose_inst->AllocatingIndices(),
weights_transpose_inst->LayoutDependencies()));
out_weights = args[1];
TF_CHECK_OK(AddOutputTensor(tensor_map, inst, 0, out_weights));
return seq;
}
};
REGISTER_POPLAR_OP(WeightsTransposeChansFlipXY, WeightsTransposeChansFlipXYOp);
} // namespace
} // namespace poplarplugin
} // namespace xla
| 39.509434 | 102 | 0.686485 | DebeshJha |
82a40fe211c644ce226d10fea60de697bf874339 | 33,241 | cc | C++ | gnuradio-3.7.13.4/gnuradio-runtime/lib/hier_block2_detail.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | 1 | 2021-03-09T07:32:37.000Z | 2021-03-09T07:32:37.000Z | gnuradio-3.7.13.4/gnuradio-runtime/lib/hier_block2_detail.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | gnuradio-3.7.13.4/gnuradio-runtime/lib/hier_block2_detail.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | /* -*- c++ -*- */
/*
* Copyright 2006,2007,2009,2013 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "hier_block2_detail.h"
#include <gnuradio/io_signature.h>
#include <gnuradio/prefs.h>
#include <stdexcept>
#include <sstream>
#include <boost/format.hpp>
namespace gr {
#define HIER_BLOCK2_DETAIL_DEBUG 0
hier_block2_detail::hier_block2_detail(hier_block2 *owner)
: d_owner(owner),
d_parent_detail(0),
d_fg(make_flowgraph())
{
int min_inputs = owner->input_signature()->min_streams();
int max_inputs = owner->input_signature()->max_streams();
int min_outputs = owner->output_signature()->min_streams();
int max_outputs = owner->output_signature()->max_streams();
if(max_inputs == io_signature::IO_INFINITE ||
max_outputs == io_signature::IO_INFINITE ||
(min_inputs != max_inputs) ||(min_outputs != max_outputs) ) {
std::stringstream msg;
msg << "Hierarchical blocks do not yet support arbitrary or"
<< " variable numbers of inputs or outputs (" << d_owner->name() << ")";
throw std::runtime_error(msg.str());
}
d_inputs = std::vector<endpoint_vector_t>(max_inputs);
d_outputs = endpoint_vector_t(max_outputs);
d_max_output_buffer = std::vector<size_t>(std::max(max_outputs,1), 0);
d_min_output_buffer = std::vector<size_t>(std::max(max_outputs,1), 0);
}
hier_block2_detail::~hier_block2_detail()
{
d_owner = 0; // Don't use delete, we didn't allocate
}
void
hier_block2_detail::connect(basic_block_sptr block)
{
std::stringstream msg;
// Check if duplicate
if(std::find(d_blocks.begin(), d_blocks.end(), block) != d_blocks.end()) {
msg << "Block " << block << " already connected.";
throw std::invalid_argument(msg.str());
}
// Check if has inputs or outputs
if(block->input_signature()->max_streams() != 0 ||
block->output_signature()->max_streams() != 0) {
msg << "Block " << block << " must not have any input or output ports";
throw std::invalid_argument(msg.str());
}
hier_block2_sptr hblock(cast_to_hier_block2_sptr(block));
if(hblock && hblock.get() != d_owner) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "connect: block is hierarchical, setting parent to " << this << std::endl;
hblock->d_detail->d_parent_detail = this;
}
d_blocks.push_back(block);
}
void
hier_block2_detail::connect(basic_block_sptr src, int src_port,
basic_block_sptr dst, int dst_port)
{
std::stringstream msg;
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "connecting: " << endpoint(src, src_port)
<< " -> " << endpoint(dst, dst_port) << std::endl;
if(src.get() == dst.get())
throw std::invalid_argument("connect: src and destination blocks cannot be the same");
hier_block2_sptr src_block(cast_to_hier_block2_sptr(src));
hier_block2_sptr dst_block(cast_to_hier_block2_sptr(dst));
if(src_block && src.get() != d_owner) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "connect: src is hierarchical, setting parent to " << this << std::endl;
src_block->d_detail->d_parent_detail = this;
}
if(dst_block && dst.get() != d_owner) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "connect: dst is hierarchical, setting parent to " << this << std::endl;
dst_block->d_detail->d_parent_detail = this;
}
// Connections to block inputs or outputs
int max_port;
if(src.get() == d_owner) {
max_port = src->input_signature()->max_streams();
if((max_port != -1 && (src_port >= max_port)) || src_port < 0) {
msg << "source port " << src_port << " out of range for " << src;
throw std::invalid_argument(msg.str());
}
return connect_input(src_port, dst_port, dst);
}
if(dst.get() == d_owner) {
max_port = dst->output_signature()->max_streams();
if((max_port != -1 && (dst_port >= max_port)) || dst_port < 0) {
msg << "destination port " << dst_port << " out of range for " << dst;
throw std::invalid_argument(msg.str());
}
return connect_output(dst_port, src_port, src);
}
// Internal connections
d_fg->connect(src, src_port, dst, dst_port);
// TODO: connects to NC
}
void
hier_block2_detail::msg_connect(basic_block_sptr src, pmt::pmt_t srcport,
basic_block_sptr dst, pmt::pmt_t dstport)
{
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "connecting message port..." << std::endl;
// add block uniquely to list to internal blocks
if(std::find(d_blocks.begin(), d_blocks.end(), dst) == d_blocks.end()){
d_blocks.push_back(src);
d_blocks.push_back(dst);
}
bool hier_in=false, hier_out=false;
if(d_owner == src.get()){
hier_out = src->message_port_is_hier_in(srcport);
} else if (d_owner == dst.get()){
hier_in = dst->message_port_is_hier_out(dstport);;
} else {
hier_out = src->message_port_is_hier_out(srcport);
hier_in = dst->message_port_is_hier_in(dstport);
}
hier_block2_sptr src_block(cast_to_hier_block2_sptr(src));
hier_block2_sptr dst_block(cast_to_hier_block2_sptr(dst));
if(src_block && src.get() != d_owner) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "msg_connect: src is hierarchical, setting parent to " << this << std::endl;
src_block->d_detail->d_parent_detail = this;
}
if(dst_block && dst.get() != d_owner) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "msg_connect: dst is hierarchical, setting parent to " << this << std::endl;
dst_block->d_detail->d_parent_detail = this;
}
// add edge for this message connection
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << boost::format("msg_connect( (%s, %s, %d), (%s, %s, %d) )\n") % \
src % srcport % hier_out %
dst % dstport % hier_in;
d_fg->connect(msg_endpoint(src, srcport, hier_out), msg_endpoint(dst, dstport, hier_in));
}
void
hier_block2_detail::msg_disconnect(basic_block_sptr src, pmt::pmt_t srcport,
basic_block_sptr dst, pmt::pmt_t dstport)
{
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "disconnecting message port..." << std::endl;
// remove edge for this message connection
bool hier_in=false, hier_out=false;
if(d_owner == src.get()){
hier_out = src->message_port_is_hier_in(srcport);
} else if (d_owner == dst.get()){
hier_in = dst->message_port_is_hier_out(dstport);;
} else {
hier_out = src->message_port_is_hier_out(srcport);
hier_in = dst->message_port_is_hier_in(dstport);
}
d_fg->disconnect(msg_endpoint(src, srcport, hier_out), msg_endpoint(dst, dstport, hier_in));
hier_block2_sptr src_block(cast_to_hier_block2_sptr(src));
hier_block2_sptr dst_block(cast_to_hier_block2_sptr(dst));
if (src_block && src.get() != d_owner) {
// if the source is hier, we need to resolve the endpoint before calling unsub
msg_edge_vector_t edges = src_block->d_detail->d_fg->msg_edges();
for (msg_edge_viter_t it = edges.begin(); it != edges.end(); ++it) {
if ((*it).dst().block() == src) {
src = (*it).src().block();
srcport = (*it).src().port();
}
}
}
if (dst_block && dst.get() != d_owner) {
// if the destination is hier, we need to resolve the endpoint before calling unsub
msg_edge_vector_t edges = dst_block->d_detail->d_fg->msg_edges();
for (msg_edge_viter_t it = edges.begin(); it != edges.end(); ++it) {
if ((*it).src().block() == dst) {
dst = (*it).dst().block();
dstport = (*it).dst().port();
}
}
}
// unregister the subscription - if already subscribed
src->message_port_unsub(srcport, pmt::cons(dst->alias_pmt(), dstport));
}
void
hier_block2_detail::disconnect(basic_block_sptr block)
{
// Check on singleton list
for(basic_block_viter_t p = d_blocks.begin(); p != d_blocks.end(); p++) {
if(*p == block) {
d_blocks.erase(p);
hier_block2_sptr hblock(cast_to_hier_block2_sptr(block));
if(block && block.get() != d_owner) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "disconnect: block is hierarchical, clearing parent" << std::endl;
hblock->d_detail->d_parent_detail = 0;
}
return;
}
}
// Otherwise find all edges containing block
edge_vector_t edges, tmp = d_fg->edges();
edge_vector_t::iterator p;
for(p = tmp.begin(); p != tmp.end(); p++) {
if((*p).src().block() == block || (*p).dst().block() == block) {
edges.push_back(*p);
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "disconnect: block found in edge " << (*p) << std::endl;
}
}
if(edges.size() == 0) {
std::stringstream msg;
msg << "cannot disconnect block " << block << ", not found";
throw std::invalid_argument(msg.str());
}
for(p = edges.begin(); p != edges.end(); p++) {
disconnect((*p).src().block(), (*p).src().port(),
(*p).dst().block(), (*p).dst().port());
}
}
void
hier_block2_detail::disconnect(basic_block_sptr src, int src_port,
basic_block_sptr dst, int dst_port)
{
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "disconnecting: " << endpoint(src, src_port)
<< " -> " << endpoint(dst, dst_port) << std::endl;
if(src.get() == dst.get())
throw std::invalid_argument("disconnect: source and destination blocks cannot be the same");
hier_block2_sptr src_block(cast_to_hier_block2_sptr(src));
hier_block2_sptr dst_block(cast_to_hier_block2_sptr(dst));
if(src_block && src.get() != d_owner) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "disconnect: src is hierarchical, clearing parent" << std::endl;
src_block->d_detail->d_parent_detail = 0;
}
if(dst_block && dst.get() != d_owner) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "disconnect: dst is hierarchical, clearing parent" << std::endl;
dst_block->d_detail->d_parent_detail = 0;
}
if(src.get() == d_owner)
return disconnect_input(src_port, dst_port, dst);
if(dst.get() == d_owner)
return disconnect_output(dst_port, src_port, src);
// Internal connections
d_fg->disconnect(src, src_port, dst, dst_port);
}
void
hier_block2_detail::refresh_io_signature()
{
int min_inputs = d_owner->input_signature()->min_streams();
int max_inputs = d_owner->input_signature()->max_streams();
int min_outputs = d_owner->output_signature()->min_streams();
int max_outputs = d_owner->output_signature()->max_streams();
if(max_inputs == io_signature::IO_INFINITE ||
max_outputs == io_signature::IO_INFINITE ||
(min_inputs != max_inputs) ||(min_outputs != max_outputs) ) {
std::stringstream msg;
msg << "Hierarchical blocks do not yet support arbitrary or"
<< " variable numbers of inputs or outputs (" << d_owner->name() << ")";
throw std::runtime_error(msg.str());
}
// Check for # input change
if ((signed)d_inputs.size() != max_inputs)
{
d_inputs.resize(max_inputs);
}
// Check for # output change
if ((signed)d_outputs.size() != max_outputs)
{
d_outputs.resize(max_outputs);
d_min_output_buffer.resize(max_outputs, 0);
d_max_output_buffer.resize(max_outputs, 0);
}
}
void
hier_block2_detail::connect_input(int my_port, int port,
basic_block_sptr block)
{
std::stringstream msg;
refresh_io_signature();
if(my_port < 0 || my_port >= (signed)d_inputs.size()) {
msg << "input port " << my_port << " out of range for " << block;
throw std::invalid_argument(msg.str());
}
endpoint_vector_t &endps = d_inputs[my_port];
endpoint endp(block, port);
endpoint_viter_t p = std::find(endps.begin(), endps.end(), endp);
if(p != endps.end()) {
msg << "external input port " << my_port << " already wired to " << endp;
throw std::invalid_argument(msg.str());
}
endps.push_back(endp);
}
void
hier_block2_detail::connect_output(int my_port, int port,
basic_block_sptr block)
{
std::stringstream msg;
refresh_io_signature();
if(my_port < 0 || my_port >= (signed)d_outputs.size()) {
msg << "output port " << my_port << " out of range for " << block;
throw std::invalid_argument(msg.str());
}
if(d_outputs[my_port].block()) {
msg << "external output port " << my_port << " already connected from "
<< d_outputs[my_port];
throw std::invalid_argument(msg.str());
}
d_outputs[my_port] = endpoint(block, port);
}
void
hier_block2_detail::disconnect_input(int my_port, int port,
basic_block_sptr block)
{
std::stringstream msg;
refresh_io_signature();
if(my_port < 0 || my_port >= (signed)d_inputs.size()) {
msg << "input port number " << my_port << " out of range for " << block;
throw std::invalid_argument(msg.str());
}
endpoint_vector_t &endps = d_inputs[my_port];
endpoint endp(block, port);
endpoint_viter_t p = std::find(endps.begin(), endps.end(), endp);
if(p == endps.end()) {
msg << "external input port " << my_port << " not connected to " << endp;
throw std::invalid_argument(msg.str());
}
endps.erase(p);
}
void
hier_block2_detail::disconnect_output(int my_port, int port,
basic_block_sptr block)
{
std::stringstream msg;
refresh_io_signature();
if(my_port < 0 || my_port >= (signed)d_outputs.size()) {
msg << "output port number " << my_port << " out of range for " << block;
throw std::invalid_argument(msg.str());
}
if(d_outputs[my_port].block() != block) {
msg << "block " << block << " not assigned to output "
<< my_port << ", can't disconnect";
throw std::invalid_argument(msg.str());
}
d_outputs[my_port] = endpoint();
}
endpoint_vector_t
hier_block2_detail::resolve_port(int port, bool is_input)
{
std::stringstream msg;
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Resolving port " << port << " as an "
<< (is_input ? "input" : "output")
<< " of " << d_owner->name() << std::endl;
endpoint_vector_t result;
if(is_input) {
if(port < 0 || port >= (signed)d_inputs.size()) {
msg << "resolve_port: hierarchical block '" << d_owner->name()
<< "': input " << port << " is out of range";
throw std::runtime_error(msg.str());
}
if(d_inputs[port].empty()) {
msg << "resolve_port: hierarchical block '" << d_owner->name()
<< "': input " << port << " is not connected internally";
throw std::runtime_error(msg.str());
}
endpoint_vector_t &endps = d_inputs[port];
endpoint_viter_t p;
for(p = endps.begin(); p != endps.end(); p++) {
endpoint_vector_t tmp = resolve_endpoint(*p, true);
std::copy(tmp.begin(), tmp.end(), back_inserter(result));
}
}
else {
if(port < 0 || port >= (signed)d_outputs.size()) {
msg << "resolve_port: hierarchical block '" << d_owner->name()
<< "': output " << port << " is out of range";
throw std::runtime_error(msg.str());
}
if(d_outputs[port] == endpoint()) {
msg << "resolve_port: hierarchical block '" << d_owner->name()
<< "': output " << port << " is not connected internally";
throw std::runtime_error(msg.str());
}
result = resolve_endpoint(d_outputs[port], false);
}
if(result.empty()) {
msg << "resolve_port: hierarchical block '" << d_owner->name()
<< "': unable to resolve "
<< (is_input ? "input port " : "output port ")
<< port;
throw std::runtime_error(msg.str());
}
return result;
}
void
hier_block2_detail::disconnect_all()
{
d_fg->clear();
d_blocks.clear();
int max_inputs = d_owner->input_signature()->max_streams();
int max_outputs = d_owner->output_signature()->max_streams();
d_inputs = std::vector<endpoint_vector_t>(max_inputs);
d_outputs = endpoint_vector_t(max_outputs);
}
endpoint_vector_t
hier_block2_detail::resolve_endpoint(const endpoint &endp, bool is_input) const
{
std::stringstream msg;
endpoint_vector_t result;
// Check if endpoint is a leaf node
if(cast_to_block_sptr(endp.block())) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Block " << endp.block() << " is a leaf node, returning." << std::endl;
result.push_back(endp);
return result;
}
// Check if endpoint is a hierarchical block
hier_block2_sptr hier_block2(cast_to_hier_block2_sptr(endp.block()));
if(hier_block2) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Resolving endpoint " << endp << " as an "
<< (is_input ? "input" : "output")
<< ", recursing" << std::endl;
return hier_block2->d_detail->resolve_port(endp.port(), is_input);
}
msg << "unable to resolve" << (is_input ? " input " : " output ")
<< "endpoint " << endp;
throw std::runtime_error(msg.str());
}
void
hier_block2_detail::flatten_aux(flat_flowgraph_sptr sfg) const
{
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << " ** Flattening " << d_owner->name() << " parent: " << d_parent_detail << std::endl;
bool is_top_block = (d_parent_detail == NULL);
// Add my edges to the flow graph, resolving references to actual endpoints
edge_vector_t edges = d_fg->edges();
msg_edge_vector_t msg_edges = d_fg->msg_edges();
edge_viter_t p;
msg_edge_viter_t q,u;
// Only run setup_rpc if ControlPort config param is enabled.
bool ctrlport_on = prefs::singleton()->get_bool("ControlPort", "on", false);
int min_buff = 0;
int max_buff = 0;
// Determine how the buffers should be set
bool set_all_min_buff = d_owner->all_min_output_buffer_p();
bool set_all_max_buff = d_owner->all_max_output_buffer_p();
// Get the min and max buffer length
if(set_all_min_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Getting (" << (d_owner->alias()).c_str()
<< ") min buffer" << std::endl;
min_buff = d_owner->min_output_buffer();
}
if(set_all_max_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Getting (" << (d_owner->alias()).c_str()
<< ") max buffer" << std::endl;
max_buff = d_owner->max_output_buffer();
}
// For every block (gr::block and gr::hier_block2), set up the RPC
// interface.
for(p = edges.begin(); p != edges.end(); p++) {
basic_block_sptr b;
b = p->src().block();
if(set_all_min_buff){
//sets the min buff for every block within hier_block2
if(min_buff != 0){
block_sptr bb = boost::dynamic_pointer_cast<block>(b);
if(bb != 0){
if(bb->min_output_buffer(0) != min_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Block (" << (bb->alias()).c_str()
<< ") min_buff (" << min_buff
<< ")" << std::endl;
bb->set_min_output_buffer(min_buff);
}
}
else{
hier_block2_sptr hh = boost::dynamic_pointer_cast<hier_block2>(b);
if(hh != 0){
if(hh->min_output_buffer(0) != min_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "HBlock (" << (hh->alias()).c_str()
<< ") min_buff (" << min_buff
<< ")" << std::endl;
hh->set_min_output_buffer(min_buff);
}
}
}
}
}
if(set_all_max_buff){
//sets the max buff for every block within hier_block2
if(max_buff != 0){
block_sptr bb = boost::dynamic_pointer_cast<block>(b);
if(bb != 0){
if(bb->max_output_buffer(0) != max_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Block (" << (bb->alias()).c_str()
<< ") max_buff (" << max_buff
<< ")" << std::endl;
bb->set_max_output_buffer(max_buff);
}
}
else{
hier_block2_sptr hh = boost::dynamic_pointer_cast<hier_block2>(b);
if(hh != 0){
if(hh->max_output_buffer(0) != max_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "HBlock (" << (hh->alias()).c_str()
<< ") max_buff (" << max_buff
<< ")" << std::endl;
hh->set_max_output_buffer(max_buff);
}
}
}
}
}
b = p->dst().block();
if(set_all_min_buff){
//sets the min buff for every block within hier_block2
if(min_buff != 0){
block_sptr bb = boost::dynamic_pointer_cast<block>(b);
if(bb != 0){
if(bb->min_output_buffer(0) != min_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Block (" << (bb->alias()).c_str()
<< ") min_buff (" << min_buff
<< ")" << std::endl;
bb->set_min_output_buffer(min_buff);
}
}
else{
hier_block2_sptr hh = boost::dynamic_pointer_cast<hier_block2>(b);
if(hh != 0){
if(hh->min_output_buffer(0) != min_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "HBlock (" << (hh->alias()).c_str()
<< ") min_buff (" << min_buff
<< ")" << std::endl;
hh->set_min_output_buffer(min_buff);
}
}
}
}
}
if(set_all_max_buff){
//sets the max buff for every block within hier_block2
if(max_buff != 0){
block_sptr bb = boost::dynamic_pointer_cast<block>(b);
if(bb != 0){
if(bb->max_output_buffer(0) != max_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Block (" << (bb->alias()).c_str()
<< ") max_buff (" << max_buff
<< ")" << std::endl;
bb->set_max_output_buffer(max_buff);
}
}
else{
hier_block2_sptr hh = boost::dynamic_pointer_cast<hier_block2>(b);
if(hh != 0){
if(hh->max_output_buffer(0) != max_buff){
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "HBlock (" << (hh->alias()).c_str()
<< ") max_buff (" << max_buff
<< ")" << std::endl;
hh->set_max_output_buffer(max_buff);
}
}
}
}
}
}
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Flattening stream connections: " << std::endl;
for(p = edges.begin(); p != edges.end(); p++) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Flattening edge " << (*p) << std::endl;
endpoint_vector_t src_endps = resolve_endpoint(p->src(), false);
endpoint_vector_t dst_endps = resolve_endpoint(p->dst(), true);
endpoint_viter_t s, d;
for(s = src_endps.begin(); s != src_endps.end(); s++) {
for(d = dst_endps.begin(); d != dst_endps.end(); d++) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << (*s) << "->" << (*d) << std::endl;
sfg->connect(*s, *d);
}
}
}
// loop through flattening hierarchical connections
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Flattening msg connections: " << std::endl;
std::vector<std::pair<msg_endpoint, bool> > resolved_endpoints;
for(q = msg_edges.begin(); q != msg_edges.end(); q++) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << boost::format(" flattening edge ( %s, %s, %d) -> ( %s, %s, %d)\n") % \
q->src().block() % q->src().port() % q->src().is_hier() % q->dst().block() % \
q->dst().port() % q->dst().is_hier();
if(q->src().is_hier() && q->src().block().get() == d_owner){
// connection into this block ..
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "hier incoming port: " << q->src() << std::endl;
sfg->replace_endpoint(q->src(), q->dst(), false);
resolved_endpoints.push_back( std::pair<msg_endpoint,bool>( q->src(), false));
} else
if(q->dst().is_hier() && q->dst().block().get() == d_owner){
// connection out of this block
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "hier outgoing port: " << q->dst() << std::endl;
sfg->replace_endpoint(q->dst(), q->src(), true);
resolved_endpoints.push_back( std::pair<msg_endpoint,bool>(q->dst(), true));
} else {
// internal connection only
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "internal msg connection: " << q->src() << "-->" << q->dst() << std::endl;
sfg->connect( q->src(), q->dst() );
}
}
for(std::vector<std::pair<msg_endpoint, bool> >::iterator it = resolved_endpoints.begin();
it != resolved_endpoints.end(); it++) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "sfg->clear_endpoint(" << (*it).first << ", " << (*it).second << ") " << std::endl;
sfg->clear_endpoint((*it).first, (*it).second);
}
/*
// connect primitive edges in the new fg
for(q = msg_edges.begin(); q != msg_edges.end(); q++) {
if((!q->src().is_hier()) && (!q->dst().is_hier())) {
sfg->connect(q->src(), q->dst());
}
else {
std::cout << "not connecting hier connection!" << std::endl;
}
}
*/
// Construct unique list of blocks used either in edges, inputs,
// outputs, or by themselves. I still hate STL.
basic_block_vector_t blocks; // unique list of used blocks
basic_block_vector_t tmp = d_fg->calc_used_blocks();
// First add the list of singleton blocks
std::vector<basic_block_sptr>::const_iterator b; // Because flatten_aux is const
for(b = d_blocks.begin(); b != d_blocks.end(); b++) {
tmp.push_back(*b);
}
// Now add the list of connected input blocks
std::stringstream msg;
for(unsigned int i = 0; i < d_inputs.size(); i++) {
if(d_inputs[i].size() == 0) {
msg << "In hierarchical block " << d_owner->name() << ", input " << i
<< " is not connected internally";
throw std::runtime_error(msg.str());
}
for(unsigned int j = 0; j < d_inputs[i].size(); j++)
tmp.push_back(d_inputs[i][j].block());
}
for(unsigned int i = 0; i < d_outputs.size(); i++) {
basic_block_sptr blk = d_outputs[i].block();
if(!blk) {
msg << "In hierarchical block " << d_owner->name() << ", output " << i
<< " is not connected internally";
throw std::runtime_error(msg.str());
}
// Set the buffers of only the blocks connected to the hier output
if(!set_all_min_buff){
min_buff = d_owner->min_output_buffer(i);
if(min_buff != 0){
block_sptr bb = boost::dynamic_pointer_cast<block>(blk);
if(bb != 0){
int bb_src_port = d_outputs[i].port();
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Block (" << (bb->alias()).c_str()
<< ") Port (" << bb_src_port
<< ") min_buff (" << min_buff
<< ")" << std::endl;
bb->set_min_output_buffer(bb_src_port, min_buff);
}
else{
hier_block2_sptr hh = boost::dynamic_pointer_cast<hier_block2>(blk);
if(hh != 0){
int hh_src_port = d_outputs[i].port();
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "HBlock (" << (hh->alias()).c_str()
<< ") Port (" << hh_src_port
<< ") min_buff ("<< min_buff
<< ")" << std::endl;
hh->set_min_output_buffer(hh_src_port, min_buff);
}
}
}
}
if(!set_all_max_buff){
max_buff = d_owner->max_output_buffer(i);
if(max_buff != 0){
block_sptr bb = boost::dynamic_pointer_cast<block>(blk);
if(bb != 0){
int bb_src_port = d_outputs[i].port();
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "Block (" << (bb->alias()).c_str()
<< ") Port (" << bb_src_port
<< ") max_buff (" << max_buff
<< ")" << std::endl;
bb->set_max_output_buffer(bb_src_port, max_buff);
}
else{
hier_block2_sptr hh = boost::dynamic_pointer_cast<hier_block2>(blk);
if(hh != 0){
int hh_src_port = d_outputs[i].port();
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "HBlock (" << (hh->alias()).c_str()
<< ") Port (" << hh_src_port
<< ") max_buff (" << max_buff
<< ")" << std::endl;
hh->set_max_output_buffer(hh_src_port, max_buff);
}
}
}
}
tmp.push_back(blk);
}
sort(tmp.begin(), tmp.end());
std::insert_iterator<basic_block_vector_t> inserter(blocks, blocks.begin());
unique_copy(tmp.begin(), tmp.end(), inserter);
// Recurse hierarchical children
for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) {
hier_block2_sptr hier_block2(cast_to_hier_block2_sptr(*p));
if(hier_block2 && (hier_block2.get() != d_owner)) {
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "flatten_aux: recursing into hierarchical block "
<< hier_block2->alias() << std::endl;
hier_block2->d_detail->flatten_aux(sfg);
}
}
// prune any remaining hier connections
// if they were not replaced with hier internal connections while in sub-calls
// they must remain unconnected and can be deleted...
if(is_top_block){
sfg->clear_hier();
}
// print all primitive connections at exit
if(HIER_BLOCK2_DETAIL_DEBUG && is_top_block){
std::cout << "flatten_aux finished in top_block" << std::endl;
sfg->dump();
}
// if ctrlport is enabled, call setup RPC for all blocks in the flowgraph
if(ctrlport_on) {
for(b = blocks.begin(); b != blocks.end(); b++) {
if(!(*b)->is_rpc_set()) {
(*b)->setup_rpc();
(*b)->rpc_set();
}
}
}
}
void
hier_block2_detail::lock()
{
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "lock: entered in " << this << std::endl;
if(d_parent_detail)
d_parent_detail->lock();
else
d_owner->lock();
}
void
hier_block2_detail::unlock()
{
if(HIER_BLOCK2_DETAIL_DEBUG)
std::cout << "unlock: entered in " << this << std::endl;
if(d_parent_detail)
d_parent_detail->unlock();
else
d_owner->unlock();
}
void
hier_block2_detail::set_processor_affinity(const std::vector<int> &mask)
{
basic_block_vector_t tmp = d_fg->calc_used_blocks();
for(basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) {
(*p)->set_processor_affinity(mask);
}
}
void
hier_block2_detail::unset_processor_affinity()
{
basic_block_vector_t tmp = d_fg->calc_used_blocks();
for(basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) {
(*p)->unset_processor_affinity();
}
}
std::vector<int>
hier_block2_detail::processor_affinity()
{
basic_block_vector_t tmp = d_fg->calc_used_blocks();
return tmp[0]->processor_affinity();
}
} /* namespace gr */
| 34.662148 | 104 | 0.572004 | v1259397 |
82a4be72e1d357e8362128381c9a8ff01eed5ac3 | 5,081 | hpp | C++ | include/my_async/udp_client/impl/client_base_impl.hpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | include/my_async/udp_client/impl/client_base_impl.hpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | include/my_async/udp_client/impl/client_base_impl.hpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | 1 | 2021-03-10T13:02:13.000Z | 2021-03-10T13:02:13.000Z | #ifndef UDP_CLIENT_BASE_SESSION_IMPL_HPP__
#define UDP_CLIENT_BASE_SESSION_IMPL_HPP__
#include "../client_base.hpp"
using boost::asio::ip::udp;
namespace My_Async{
namespace UDP{
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
Client_Base(boost::asio::io_context& ioc, const udp::endpoint& ep)
: socket_(ioc, ep){}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
Client_Base(boost::asio::io_context& ioc)
: socket_(ioc, udp::endpoint(udp::v4(), 0)){}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
Client_Base(boost::asio::io_context& ioc, unsigned short port)
: socket_(ioc, udp::endpoint(udp::v4(), port)){}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
open(udp::endpoint const& endpoint) noexcept
{
endpoint_ = endpoint;
on_open();
do_read();
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
write(std::shared_ptr<OutContainer const> data) noexcept
{
boost::asio::post(
socket_.get_executor(),
std::bind(
&self_type::writing,
derived().shared_from_this(),
data)
);
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
write(OutContainer const data) noexcept
{
write(std::make_shared<OutContainer const>(std::move(data)));
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
close(boost::system::error_code& ec) noexcept
{
socket_.close(ec);
on_close(ec);
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
udp::endpoint
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
endpoint() const
{
return endpoint_;
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
udp::endpoint
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
local_endpoint() const
{
return socket_.local_endpoint();
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
fail(boost::system::error_code ec, char const* what) noexcept
{
if(ec == boost::asio::error::operation_aborted ||
ec == boost::asio::error::bad_descriptor)
return;
on_error(ec, what);
close(ec);
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
do_read() noexcept
{
socket_.async_receive_from(
boost::asio::dynamic_buffer(buffer_).prepare(ReadBufferSize),
endpoint_,
std::bind(
&self_type::on_read,
derived().shared_from_this(),
std::placeholders::_1, //error_code
std::placeholders::_2 //bytes transfered
)
);
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
on_read(boost::system::error_code ec, std::size_t bytes_transfered) noexcept
{
if(ec)
return fail(ec, "read");
buffer_.resize(bytes_transfered);
read_handler(buffer_);
buffer_.erase(buffer_.begin(), buffer_.end());
do_read();
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
writing(std::shared_ptr<OutContainer const> const data) noexcept
{
queue_.push_back(data);
if(queue_.size() > 1) return;
do_write();
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
do_write() noexcept{
socket_.async_send_to(
boost::asio::buffer(*queue_.front()),
endpoint_,
std::bind(
&self_type::on_write,
derived().shared_from_this(),
std::placeholders::_1,
std::placeholders::_2
)
);
}
template<typename Derived,
typename InContainer,
typename OutContainer,
std::size_t ReadBufferSize>
void
Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>::
on_write(boost::system::error_code ec, std::size_t) noexcept
{
if(ec)
return fail(ec, "write");
queue_.erase(queue_.begin());
if(! queue_.empty())
do_write();
}
}//UDP
}//My_Async
#endif /* UDP_CLIENT_BASE_SESSION_IMPL_HPP__ */
| 23.095455 | 76 | 0.758906 | rnascunha |
82a5256542dd6d2a2fa6fc2596ef857ba1c64171 | 756 | hpp | C++ | c++/include/celerite2/utils.hpp | jacksonloper/celerite2 | e413e28dc43ba33e67960b51a9cbbac43c2f58df | [
"MIT"
] | 38 | 2020-10-10T02:43:53.000Z | 2022-03-30T09:59:21.000Z | c++/include/celerite2/utils.hpp | jacksonloper/celerite2 | e413e28dc43ba33e67960b51a9cbbac43c2f58df | [
"MIT"
] | 34 | 2020-10-06T18:50:47.000Z | 2022-01-28T10:33:04.000Z | c++/include/celerite2/utils.hpp | jacksonloper/celerite2 | e413e28dc43ba33e67960b51a9cbbac43c2f58df | [
"MIT"
] | 6 | 2020-11-09T18:12:54.000Z | 2022-02-03T20:20:59.000Z | #ifndef _CELERITE2_UTILS_HPP_DEFINED_
#define _CELERITE2_UTILS_HPP_DEFINED_
#include <Eigen/Core>
#include <cassert>
namespace celerite2 {
namespace utils {
#define ASSERT_SAME_OR_DYNAMIC(VAL, J) assert((VAL == Eigen::Dynamic) || (VAL == J))
// adapted from https://academy.realm.io/posts/how-we-beat-cpp-stl-binary-search/
template <typename T>
inline int search_sorted(const Eigen::MatrixBase<T> &x, const typename T::Scalar &value) {
const int N = x.rows();
int low = -1, high = N;
while (high - low > 1) {
int probe = (low + high) / 2;
auto v = x(probe);
if (v > value)
high = probe;
else
low = probe;
}
return high;
}
} // namespace utils
} // namespace celerite2
#endif // _CELERITE2_UTILS_HPP_DEFINED_
| 23.625 | 90 | 0.671958 | jacksonloper |