text
stringlengths 5
1.04M
|
|---|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2018, Mohamad Ayman.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * The name of Mohamad Ayman may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Mohamad Ayman */
// SA
#include "ros_controllers_widget.h"
#include <moveit_msgs/JointLimits.h>
// Qt
#include <QFormLayout>
#include <QMessageBox>
#include <QDoubleValidator>
#include <QTreeWidgetItem>
#include <QApplication>
#include <regex>
#include <moveit/robot_state/conversions.h>
namespace moveit_setup_assistant
{
// ******************************************************************************************
// Outer User Interface for MoveIt Configuration Assistant
// ******************************************************************************************
ROSControllersWidget::ROSControllersWidget(QWidget* parent, const MoveItConfigDataPtr& config_data)
: SetupScreenWidget(parent), config_data_(config_data)
{
// Basic widget container
QVBoxLayout* layout = new QVBoxLayout();
layout->setAlignment(Qt::AlignTop);
// Title
this->setWindowTitle("ROS Control Controllers"); // title of window
// Top Header Area ------------------------------------------------
moveit_setup_assistant::HeaderWidget* header = new moveit_setup_assistant::HeaderWidget(
"Setup ROS Controllers", "Configure MoveIt to work with ROS Control to control the robot's physical hardware",
this);
layout->addWidget(header);
// Tree Box ----------------------------------------------------------------------
controllers_tree_widget_ = createContentsWidget();
// Joints edit widget
joints_widget_ = new moveit_setup_assistant::DoubleListWidget(this, config_data_, "Joint Collection", "Joint");
connect(joints_widget_, SIGNAL(cancelEditing()), this, SLOT(cancelEditing()));
connect(joints_widget_, SIGNAL(doneEditing()), this, SLOT(saveJointsScreen()));
connect(joints_widget_, SIGNAL(previewSelected(std::vector<std::string>)), this,
SLOT(previewSelectedJoints(std::vector<std::string>)));
// Joints Groups Widget
joint_groups_widget_ =
new moveit_setup_assistant::DoubleListWidget(this, config_data_, "Group Joints Collection", "Group");
connect(joint_groups_widget_, SIGNAL(cancelEditing()), this, SLOT(cancelEditing()));
connect(joint_groups_widget_, SIGNAL(doneEditing()), this, SLOT(saveJointsGroupsScreen()));
connect(joint_groups_widget_, SIGNAL(previewSelected(std::vector<std::string>)), this,
SLOT(previewSelectedGroup(std::vector<std::string>)));
// Controller Edit Widget
controller_edit_widget_ = new ControllerEditWidget(this, config_data_);
connect(controller_edit_widget_, SIGNAL(cancelEditing()), this, SLOT(cancelEditing()));
connect(controller_edit_widget_, SIGNAL(deleteController()), this, SLOT(deleteController()));
connect(controller_edit_widget_, SIGNAL(save()), this, SLOT(saveControllerScreenEdit()));
connect(controller_edit_widget_, SIGNAL(saveJoints()), this, SLOT(saveControllerScreenJoints()));
connect(controller_edit_widget_, SIGNAL(saveJointsGroups()), this, SLOT(saveControllerScreenGroups()));
// Combine into stack
stacked_layout_ = new QStackedLayout(this);
stacked_layout_->addWidget(controllers_tree_widget_); // screen index 0
stacked_layout_->addWidget(joints_widget_); // screen index 1
stacked_layout_->addWidget(controller_edit_widget_); // screen index 2
stacked_layout_->addWidget(joint_groups_widget_); // screen index 3
// Finish GUI -----------------------------------------------------------
// Create Widget wrapper for layout
QWidget* stacked_layout_widget = new QWidget(this);
stacked_layout_widget->setLayout(stacked_layout_);
layout->addWidget(stacked_layout_widget);
this->setLayout(layout);
}
// ******************************************************************************************
// Create the main tree view widget
// ******************************************************************************************
QWidget* ROSControllersWidget::createContentsWidget()
{
// Main widget
QWidget* content_widget = new QWidget(this);
// Basic widget container
QVBoxLayout* layout = new QVBoxLayout(this);
QHBoxLayout* upper_controls_layout = new QHBoxLayout();
// Add default controller
QPushButton* btn_add_default =
new QPushButton("Auto Add &FollowJointsTrajectory \n Controllers For Each Planning Group", this);
btn_add_default->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
btn_add_default->setMaximumWidth(600);
connect(btn_add_default, SIGNAL(clicked()), this, SLOT(addDefaultControllers()));
upper_controls_layout->addWidget(btn_add_default);
upper_controls_layout->setAlignment(btn_add_default, Qt::AlignLeft);
// Add Controls to layout
layout->addLayout(upper_controls_layout);
// Tree Box ----------------------------------------------------------------------
controllers_tree_ = new QTreeWidget(this);
controllers_tree_->setColumnCount(2);
QStringList labels;
labels << "Controller"
<< "Controller Type";
controllers_tree_->setHeaderLabels(labels);
controllers_tree_->setColumnWidth(0, 250);
connect(controllers_tree_, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(editSelected()));
connect(controllers_tree_, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this,
SLOT(previewSelected(QTreeWidgetItem*, int)));
connect(controllers_tree_, SIGNAL(itemSelectionChanged()), this, SLOT(itemSelectionChanged()));
layout->addWidget(controllers_tree_);
// Bottom Controls -------------------------------------------------------------
controls_layout_ = new QHBoxLayout();
// Expand/Contract controls
QLabel* expand_controls = new QLabel(this);
expand_controls->setText("<a href='expand'>Expand All</a> <a href='contract'>Collapse All</a>");
connect(expand_controls, SIGNAL(linkActivated(const QString)), this, SLOT(alterTree(const QString)));
controls_layout_->addWidget(expand_controls);
// Spacer
QWidget* spacer = new QWidget(this);
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
controls_layout_->addWidget(spacer);
// Delete
btn_delete_ = new QPushButton("&Delete Controller", this);
btn_delete_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
btn_delete_->setMaximumWidth(200);
connect(btn_delete_, SIGNAL(clicked()), this, SLOT(deleteController()));
controls_layout_->addWidget(btn_delete_);
controls_layout_->setAlignment(btn_delete_, Qt::AlignRight);
// Add Controller Button
btn_add_ = new QPushButton("&Add Controller", this);
btn_add_->setMaximumWidth(300);
connect(btn_add_, SIGNAL(clicked()), this, SLOT(addController()));
controls_layout_->addWidget(btn_add_);
controls_layout_->setAlignment(btn_add_, Qt::AlignRight);
// Edit
btn_edit_ = new QPushButton("&Edit Selected", this);
btn_edit_->setMaximumWidth(300);
connect(btn_edit_, SIGNAL(clicked()), this, SLOT(editSelected()));
controls_layout_->addWidget(btn_edit_);
controls_layout_->setAlignment(btn_edit_, Qt::AlignRight);
// Add Controls to layout
layout->addLayout(controls_layout_);
// Set layout
content_widget->setLayout(layout);
return content_widget;
}
// ******************************************************************************************
// Displays data in the ros_controllers_config_ data structure into a QtTableWidget
// ******************************************************************************************
void ROSControllersWidget::loadControllersTree()
{
// Disable Tree
controllers_tree_->setUpdatesEnabled(false); // prevent table from updating until we are completely done
controllers_tree_->setDisabled(true); // make sure we disable it so that the cellChanged event is not called
controllers_tree_->clear(); // reset the tree
// Display all controllers by looping through them
for (ROSControlConfig& controller : config_data_->getROSControllers())
{
loadToControllersTree(controller);
}
// Reenable Tree
controllers_tree_->setUpdatesEnabled(true); // prevent table from updating until we are completely done
controllers_tree_->setDisabled(false); // make sure we disable it so that the cellChanged event is not called
current_edit_controller_.clear(); // no controller is being edited
alterTree("expand");
}
// ******************************************************************************************
// Displays data in the controller_config_ data structure into a QtTableWidget
// ******************************************************************************************
void ROSControllersWidget::loadToControllersTree(const moveit_setup_assistant::ROSControlConfig& controller_it)
{
// Fonts for tree
const QFont top_level_font(QFont().defaultFamily(), 11, QFont::Bold);
const QFont type_font(QFont().defaultFamily(), 11, QFont::Normal, QFont::StyleItalic);
QTreeWidgetItem* controller;
controller = new QTreeWidgetItem();
// First column
controller->setText(0, controller_it.name_.c_str());
controller->setFont(0, top_level_font);
controller->setData(0, Qt::UserRole, QVariant::fromValue(0));
// Second column
controller->setText(1, controller_it.type_.c_str());
controller->setFont(1, type_font);
controller->setData(1, Qt::UserRole, QVariant::fromValue(4));
controllers_tree_->addTopLevelItem(controller);
if (!controller_it.joints_.empty())
{
// Joints --------------------------------------------------------------
QTreeWidgetItem* joints = new QTreeWidgetItem(controller);
joints->setText(0, "Joints");
joints->setFont(0, type_font);
joints->setData(0, Qt::UserRole, QVariant::fromValue(1));
controller->addChild(joints);
// Loop through all available joints
for (const std::string& joint : controller_it.joints_)
{
QTreeWidgetItem* joint_item = new QTreeWidgetItem(joints);
joint_item->setData(0, Qt::UserRole, QVariant::fromValue(2));
// Add to tree
joint_item->setText(0, joint.c_str());
joints->addChild(joint_item);
}
}
}
// ******************************************************************************************
// Called when setup assistant navigation switches to this screen
// ******************************************************************************************
void ROSControllersWidget::focusGiven()
{
// load controllers tree
btn_edit_->setEnabled(false);
btn_delete_->setEnabled(false);
loadControllersTree();
}
// ******************************************************************************************
// Load the popup screen with correct data for joints
// ******************************************************************************************
void ROSControllersWidget::loadJointsScreen(moveit_setup_assistant::ROSControlConfig* this_controller)
{
// Retrieve pointer to the shared kinematic model
const moveit::core::RobotModelConstPtr& model = config_data_->getRobotModel();
// Get the names of the all joints
const std::vector<std::string>& joints = model->getJointModelNames();
if (joints.empty())
{
QMessageBox::critical(this, "Error Loading", "No joints found for robot model");
return;
}
// Set the available joints (left box)
joints_widget_->setAvailable(joints);
// Set the selected joints (right box)
joints_widget_->setSelected(this_controller->joints_);
// Set the title
joints_widget_->title_->setText(
QString("Edit '").append(QString::fromUtf8(this_controller->name_.c_str())).append("' Joint Collection"));
// Remember what is currently being edited so we can later save changes
current_edit_controller_ = this_controller->name_;
}
// ******************************************************************************************
// Load the popup screen with correct data for gcroups
// ******************************************************************************************
void ROSControllersWidget::loadGroupsScreen(moveit_setup_assistant::ROSControlConfig* this_controller)
{
// Load all groups into the subgroup screen
std::vector<std::string> groups;
// Display all groups by looping through them
for (const srdf::Model::Group& group : config_data_->srdf_->srdf_model_->getGroups())
{
// Add to available groups list
groups.push_back(group.name_);
}
// Set the available groups (left box)
joint_groups_widget_->setAvailable(groups);
// Set the selected groups (right box)
joint_groups_widget_->setSelected(this_controller->joints_);
// Set the title
joint_groups_widget_->title_->setText(
QString("Edit '").append(QString::fromUtf8(this_controller->name_.c_str())).append("' Joints groups collection"));
// Remember what is currently being edited so we can later save changes
current_edit_controller_ = this_controller->name_;
}
// ******************************************************************************************
// Delete a controller
// ******************************************************************************************
void ROSControllersWidget::deleteController()
{
std::string controller_name = current_edit_controller_;
if (controller_name.empty())
{
QTreeWidgetItem* item = controllers_tree_->currentItem();
// Check that something was actually selected
if (item == nullptr)
return;
// Get the user custom properties of the currently selected row
int type = item->data(0, Qt::UserRole).value<int>();
if (type == 0)
controller_name = item->text(0).toUtf8().constData();
}
// Confirm user wants to delete controller
if (QMessageBox::question(
this, "Confirm Controller Deletion",
QString("Are you sure you want to delete the controller '").append(controller_name.c_str()).append(" ?"),
QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel)
{
return;
}
// Delete actual controller
if (config_data_->deleteROSController(controller_name))
{
ROS_INFO_STREAM_NAMED("Setup Assistant", "Controller " << controller_name << " deleted succefully");
}
else
{
ROS_WARN_STREAM_NAMED("Setup Assistant", "Couldn't delete Controller " << controller_name);
}
current_edit_controller_.clear();
// Switch to main screen
showMainScreen();
// Reload main screen table
loadControllersTree();
}
// ******************************************************************************************
// Create a new controller
// ******************************************************************************************
void ROSControllersWidget::addController()
{
// New Controller
adding_new_controller_ = true;
// Load the data
loadControllerScreen(nullptr); // NULL indicates this is a new controller, not an existing one
changeScreen(2); // 1 is index of controller edit
}
// ******************************************************************************************
// Add a Follow Joint Trajectory action Controller for each Planning Group
// ******************************************************************************************
void ROSControllersWidget::addDefaultControllers()
{
if (!config_data_->addDefaultControllers())
QMessageBox::warning(this, "Error adding contollers", "No Planning Groups configured!");
loadControllersTree();
}
// ******************************************************************************************
// Load the popup screen with correct data for controllers
// ******************************************************************************************
void ROSControllersWidget::loadControllerScreen(moveit_setup_assistant::ROSControlConfig* this_controller)
{
// Load the avail controllers. This function only runs once
controller_edit_widget_->loadControllersTypesComboBox();
if (this_controller == nullptr) // this is a new screen
{
current_edit_controller_.clear(); // provide a blank controller name
controller_edit_widget_->setTitle("Create New Controller");
controller_edit_widget_->hideDelete();
controller_edit_widget_->showNewButtonsWidget(); // helps user choose next step
controller_edit_widget_->showSave(); // this is only for edit mode
}
else // load the controller name into the widget
{
current_edit_controller_ = this_controller->name_;
controller_edit_widget_->setTitle(
QString("Edit Controller '").append(current_edit_controller_.c_str()).append("'"));
controller_edit_widget_->showDelete();
controller_edit_widget_->hideNewButtonsWidget(); // not necessary for existing controllers
controller_edit_widget_->showSave(); // this is only for edit mode
}
// Set the data in the edit box
controller_edit_widget_->setSelected(current_edit_controller_);
}
// ******************************************************************************************
// Call when edit screen is canceled
// ******************************************************************************************
void ROSControllersWidget::cancelEditing()
{
if (!current_edit_controller_.empty() && adding_new_controller_)
{
moveit_setup_assistant::ROSControlConfig* editing = config_data_->findROSControllerByName(current_edit_controller_);
if (editing && editing->joints_.empty())
{
config_data_->deleteROSController(current_edit_controller_);
current_edit_controller_.clear();
// Load the data to the tree
loadControllersTree();
}
}
else
{
current_edit_controller_.clear();
}
// Switch to main screen
showMainScreen();
}
// ******************************************************************************************
// Called from Double List widget to highlight joints
// ******************************************************************************************
void ROSControllersWidget::previewSelectedJoints(const std::vector<std::string>& joints)
{
// Unhighlight all links
Q_EMIT unhighlightAll();
for (const std::string& joint : joints)
{
const moveit::core::JointModel* joint_model = config_data_->getRobotModel()->getJointModel(joint);
// Check that a joint model was found
if (!joint_model)
{
continue;
}
// Get the name of the link
const std::string link = joint_model->getChildLinkModel()->getName();
if (link.empty())
{
continue;
}
// Highlight link
Q_EMIT highlightLink(link, QColor(255, 0, 0));
}
}
// ******************************************************************************************
// Called from Double List widget to highlight a group
// ******************************************************************************************
void ROSControllersWidget::previewSelectedGroup(const std::vector<std::string>& groups)
{
// Unhighlight all links
Q_EMIT unhighlightAll();
for (const std::string& group : groups)
{
// Highlight group
Q_EMIT highlightGroup(group);
}
}
// ******************************************************************************************
// Called when an item is seleceted from the controllers tree
// ******************************************************************************************
void ROSControllersWidget::previewSelected(QTreeWidgetItem* selected_item, int /*column*/)
{
// Get the user custom properties of the currently selected row
int type = selected_item->data(0, Qt::UserRole).value<int>();
btn_edit_->setEnabled(true);
// Enable delete button if a controller was selected
if (type == 0)
{
btn_delete_->setEnabled(true);
}
else
{
btn_delete_->setEnabled(false);
}
}
// ******************************************************************************************
// Call when a new controller is created and ready to progress to next screen
// ******************************************************************************************
void ROSControllersWidget::saveControllerScreenJoints()
{
// Save the controller
if (!saveControllerScreen())
return;
// Find the controller we are editing based on the controller name string
moveit_setup_assistant::ROSControlConfig* editing_controller =
config_data_->findROSControllerByName(current_edit_controller_);
loadJointsScreen(editing_controller);
// Switch to screen
changeScreen(1); // 1 is index of joints
}
// ******************************************************************************************
// Call when a new controller is created and ready to progress to next screen
// ******************************************************************************************
void ROSControllersWidget::saveControllerScreenGroups()
{
// Save the controller
if (!saveControllerScreen())
return;
// Find the controller we are editing based on the controller name string
moveit_setup_assistant::ROSControlConfig* editing_controller =
config_data_->findROSControllerByName(current_edit_controller_);
loadGroupsScreen(editing_controller);
// Switch to screen
changeScreen(3); // 3 is index of groups
}
// ******************************************************************************************
// Call when joints edit sceen is done and needs to be saved
// ******************************************************************************************
void ROSControllersWidget::saveJointsScreen()
{
// Find the controller we are editing based on the controller name string
moveit_setup_assistant::ROSControlConfig* searched_controller =
config_data_->findROSControllerByName(current_edit_controller_);
// Clear the old data
searched_controller->joints_.clear();
// Copy the data
for (int i = 0; i < joints_widget_->selected_data_table_->rowCount(); ++i)
{
searched_controller->joints_.push_back(joints_widget_->selected_data_table_->item(i, 0)->text().toStdString());
}
// Switch to main screen
showMainScreen();
// Reload main screen table
loadControllersTree();
}
// ******************************************************************************************
// Call when joints edit sceen is done and needs to be saved
// ******************************************************************************************
void ROSControllersWidget::saveJointsGroupsScreen()
{
// Find the controller we are editing based on the controller name string
moveit_setup_assistant::ROSControlConfig* searched_controller =
config_data_->findROSControllerByName(current_edit_controller_);
// Clear the old data
searched_controller->joints_.clear();
// Copy the data
for (int i = 0; i < joint_groups_widget_->selected_data_table_->rowCount(); ++i)
{
// Get list of associated joints
const moveit::core::JointModelGroup* joint_model_group = config_data_->getRobotModel()->getJointModelGroup(
joint_groups_widget_->selected_data_table_->item(i, 0)->text().toStdString());
const std::vector<const moveit::core::JointModel*>& joint_models = joint_model_group->getActiveJointModels();
// Iterate through the joints
for (const moveit::core::JointModel* joint : joint_models)
{
if (joint->isPassive() || joint->getMimic() != nullptr || joint->getType() == moveit::core::JointModel::FIXED)
continue;
searched_controller->joints_.push_back(joint->getName());
}
}
// Switch to main screen
showMainScreen();
// Reload main screen table
loadControllersTree();
}
// ******************************************************************************************
// Call when joints edit sceen is done and needs to be saved
// ******************************************************************************************
void ROSControllersWidget::saveControllerScreenEdit()
{
// Save the controller
if (!saveControllerScreen())
return;
// Switch to main screen
showMainScreen();
}
// ******************************************************************************************
// Call when controller edit sceen is done and needs to be saved
// ******************************************************************************************
bool ROSControllersWidget::saveControllerScreen()
{
// Get a reference to the supplied strings
const std::string& controller_name = controller_edit_widget_->getControllerName();
const std::string& controller_type = controller_edit_widget_->getControllerType();
// Used for editing existing controllers
moveit_setup_assistant::ROSControlConfig* searched_controller = nullptr;
std::smatch invalid_name_match;
std::regex invalid_reg_ex("[^a-z|^1-9|^_]");
// Check that a valid controller name has been given
if (controller_name.empty() || std::regex_search(controller_name, invalid_name_match, invalid_reg_ex))
{
QMessageBox::warning(this, "Error Saving", "Invalid ROS controller name");
return false;
}
// Check if this is an existing controller
if (!current_edit_controller_.empty())
{
// Find the controller we are editing based on the goup name string
searched_controller = config_data_->findROSControllerByName(current_edit_controller_);
}
// Check that the controller name is unique
for (const auto& controller : config_data_->getROSControllers())
{
if (controller.name_.compare(controller_name) == 0) // the names are the same
{
// is this our existing controller? check if controller pointers are same
if (&controller != searched_controller)
{
QMessageBox::warning(this, "Error Saving", "A controller already exists with that name!");
return false;
}
}
}
adding_new_controller_ = false;
// Save the new controller name or create the new controller
if (searched_controller == nullptr) // create new
{
moveit_setup_assistant::ROSControlConfig new_controller;
new_controller.name_ = controller_name;
new_controller.type_ = controller_type;
config_data_->addROSController(new_controller);
adding_new_controller_ = true; // remember this controller is new
}
else
{
// Remember old controller name and type
const std::string old_controller_name = searched_controller->name_;
// Change controller name
searched_controller->name_ = controller_name;
searched_controller->type_ = controller_type;
}
// Reload main screen table
loadControllersTree();
// Update the current edit controller so that we can proceed to the next screen, if user desires
current_edit_controller_ = controller_name;
return true;
}
// ******************************************************************************************
// Edit whenever element is selected in the controllers tree view
// ******************************************************************************************
void ROSControllersWidget::editSelected()
{
QTreeWidgetItem* item = controllers_tree_->currentItem();
QTreeWidgetItem* controller_item;
// Check that something was actually selected
if (item == nullptr)
return;
adding_new_controller_ = false;
// Get the user custom properties of the currently selected row
int type = item->data(0, Qt::UserRole).value<int>();
if (type == 2)
{
// The controller this joint belong to
controller_item = item->parent()->parent();
current_edit_controller_ = controller_item->text(0).toUtf8().constData();
moveit_setup_assistant::ROSControlConfig* this_controller =
config_data_->findROSControllerByName(current_edit_controller_);
// Load the data
loadJointsScreen(this_controller);
// Switch to screen
changeScreen(1); // 1 is index of joints
}
else if (type == 1)
{
controller_item = item->parent();
current_edit_controller_ = controller_item->text(0).toUtf8().constData();
moveit_setup_assistant::ROSControlConfig* this_controller =
config_data_->findROSControllerByName(current_edit_controller_);
// Load the data
loadJointsScreen(this_controller);
// Switch to screen
changeScreen(1); // 1 is index of joints
}
else if (type == 0)
{
// Load the data
current_edit_controller_ = item->text(0).toUtf8().constData();
moveit_setup_assistant::ROSControlConfig* this_controller =
config_data_->findROSControllerByName(current_edit_controller_);
loadControllerScreen(this_controller);
// Switch to screen
changeScreen(2); // 1 is index of controller edit
}
else
{
QMessageBox::critical(this, "Error Loading", "An internal error has occured while loading.");
}
}
// ******************************************************************************************
// Edit a controller
// ******************************************************************************************
void ROSControllersWidget::editController()
{
QTreeWidgetItem* item = controllers_tree_->currentItem();
// Check that something was actually selected
if (item == nullptr)
return;
adding_new_controller_ = false;
loadControllerScreen(config_data_->findROSControllerByName(current_edit_controller_));
// Switch to screen
changeScreen(2); // 1 is index of controller edit
}
// ******************************************************************************************
// Switch to current controllers view
// ******************************************************************************************
void ROSControllersWidget::showMainScreen()
{
stacked_layout_->setCurrentIndex(0);
// Announce that this widget is not in modal mode
Q_EMIT isModal(false);
}
// ******************************************************************************************
// Switch which screen is being shown
// ******************************************************************************************
void ROSControllersWidget::changeScreen(int index)
{
stacked_layout_->setCurrentIndex(index);
// Announce this widget's mode
Q_EMIT isModal(index != 0);
}
// ******************************************************************************************
// Expand/Collapse Tree
// ******************************************************************************************
void ROSControllersWidget::alterTree(const QString& link)
{
if (link.contains("expand"))
controllers_tree_->expandAll();
else
controllers_tree_->collapseAll();
}
void ROSControllersWidget::itemSelectionChanged()
{
QList<QTreeWidgetItem*> selected_items = controllers_tree_->selectedItems();
if (selected_items.empty())
{
btn_edit_->setEnabled(false);
btn_delete_->setEnabled(false);
}
}
} // namespace moveit_setup_assistant
|
// Copyright (c) 2013 Mario Mulansky
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// This test case demonstrates the issue described in #798: HPX_LIMIT does not
// work for local dataflow
#include <hpx/hpx.hpp>
#include <hpx/hpx_main.hpp>
#include <hpx/include/actions.hpp>
#include <hpx/util/lightweight_test.hpp>
#include <hpx/dataflow.hpp>
#include <hpx/util/unwrapped.hpp>
using hpx::lcos::shared_future;
using hpx::lcos::make_ready_future;
using hpx::util::unwrapped;
// define large action
double func(double x1 , double x2 , double x3 , double x4 ,
double x5 , double x6 , double x7)
{
return x1;
}
int main()
{
shared_future< double > f = make_ready_future( 1.0 );
f = hpx::dataflow(
hpx::launch::sync,
unwrapped(&func),
f, f, f, f, f, f, f);
return hpx::util::report_errors();
}
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
///
/// \file Sdf/layer.cpp
#include "pxr/pxr.h"
#include "pxr/usd/sdf/layer.h"
#include "pxr/usd/sdf/assetPathResolver.h"
#include "pxr/usd/sdf/attributeSpec.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/usd/sdf/changeManager.h"
#include "pxr/usd/sdf/childrenPolicies.h"
#include "pxr/usd/sdf/childrenUtils.h"
#include "pxr/usd/sdf/debugCodes.h"
#include "pxr/usd/sdf/fileFormat.h"
#include "pxr/usd/sdf/layerRegistry.h"
#include "pxr/usd/sdf/layerStateDelegate.h"
#include "pxr/usd/sdf/layerUtils.h"
#include "pxr/usd/sdf/notice.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/primSpec.h"
#include "pxr/usd/sdf/reference.h"
#include "pxr/usd/sdf/relationshipSpec.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/usd/sdf/specType.h"
#include "pxr/usd/sdf/textFileFormat.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/subLayerListEditor.h"
#include "pxr/usd/sdf/variantSetSpec.h"
#include "pxr/usd/sdf/variantSpec.h"
#include "pxr/usd/ar/resolver.h"
#include "pxr/usd/ar/resolverContextBinder.h"
#include "pxr/base/arch/fileSystem.h"
#include "pxr/base/arch/errno.h"
#include "pxr/base/trace/trace.h"
#include "pxr/base/tf/debug.h"
#include "pxr/base/tf/envSetting.h"
#include "pxr/base/tf/fileUtils.h"
#include "pxr/base/tf/iterator.h"
#include "pxr/base/tf/mallocTag.h"
#include "pxr/base/tf/ostreamMethods.h"
#include "pxr/base/tf/pathUtils.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/scopeDescription.h"
#include "pxr/base/tf/staticData.h"
#include "pxr/base/tf/stackTrace.h"
#include <tbb/queuing_rw_mutex.h>
#include <atomic>
#include <functional>
#include <fstream>
#include <iostream>
#include <set>
#include <thread>
#include <vector>
using std::map;
using std::set;
using std::string;
using std::vector;
namespace ph = std::placeholders;
PXR_NAMESPACE_OPEN_SCOPE
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<SdfLayer>();
}
// Muted Layers stores the paths of layers that should be muted. The stored
// paths should be asset paths, when applicable, or identifiers if no asset
// path exists for the desired layers.
typedef set<string> _MutedLayers;
typedef std::map<std::string, SdfAbstractDataRefPtr> _MutedLayerDataMap;
static TfStaticData<_MutedLayers> _mutedLayers;
static TfStaticData<_MutedLayerDataMap> _mutedLayerData;
// Global mutex protecting _mutedLayers and _mutedLayerData
static TfStaticData<std::mutex> _mutedLayersMutex;
// This is a global revision number that tracks changes to _mutedLayers. Since
// we seldom mute and unmute layers, this lets layers cache their muteness and
// do quick validity checks without taking a lock and looking themselves up in
// _mutedLayers.
static std::atomic_size_t _mutedLayersRevision { 1 };
// A registry for loaded layers.
static TfStaticData<Sdf_LayerRegistry> _layerRegistry;
// Global mutex protecting _layerRegistry.
static tbb::queuing_rw_mutex &
_GetLayerRegistryMutex() {
static tbb::queuing_rw_mutex mutex;
return mutex;
}
TF_DEFINE_ENV_SETTING(
SDF_LAYER_VALIDATE_AUTHORING, false,
"If enabled, layers will validate new fields and specs being authored "
"against their schema. If the field or spec is not defined in the schema "
"a coding error will be issued and the authoring operation will fail.");
SdfLayer::SdfLayer(
const SdfFileFormatConstPtr &fileFormat,
const string &identifier,
const string &realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments &args,
bool validateAuthoring)
: _self(this)
, _fileFormat(fileFormat)
, _fileFormatArgs(args)
, _idRegistry(SdfLayerHandle(this))
, _data(fileFormat->InitData(args))
, _stateDelegate(SdfSimpleLayerStateDelegate::New())
, _lastDirtyState(false)
, _assetInfo(new Sdf_AssetInfo)
, _mutedLayersRevisionCache(0)
, _isMutedCache(false)
, _permissionToEdit(true)
, _permissionToSave(true)
, _validateAuthoring(
validateAuthoring || TfGetEnvSetting<bool>(SDF_LAYER_VALIDATE_AUTHORING))
, _hints{/*.mightHaveRelocates =*/ false}
{
TF_DEBUG(SDF_LAYER).Msg("SdfLayer::SdfLayer('%s', '%s')\n",
identifier.c_str(), realPath.c_str());
// If the identifier has the anonymous layer identifier prefix, it is a
// template into which the layer address must be inserted. This ensures
// that anonymous layers have unique identifiers, and can be referenced by
// Sd object reprs.
string layerIdentifier = Sdf_IsAnonLayerIdentifier(identifier) ?
Sdf_ComputeAnonLayerIdentifier(identifier, this) : identifier;
// Indicate that this layer's initialization is not yet complete before we
// publish this object (i.e. add it to the registry in
// _InitializeFromIdentifier). This ensures that other threads looking for
// this layer will block until it is fully initialized.
_initializationComplete = false;
// Initialize layer asset information.
_InitializeFromIdentifier(
layerIdentifier, realPath, std::string(), assetInfo);
// A new layer is not dirty.
_MarkCurrentStateAsClean();
}
SdfLayer::~SdfLayer()
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::~SdfLayer('%s')\n", GetIdentifier().c_str());
if (IsMuted()) {
std::string mutedPath = _GetMutedPath();
SdfAbstractDataRefPtr mutedData;
{
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
// Drop any in-memory edits we may have been holding for this layer.
// To minimize time holding the lock, swap the data out and
// erase the entry, then release the lock before proceeding
// to drop the refcount.
_MutedLayerDataMap::iterator i = _mutedLayerData->find(mutedPath);
if (i != _mutedLayerData->end()) {
std::swap(mutedData, i->second);
_mutedLayerData->erase(i);
}
}
}
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
// Note that FindOrOpen may have already removed this layer from
// the registry, so we count on this API not emitting errors in that
// case.
_layerRegistry->Erase(_self);
}
const SdfFileFormatConstPtr&
SdfLayer::GetFileFormat() const
{
return _fileFormat;
}
const SdfLayer::FileFormatArguments&
SdfLayer::GetFileFormatArguments() const
{
return _fileFormatArgs;
}
SdfLayerRefPtr
SdfLayer::_CreateNewWithFormat(
const SdfFileFormatConstPtr &fileFormat,
const string& identifier,
const string& realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments& args)
{
// This method should be called with the layerRegistryMutex already held.
// Create and return a new layer with _initializationComplete set false.
return fileFormat->NewLayer(
fileFormat, identifier, realPath, assetInfo, args);
}
void
SdfLayer::_FinishInitialization(bool success)
{
_initializationWasSuccessful = success;
_initializationComplete = true; // unblock waiters.
}
bool
SdfLayer::_WaitForInitializationAndCheckIfSuccessful()
{
// Note: the caller is responsible for holding a reference to this
// layer, to keep it from being destroyed out from under us while
// blocked on the mutex.
// Drop the GIL in case we might have it -- if the layer load happening in
// another thread needs the GIL, we'd deadlock here.
TF_PY_ALLOW_THREADS_IN_SCOPE();
// Wait until _initializationComplete is set to true. If the layer is still
// being initialized, this will be false, blocking progress until
// initialization completes.
while (!_initializationComplete) {
std::this_thread::yield();
}
// For various reasons, initialization may have failed.
// For example, the menva parser may have hit a syntax error,
// or transferring content from a source layer may have failed.
// In this case _initializationWasSuccessful will be set to false.
// The callers of this method are responsible for checking the result
// and dropping any references they hold. As a convenience to them,
// we return the value here.
return _initializationWasSuccessful.get();
}
SdfLayerRefPtr
SdfLayer::CreateAnonymous(
const string& tag, const FileFormatArguments& args)
{
SdfFileFormatConstPtr fileFormat;
string suffix = TfStringGetSuffix(tag);
if (!suffix.empty()) {
fileFormat = SdfFileFormat::FindByExtension(suffix, args);
}
if (!fileFormat) {
fileFormat = SdfFileFormat::FindById(SdfTextFileFormatTokens->Id);
}
if (!fileFormat) {
TF_CODING_ERROR("Cannot determine file format for anonymous SdfLayer");
return SdfLayerRefPtr();
}
return _CreateAnonymousWithFormat(fileFormat, tag, args);
}
SdfLayerRefPtr
SdfLayer::CreateAnonymous(
const string &tag, const SdfFileFormatConstPtr &format,
const FileFormatArguments &args)
{
if (!format) {
TF_CODING_ERROR("Invalid file format for anonymous SdfLayer");
return SdfLayerRefPtr();
}
return _CreateAnonymousWithFormat(format, tag, args);
}
SdfLayerRefPtr
SdfLayer::_CreateAnonymousWithFormat(
const SdfFileFormatConstPtr &fileFormat, const std::string& tag,
const FileFormatArguments &args)
{
if (fileFormat->IsPackage()) {
TF_CODING_ERROR("Cannot create anonymous layer: creating package %s "
"layer is not allowed through this API.",
fileFormat->GetFormatId().GetText());
return SdfLayerRefPtr();
}
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
SdfLayerRefPtr layer =
_CreateNewWithFormat(
fileFormat, Sdf_GetAnonLayerIdentifierTemplate(tag),
string(), ArAssetInfo(), args);
// No layer initialization required, so initialization is complete.
layer->_FinishInitialization(/* success = */ true);
return layer;
}
bool
SdfLayer::IsAnonymous() const
{
return Sdf_IsAnonLayerIdentifier(GetIdentifier());
}
bool
SdfLayer::IsAnonymousLayerIdentifier(const string& identifier)
{
return Sdf_IsAnonLayerIdentifier(identifier);
}
string
SdfLayer::GetDisplayNameFromIdentifier(const string& identifier)
{
return Sdf_GetLayerDisplayName(identifier);
}
SdfLayerRefPtr
SdfLayer::CreateNew(
const string& identifier,
const FileFormatArguments &args)
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::CreateNew('%s', '%s')\n",
identifier.c_str(), TfStringify(args).c_str());
return _CreateNew(TfNullPtr, identifier, args);
}
SdfLayerRefPtr
SdfLayer::CreateNew(
const SdfFileFormatConstPtr& fileFormat,
const string& identifier,
const FileFormatArguments &args)
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::CreateNew('%s', '%s', '%s')\n",
fileFormat->GetFormatId().GetText(),
identifier.c_str(), TfStringify(args).c_str());
return _CreateNew(fileFormat, identifier, args);
}
SdfLayerRefPtr
SdfLayer::_CreateNew(
SdfFileFormatConstPtr fileFormat,
const string& identifier,
const FileFormatArguments &args)
{
if (Sdf_IsAnonLayerIdentifier(identifier)) {
TF_CODING_ERROR("Cannot create a new layer with anonymous "
"layer identifier '%s'.", identifier.c_str());
return TfNullPtr;
}
string whyNot;
if (!Sdf_CanCreateNewLayerWithIdentifier(identifier, &whyNot)) {
TF_CODING_ERROR("Cannot create new layer '%s': %s",
identifier.c_str(),
whyNot.c_str());
return TfNullPtr;
}
ArResolver& resolver = ArGetResolver();
ArAssetInfo assetInfo;
#if AR_VERSION == 1
// When creating a new layer, assume that relative identifiers are
// relative to the current working directory.
const bool isRelativePath = resolver.IsRelativePath(identifier);
const string absIdentifier =
isRelativePath ? TfAbsPath(identifier) : identifier;
// Direct newly created layers to a local path.
const string localPath = resolver.ComputeLocalPath(absIdentifier);
#else
const string absIdentifier =
resolver.CreateIdentifierForNewAsset(identifier);
// Resolve the identifier to the path where new assets should go.
const string localPath = resolver.ResolveForNewAsset(absIdentifier);
#endif
if (localPath.empty()) {
TF_CODING_ERROR(
"Failed to compute path for new layer with "
"identifier '%s'", absIdentifier.c_str());
return TfNullPtr;
}
// If not explicitly supplied one, try to determine the fileFormat
// based on the local path suffix,
if (!fileFormat) {
fileFormat = SdfFileFormat::FindByExtension(localPath, args);
// XXX: This should be a coding error, not a failed verify.
if (!TF_VERIFY(fileFormat))
return TfNullPtr;
}
// Restrict creating package layers via the Sdf API. These layers
// are expected to be created via other libraries or external programs.
if (Sdf_IsPackageOrPackagedLayer(fileFormat, identifier)) {
TF_CODING_ERROR("Cannot create new layer '%s': creating %s %s "
"layer is not allowed through this API.",
identifier.c_str(),
fileFormat->IsPackage() ? "package" : "packaged",
fileFormat->GetFormatId().GetText());
return TfNullPtr;
}
// In case of failure below, we want to release the layer
// registry mutex lock before destroying the layer.
SdfLayerRefPtr layer;
{
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
// Check for existing layer with this identifier.
if (_layerRegistry->Find(absIdentifier)) {
TF_CODING_ERROR("A layer already exists with identifier '%s'",
absIdentifier.c_str());
return TfNullPtr;
}
layer = _CreateNewWithFormat(
fileFormat, absIdentifier, localPath, ArAssetInfo(), args);
if (!TF_VERIFY(layer)) {
return TfNullPtr;
}
// Stash away the existing layer hints. The call to _Save below will
// invalidate them but they should still be good.
SdfLayerHints hints = layer->_hints;
// XXX 2011-08-19 Newly created layers should not be
// saved to disk automatically.
//
// Force the save here to ensure this new layer overwrites any
// existing layer on disk.
if (!layer->_Save(/* force = */ true)) {
// Dropping the layer reference will destroy it, and
// the destructor will remove it from the registry.
return TfNullPtr;
}
layer->_hints = hints;
// Once we have saved the layer, initialization is complete.
layer->_FinishInitialization(/* success = */ true);
}
// Return loaded layer or special-cased in-memory layer.
return layer;
}
SdfLayerRefPtr
SdfLayer::New(
const SdfFileFormatConstPtr& fileFormat,
const string& identifier,
const FileFormatArguments& args)
{
if (!fileFormat) {
TF_CODING_ERROR("Invalid file format");
return TfNullPtr;
}
if (identifier.empty()) {
TF_CODING_ERROR("Cannot construct a layer with an empty identifier.");
return TfNullPtr;
}
if (Sdf_IsPackageOrPackagedLayer(fileFormat, identifier)) {
TF_CODING_ERROR("Cannot construct new %s %s layer",
fileFormat->IsPackage() ? "package" : "packaged",
fileFormat->GetFormatId().GetText());
return TfNullPtr;
}
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
#if AR_VERSION == 1
// When creating a new layer, assume that relative identifiers are
// relative to the current working directory.
const string absIdentifier = ArGetResolver().IsRelativePath(identifier) ?
TfAbsPath(identifier) : identifier;
#else
const string absIdentifier =
ArGetResolver().CreateIdentifierForNewAsset(identifier);
#endif
SdfLayerRefPtr layer = _CreateNewWithFormat(
fileFormat, absIdentifier, std::string(), ArAssetInfo(), args);
// No further initialization required.
layer->_FinishInitialization(/* success = */ true);
return layer;
}
/* static */
string
SdfLayer::ComputeRealPath(const string &layerPath)
{
return Sdf_ComputeFilePath(layerPath);
}
static SdfLayer::FileFormatArguments&
_CanonicalizeFileFormatArguments(const std::string& filePath,
const SdfFileFormatConstPtr& fileFormat,
SdfLayer::FileFormatArguments& args)
{
// Nothing to do if there isn't an associated file format.
// This is expected by _ComputeInfoToFindOrOpenLayer and isn't an error.
if (!fileFormat) {
// XXX:
// Sdf is unable to determine a file format for layers that are created
// without a file extension (which includes anonymous layers). The keys
// for these layers in the registry will never include a 'target'
// argument -- the API doesn't give you a way to do that.
//
// So, if a 'target' is specified here, we want to strip it out
// so Find and FindOrOpen will search the registry and find these
// layers. If we didn't, we would search the registry for an
// identifier with the 'target' arg embedded, and we'd never find
// it.
//
// This is a hack. I think the right thing is to either:
// a) Ensure that a layer's identifier always encodes its file format
// b) Do this target argument stripping in Find / FindOrOpen, find
// the layer, then verify that the layer's target is the one that
// was specified.
//
// These are larger changes that require updating some clients, so
// I don't want to do this yet.
if (Sdf_GetExtension(filePath).empty()) {
args.erase(SdfFileFormatTokens->TargetArg);
}
return args;
}
SdfLayer::FileFormatArguments::iterator targetIt =
args.find(SdfFileFormatTokens->TargetArg);
if (targetIt != args.end()) {
if (fileFormat->IsPrimaryFormatForExtensions()) {
// If the file format plugin being used to open the indicated layer
// is the primary plugin for layers of that type, it means the
// 'target' argument (if any) had no effect and can be stripped
// from the arguments.
args.erase(targetIt);
}
else {
// The target argument may have been a comma-delimited list of
// targets to use. The canonical arguments should contain just
// the target for the file format for this layer so that subsequent
// lookups using the same target return the same layer. For example,
// a layer opened with target="x" and target="x,y" should return
// the same layer.
targetIt->second = fileFormat->GetTarget().GetString();
}
}
// If there aren't any more args to canonicalize, we can exit early.
if (args.empty()) {
return args;
}
// Strip out any arguments that match the file format's published
// default arguments. A layer opened without any arguments should
// be considered equivalent to a layer opened with only default
// arguments specified.
const SdfLayer::FileFormatArguments defaultArgs =
fileFormat->GetDefaultFileFormatArguments();
TF_FOR_ALL(it, defaultArgs) {
SdfLayer::FileFormatArguments::iterator argIt = args.find(it->first);
if (argIt != args.end() && argIt->second == it->second) {
args.erase(argIt);
}
}
return args;
}
struct SdfLayer::_FindOrOpenLayerInfo
{
// File format plugin for the layer. This may be NULL if
// the file format could not be identified.
SdfFileFormatConstPtr fileFormat;
// Canonical file format arguments.
SdfLayer::FileFormatArguments fileFormatArgs;
// Whether this layer is anonymous.
bool isAnonymous = false;
// Path to the layer.
string layerPath;
// Resolved path for the layer. If the layer is an anonymous layer,
// this will be the same as layerPath.
string resolvedLayerPath;
// Identifier for the layer, combining both the layer path and
// file format arguments.
string identifier;
// Asset info from resolving the layer path.
ArAssetInfo assetInfo;
};
bool
SdfLayer::_ComputeInfoToFindOrOpenLayer(
const string& identifier,
const SdfLayer::FileFormatArguments& args,
_FindOrOpenLayerInfo* info,
bool computeAssetInfo)
{
TRACE_FUNCTION();
if (identifier.empty()) {
return false;
}
string layerPath;
SdfLayer::FileFormatArguments layerArgs;
if (!Sdf_SplitIdentifier(identifier, &layerPath, &layerArgs) ||
layerPath.empty()) {
return false;
}
const bool isAnonymous = IsAnonymousLayerIdentifier(layerPath);
#if AR_VERSION > 1
if (!isAnonymous) {
layerPath = ArGetResolver().CreateIdentifier(layerPath);
}
#endif
// If we're trying to open an anonymous layer, do not try to compute the
// real path for it.
ArAssetInfo assetInfo;
string resolvedLayerPath = isAnonymous ? layerPath :
Sdf_ResolvePath(layerPath, computeAssetInfo ? &assetInfo : nullptr);
// Merge explicitly-specified arguments over any arguments
// embedded in the given identifier.
if (layerArgs.empty()) {
layerArgs = args;
}
else {
TF_FOR_ALL(it, args) {
layerArgs[it->first] = it->second;
}
}
info->fileFormat = SdfFileFormat::FindByExtension(
resolvedLayerPath.empty() ? layerPath : resolvedLayerPath, layerArgs);
info->fileFormatArgs.swap(_CanonicalizeFileFormatArguments(
layerPath, info->fileFormat, layerArgs));
info->isAnonymous = isAnonymous;
info->layerPath.swap(layerPath);
info->resolvedLayerPath.swap(resolvedLayerPath);
info->identifier = Sdf_CreateIdentifier(
info->layerPath, info->fileFormatArgs);
swap(info->assetInfo, assetInfo);
return true;
}
template <class ScopedLock>
SdfLayerRefPtr
SdfLayer::_TryToFindLayer(const string &identifier,
const string &resolvedPath,
ScopedLock &lock,
bool retryAsWriter)
{
SdfLayerRefPtr result;
bool hasWriteLock = false;
retry:
if (SdfLayerHandle layer = _layerRegistry->Find(identifier, resolvedPath)) {
// We found a layer in the registry -- try to acquire a TfRefPtr to this
// layer. Since we have the lock, we guarantee that the layer's
// TfRefBase will not be destroyed until we unlock.
result = TfCreateRefPtrFromProtectedWeakPtr(layer);
if (result) {
// We got an ownership stake in the layer, release the lock and
// return it.
lock.release();
return result;
}
// We found a layer but we could not get an ownership stake in it -- it
// is expiring. Upgrade the lock to a write lock since we will have to
// try to remove this expiring layer from the registry. If our upgrade
// is non-atomic, we must retry the steps above, since everything
// might've changed in the meantime.
if (!hasWriteLock && !lock.upgrade_to_writer()) {
// We have the write lock, but we released it in the interim, so
// repeat our steps above now that we have the write lock.
hasWriteLock = true;
goto retry;
}
if (layer) {
// Layer is expiring and we have the write lock: erase it from the
// registry.
_layerRegistry->Erase(layer);
}
} else if (!hasWriteLock && retryAsWriter && !lock.upgrade_to_writer()) {
// Retry the find since we released the lock in upgrade_to_writer().
hasWriteLock = true;
goto retry;
}
if (!retryAsWriter)
lock.release();
return result;
}
/* static */
SdfLayerRefPtr
SdfLayer::FindOrOpen(const string &identifier,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::FindOrOpen('%s', '%s')\n",
identifier.c_str(), TfStringify(args).c_str());
// Drop the GIL, since if we hold it and another thread that has the
// _layerRegistryMutex needs it (if its opening code invokes python, for
// instance), we'll deadlock.
TF_PY_ALLOW_THREADS_IN_SCOPE();
_FindOrOpenLayerInfo layerInfo;
if (!_ComputeInfoToFindOrOpenLayer(identifier, args, &layerInfo,
/* computeAssetInfo = */ true)) {
return TfNullPtr;
}
// First see if this layer is already present.
tbb::queuing_rw_mutex::scoped_lock
lock(_GetLayerRegistryMutex(), /*write=*/false);
if (SdfLayerRefPtr layer =
_TryToFindLayer(layerInfo.identifier, layerInfo.resolvedLayerPath,
lock, /*retryAsWriter=*/true)) {
// This could be written as a ternary, but we rely on return values
// being implicitly moved to avoid making an unnecessary copy of
// layer and the associated ref-count bump.
if (layer->_WaitForInitializationAndCheckIfSuccessful()) {
return layer;
}
return TfNullPtr;
}
// At this point _TryToFindLayer has upgraded lock to a writer.
// Some layers, such as anonymous layers, have identifiers but don't have
// resolved paths. They aren't backed by assets on disk. If we don't find
// such a layer by identifier in the registry, we're done since we don't
// have an asset to open.
if (layerInfo.resolvedLayerPath.empty()) {
return TfNullPtr;
}
// Otherwise we create the layer and insert it into the registry.
return _OpenLayerAndUnlockRegistry(lock, layerInfo,
/* metadataOnly */ false);
}
/* static */
SdfLayerRefPtr
SdfLayer::FindOrOpenRelativeToLayer(
const SdfLayerHandle &anchor,
const string &identifier,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
if (!anchor) {
TF_CODING_ERROR("Anchor layer is invalid");
return TfNullPtr;
}
// For consistency with FindOrOpen, we silently bail out if identifier
// is empty here to avoid the coding error that is emitted in that case
// in SdfComputeAssetPathRelativeToLayer.
if (identifier.empty()) {
return TfNullPtr;
}
return FindOrOpen(
SdfComputeAssetPathRelativeToLayer(anchor, identifier), args);
}
/* static */
SdfLayerRefPtr
SdfLayer::OpenAsAnonymous(
const std::string &layerPath,
bool metadataOnly,
const std::string &tag)
{
_FindOrOpenLayerInfo layerInfo;
if (!_ComputeInfoToFindOrOpenLayer(layerPath, FileFormatArguments(),
&layerInfo)) {
return TfNullPtr;
}
// XXX: Is this really a coding error? SdfLayer avoids issuing errors if
// given a non-existent file, for instance. Should we be following the
// same policy here?
if (!layerInfo.fileFormat) {
TF_CODING_ERROR("Cannot determine file format for @%s@",
layerInfo.identifier.c_str());
return TfNullPtr;
}
// Create a new anonymous layer.
SdfLayerRefPtr layer;
{
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
layer = _CreateNewWithFormat(
layerInfo.fileFormat, Sdf_GetAnonLayerIdentifierTemplate(tag),
string());
// From this point, we must call _FinishInitialization() on
// either success or failure in order to unblock other
// threads waiting for initialization to finish.
}
// Run the file parser to read in the file contents.
if (!layer->_Read(layerInfo.identifier, layerInfo.resolvedLayerPath,
metadataOnly)) {
layer->_FinishInitialization(/* success = */ false);
return TfNullPtr;
}
layer->_MarkCurrentStateAsClean();
layer->_FinishInitialization(/* success = */ true);
return layer;
}
const SdfSchemaBase&
SdfLayer::GetSchema() const
{
return GetFileFormat()->GetSchema();
}
// For the given layer, gets a dictionary of resolved external asset dependency
// paths to the timestamp for each asset.
static VtDictionary
_GetExternalAssetModificationTimes(const SdfLayer& layer)
{
VtDictionary result;
std::set<std::string> externalAssetDependencies =
layer.GetExternalAssetDependencies();
for (const std::string& resolvedPath : externalAssetDependencies) {
// Get the modification timestamp for the path. Note that external
// asset dependencies only returns resolved paths so pass the same
// path for both params.
result[resolvedPath] = ArGetResolver().GetModificationTimestamp(
resolvedPath, ArResolvedPath(resolvedPath));
}
return result;
}
SdfLayer::_ReloadResult
SdfLayer::_Reload(bool force)
{
TRACE_FUNCTION();
string identifier = GetIdentifier();
if (identifier.empty()) {
TF_CODING_ERROR("Can't reload a layer with no identifier");
return _ReloadFailed;
}
SdfChangeBlock block;
if (IsAnonymous() && GetFileFormat()->ShouldSkipAnonymousReload()) {
// Different file formats have different policies for reloading
// anonymous layers. Some want to treat it as a noop, others want to
// treat it as 'Clear'.
//
// XXX: in the future, I think we want FileFormat plugins to
// have a Reload function. The plugin can manage when it needs to
// reload data appropriately.
return _ReloadSkipped;
}
else if (IsMuted() || IsAnonymous()) {
// Reloading a muted layer leaves it with the initialized contents.
SdfAbstractDataRefPtr initialData =
GetFileFormat()->InitData(GetFileFormatArguments());
if (_data->Equals(initialData)) {
return _ReloadSkipped;
}
_SetData(initialData);
} else {
// The physical location of the file may have changed since
// the last load, so re-resolve the identifier.
const ArResolvedPath oldResolvedPath = GetResolvedPath();
UpdateAssetInfo();
const ArResolvedPath resolvedPath = GetResolvedPath();
// If asset resolution in UpdateAssetInfo failed, we may end
// up with an empty real path, and cannot reload the layer.
if (resolvedPath.empty()) {
TF_RUNTIME_ERROR(
"Cannot determine resolved path for '%s', skipping reload.",
identifier.c_str());
return _ReloadFailed;
}
// If this layer's modification timestamp is empty, this is a
// new layer that has never been serialized. This could happen
// if a layer were created with SdfLayer::New, for instance.
// In such cases we can skip the reload since there's nowhere
// to reload data from.
//
// This ensures we don't ask for the modification timestamp for
// unserialized new layers below, which would result in errors.
//
// XXX 2014-09-02 Reset layer to initial data?
if (_assetModificationTime.IsEmpty()) {
return _ReloadSkipped;
}
// Get the layer's modification timestamp.
VtValue timestamp = ArGetResolver().GetModificationTimestamp(
GetIdentifier(), resolvedPath);
if (timestamp.IsEmpty()) {
TF_CODING_ERROR(
"Unable to get modification time for '%s (%s)'",
GetIdentifier().c_str(), resolvedPath.GetPathString().c_str());
return _ReloadFailed;
}
// Ask the current external asset dependency state.
VtDictionary externalAssetTimestamps =
_GetExternalAssetModificationTimes(*this);
// See if we can skip reloading.
if (!force && !IsDirty()
&& (resolvedPath == oldResolvedPath)
&& (timestamp == _assetModificationTime)
&& (externalAssetTimestamps == _externalAssetModificationTimes)) {
return _ReloadSkipped;
}
if (!_Read(GetIdentifier(), resolvedPath, /* metadataOnly = */ false)) {
return _ReloadFailed;
}
_assetModificationTime.Swap(timestamp);
_externalAssetModificationTimes = std::move(externalAssetTimestamps);
if (resolvedPath != oldResolvedPath) {
Sdf_ChangeManager::Get().DidChangeLayerResolvedPath(_self);
}
}
_MarkCurrentStateAsClean();
Sdf_ChangeManager::Get().DidReloadLayerContent(_self);
return _ReloadSucceeded;
}
bool
SdfLayer::Reload(bool force)
{
return _Reload(force) == _ReloadSucceeded;
}
bool
SdfLayer::ReloadLayers(
const set<SdfLayerHandle>& layers,
bool force)
{
TF_DESCRIBE_SCOPE("Reloading %zu layer(s)", layers.size());
// Block re-composition until we've finished reloading layers.
SdfChangeBlock block;
bool status = true;
TF_FOR_ALL(layer, layers) {
if (*layer) {
if ((*layer)->_Reload(force) == _ReloadFailed) {
status = false;
TF_WARN("Unable to re-read @%s@",
(*layer)->GetIdentifier().c_str());
}
}
}
return status;
}
bool
SdfLayer::Import(const string &layerPath)
{
string filePath = Sdf_ResolvePath(layerPath);
if (filePath.empty())
return false;
return _Read(layerPath, filePath, /* metadataOnly = */ false);
}
bool
SdfLayer::ImportFromString(const std::string &s)
{
return GetFileFormat()->ReadFromString(this, s);
}
bool
SdfLayer::_Read(
const string& identifier,
const string& resolvedPath,
bool metadataOnly)
{
TRACE_FUNCTION();
TfAutoMallocTag tag("SdfLayer::_Read");
TF_DESCRIBE_SCOPE("Loading layer '%s'", resolvedPath.c_str());
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::_Read('%s', '%s', metadataOnly=%s)\n",
identifier.c_str(), resolvedPath.c_str(),
TfStringify(metadataOnly).c_str());
SdfFileFormatConstPtr format = GetFileFormat();
if (format->LayersAreFileBased()) {
if (!ArGetResolver().FetchToLocalResolvedPath(
identifier, resolvedPath)) {
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::_Read - unable to fetch '%s' to "
"local path '%s'\n",
identifier.c_str(), resolvedPath.c_str());
return false;
}
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::_Read - fetched '%s' to local path '%s'\n",
identifier.c_str(), resolvedPath.c_str());
}
return format->Read(this, resolvedPath, metadataOnly);
}
/*static*/
SdfLayerHandle
SdfLayer::Find(const string &identifier,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
// We don't need to drop the GIL here, since _TryToFindLayer() doesn't
// invoke any plugin code, and if we do wind up calling
// _WaitForInitializationAndCheckIfSuccessful() then we'll drop the GIL in
// there.
_FindOrOpenLayerInfo layerInfo;
if (!_ComputeInfoToFindOrOpenLayer(identifier, args, &layerInfo)) {
return TfNullPtr;
}
// First see if this layer is already present.
tbb::queuing_rw_mutex::scoped_lock
lock(_GetLayerRegistryMutex(), /*write=*/false);
if (SdfLayerRefPtr layer = _TryToFindLayer(
layerInfo.identifier, layerInfo.resolvedLayerPath,
lock, /*retryAsWriter=*/false)) {
return layer->_WaitForInitializationAndCheckIfSuccessful() ?
layer : TfNullPtr;
}
return TfNullPtr;
}
/* static */
SdfLayerHandle
SdfLayer::FindRelativeToLayer(
const SdfLayerHandle &anchor,
const string &identifier,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
if (!anchor) {
TF_CODING_ERROR("Anchor layer is invalid");
return TfNullPtr;
}
// For consistency with FindOrOpen, we silently bail out if identifier
// is empty here to avoid the coding error that is emitted in that case
// in SdfComputeAssetPathRelativeToLayer.
if (identifier.empty()) {
return TfNullPtr;
}
return Find(
SdfComputeAssetPathRelativeToLayer(anchor, identifier), args);
}
std::set<double>
SdfLayer::ListAllTimeSamples() const
{
return _data->ListAllTimeSamples();
}
std::set<double>
SdfLayer::ListTimeSamplesForPath(const SdfPath& path) const
{
return _data->ListTimeSamplesForPath(path);
}
bool
SdfLayer::GetBracketingTimeSamples(double time, double* tLower, double* tUpper)
{
return _data->GetBracketingTimeSamples(time, tLower, tUpper);
}
size_t
SdfLayer::GetNumTimeSamplesForPath(const SdfPath& path) const
{
return _data->GetNumTimeSamplesForPath(path);
}
bool
SdfLayer::GetBracketingTimeSamplesForPath(const SdfPath& path,
double time,
double* tLower, double* tUpper)
{
return _data->GetBracketingTimeSamplesForPath(path, time, tLower, tUpper);
}
bool
SdfLayer::QueryTimeSample(const SdfPath& path, double time,
VtValue *value) const
{
return _data->QueryTimeSample(path, time, value);
}
bool
SdfLayer::QueryTimeSample(const SdfPath& path, double time,
SdfAbstractDataValue *value) const
{
return _data->QueryTimeSample(path, time, value);
}
static TfType
_GetExpectedTimeSampleValueType(
const SdfLayer& layer, const SdfPath& path)
{
const SdfSpecType specType = layer.GetSpecType(path);
if (specType == SdfSpecTypeUnknown) {
TF_CODING_ERROR("Cannot set time sample at <%s> since spec does "
"not exist", path.GetText());
return TfType();
}
else if (specType != SdfSpecTypeAttribute &&
specType != SdfSpecTypeRelationship) {
TF_CODING_ERROR("Cannot set time sample at <%s> because spec "
"is not an attribute or relationship",
path.GetText());
return TfType();
}
TfType valueType;
TfToken valueTypeName;
if (specType == SdfSpecTypeRelationship) {
static const TfType pathType = TfType::Find<SdfPath>();
valueType = pathType;
}
else if (layer.HasField(path, SdfFieldKeys->TypeName, &valueTypeName)) {
valueType = layer.GetSchema().FindType(valueTypeName).GetType();
}
if (!valueType) {
TF_CODING_ERROR("Cannot determine value type for <%s>",
path.GetText());
}
return valueType;
}
void
SdfLayer::SetTimeSample(const SdfPath& path, double time,
const VtValue & value)
{
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot set time sample on <%s>. "
"Layer @%s@ is not editable.",
path.GetText(),
GetIdentifier().c_str());
return;
}
// circumvent type checking if setting a block.
if (value.IsHolding<SdfValueBlock>()) {
_PrimSetTimeSample(path, time, value);
return;
}
const TfType expectedType = _GetExpectedTimeSampleValueType(*this, path);
if (!expectedType) {
// Error already emitted, just bail.
return;
}
if (value.GetType() == expectedType) {
_PrimSetTimeSample(path, time, value);
}
else {
const VtValue castValue =
VtValue::CastToTypeid(value, expectedType.GetTypeid());
if (castValue.IsEmpty()) {
TF_CODING_ERROR("Can't set time sample on <%s> to %s: "
"expected a value of type \"%s\"",
path.GetText(),
TfStringify(value).c_str(),
expectedType.GetTypeName().c_str());
return;
}
_PrimSetTimeSample(path, time, castValue);
}
}
// cache the value of typeid(SdfValueBlock)
namespace
{
const TfType& _GetSdfValueBlockType()
{
static const TfType blockType = TfType::Find<SdfValueBlock>();
return blockType;
}
}
void
SdfLayer::SetTimeSample(const SdfPath& path, double time,
const SdfAbstractDataConstValue& value)
{
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot set time sample on <%s>. "
"Layer @%s@ is not editable.",
path.GetText(),
GetIdentifier().c_str());
return;
}
if (value.valueType == _GetSdfValueBlockType().GetTypeid()) {
_PrimSetTimeSample(path, time, value);
return;
}
const TfType expectedType = _GetExpectedTimeSampleValueType(*this, path);
if (!expectedType) {
// Error already emitted, just bail.
return;
}
if (TfSafeTypeCompare(value.valueType, expectedType.GetTypeid())) {
_PrimSetTimeSample(path, time, value);
}
else {
VtValue tmpValue;
value.GetValue(&tmpValue);
const VtValue castValue =
VtValue::CastToTypeid(tmpValue, expectedType.GetTypeid());
if (castValue.IsEmpty()) {
TF_CODING_ERROR("Can't set time sample on <%s> to %s: "
"expected a value of type \"%s\"",
path.GetText(),
TfStringify(tmpValue).c_str(),
expectedType.GetTypeName().c_str());
return;
}
_PrimSetTimeSample(path, time, castValue);
}
}
void
SdfLayer::EraseTimeSample(const SdfPath& path, double time)
{
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot set time sample on <%s>. "
"Layer @%s@ is not editable.",
path.GetText(),
GetIdentifier().c_str());
return;
}
if (!HasSpec(path)) {
TF_CODING_ERROR("Cannot SetTimeSample at <%s> since spec does "
"not exist", path.GetText());
return;
}
if (!QueryTimeSample(path, time)) {
// No time sample to remove.
return;
}
_PrimSetTimeSample(path, time, VtValue());
}
static
const VtValue& _GetVtValue(const VtValue& v)
{ return v; }
static
VtValue _GetVtValue(const SdfAbstractDataConstValue& v)
{
VtValue value;
TF_VERIFY(v.GetValue(&value));
return value;
}
template <class T>
void
SdfLayer::_PrimSetTimeSample(const SdfPath& path, double time,
const T& value,
bool useDelegate)
{
if (useDelegate && TF_VERIFY(_stateDelegate)) {
_stateDelegate->SetTimeSample(path, time, value);
return;
}
SdfChangeBlock block;
// TODO(USD):optimization: Analyze the affected time interval.
Sdf_ChangeManager::Get().DidChangeAttributeTimeSamples(_self, path);
// XXX: Should modify SetTimeSample API to take an
// SdfAbstractDataConstValue instead of (or along with) VtValue.
const VtValue& valueToSet = _GetVtValue(value);
_data->SetTimeSample(path, time, valueToSet);
}
template void SdfLayer::_PrimSetTimeSample(
const SdfPath&, double,
const VtValue&, bool);
template void SdfLayer::_PrimSetTimeSample(
const SdfPath&, double,
const SdfAbstractDataConstValue&, bool);
// ---
// End of SdfLayer static functions
// ---
void
SdfLayer::_InitializeFromIdentifier(
const string& identifier,
const string& realPath,
const string& fileVersion,
const ArAssetInfo& assetInfo)
{
TRACE_FUNCTION();
// Compute layer asset information from the identifier.
std::unique_ptr<Sdf_AssetInfo> newInfo(
Sdf_ComputeAssetInfoFromIdentifier(identifier, realPath, assetInfo,
fileVersion));
if (!newInfo)
return;
// If the newly computed asset info is identical to the existing asset
// info, there is no need to update registries or send notices.
if (*newInfo == *_assetInfo)
return;
// Swap the layer asset info with the newly computed information. This
// must occur prior to updating the layer registry, as the new layer
// information is used to recompute registry indices.
string oldIdentifier = _assetInfo->identifier;
ArResolvedPath oldResolvedPath = _assetInfo->resolvedPath;
_assetInfo.swap(newInfo);
// Update layer state delegate.
if (TF_VERIFY(_stateDelegate)) {
_stateDelegate->_SetLayer(_self);
}
// Update the layer registry before sending notices.
_layerRegistry->InsertOrUpdate(_self);
// Only send a notice if the identifier has changed (this notice causes
// mass invalidation. See http://bug/33217). If the old identifier was
// empty, this is a newly constructed layer, so don't send the notice.
if (!oldIdentifier.empty()) {
SdfChangeBlock block;
if (oldIdentifier != GetIdentifier()) {
Sdf_ChangeManager::Get().DidChangeLayerIdentifier(
_self, oldIdentifier);
}
if (oldResolvedPath != GetResolvedPath()) {
Sdf_ChangeManager::Get().DidChangeLayerResolvedPath(_self);
}
}
}
template <class T>
inline
void
SdfLayer::_SetValue(const TfToken& key, T value)
{
SetField(SdfPath::AbsoluteRootPath(), key, VtValue(value));
}
template <class T>
inline
T
SdfLayer::_GetValue(const TfToken& key) const
{
VtValue value;
if (!HasField(SdfPath::AbsoluteRootPath(), key, &value)) {
return GetSchema().GetFallback(key).Get<T>();
}
return value.Get<T>();
}
SdfAssetPath
SdfLayer::GetColorConfiguration() const
{
return _GetValue<SdfAssetPath>(SdfFieldKeys->ColorConfiguration);
}
void
SdfLayer::SetColorConfiguration(const SdfAssetPath &colorConfiguration)
{
_SetValue(SdfFieldKeys->ColorConfiguration, colorConfiguration);
}
bool
SdfLayer::HasColorConfiguration() const
{
return HasField(SdfPath::AbsoluteRootPath(),
SdfFieldKeys->ColorConfiguration);
}
void
SdfLayer::ClearColorConfiguration()
{
EraseField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->ColorConfiguration);
}
TfToken
SdfLayer::GetColorManagementSystem() const
{
return _GetValue<TfToken>(SdfFieldKeys->ColorManagementSystem);
}
void
SdfLayer::SetColorManagementSystem(const TfToken &cms)
{
_SetValue(SdfFieldKeys->ColorManagementSystem, cms);
}
bool
SdfLayer::HasColorManagementSystem() const
{
return HasField(SdfPath::AbsoluteRootPath(),
SdfFieldKeys->ColorManagementSystem);
}
void
SdfLayer::ClearColorManagementSystem()
{
EraseField(SdfPath::AbsoluteRootPath(),
SdfFieldKeys->ColorManagementSystem);
}
void
SdfLayer::SetComment(const string &newVal)
{
_SetValue(SdfFieldKeys->Comment, newVal);
}
string
SdfLayer::GetComment() const
{
return _GetValue<string>(SdfFieldKeys->Comment);
}
void
SdfLayer::SetDefaultPrim(const TfToken &name)
{
_SetValue(SdfFieldKeys->DefaultPrim, name);
}
TfToken
SdfLayer::GetDefaultPrim() const
{
return _GetValue<TfToken>(SdfFieldKeys->DefaultPrim);
}
void
SdfLayer::ClearDefaultPrim()
{
EraseField(SdfPath::AbsoluteRootPath(),
SdfFieldKeys->DefaultPrim);
}
bool
SdfLayer::HasDefaultPrim()
{
return HasField(SdfPath::AbsoluteRootPath(),
SdfFieldKeys->DefaultPrim);
}
void
SdfLayer::SetDocumentation(const string &newVal)
{
_SetValue(SdfFieldKeys->Documentation, newVal);
}
string
SdfLayer::GetDocumentation() const
{
return _GetValue<string>(SdfFieldKeys->Documentation);
}
void
SdfLayer::SetStartTimeCode( double newVal )
{
_SetValue(SdfFieldKeys->StartTimeCode, newVal);
}
double
SdfLayer::GetStartTimeCode() const
{
return _GetValue<double>(SdfFieldKeys->StartTimeCode);
}
bool
SdfLayer::HasStartTimeCode() const
{
return HasField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->StartTimeCode);
}
void
SdfLayer::ClearStartTimeCode()
{
EraseField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->StartTimeCode);
}
void
SdfLayer::SetEndTimeCode( double newVal )
{
_SetValue(SdfFieldKeys->EndTimeCode, newVal);
}
double
SdfLayer::GetEndTimeCode() const
{
return _GetValue<double>(SdfFieldKeys->EndTimeCode);
}
bool
SdfLayer::HasEndTimeCode() const
{
return HasField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->EndTimeCode);
}
void
SdfLayer::ClearEndTimeCode()
{
EraseField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->EndTimeCode);
}
void
SdfLayer::SetTimeCodesPerSecond( double newVal )
{
_SetValue(SdfFieldKeys->TimeCodesPerSecond, newVal);
}
double
SdfLayer::GetTimeCodesPerSecond() const
{
// If there is an authored value for timeCodesPerSecond, return that.
VtValue value;
if (HasField(
SdfPath::AbsoluteRootPath(),
SdfFieldKeys->TimeCodesPerSecond,
&value)) {
return value.Get<double>();
}
// Otherwise return framesPerSecond as a dynamic fallback. This allows
// layers to lock framesPerSecond and timeCodesPerSecond together by
// specifying only framesPerSecond.
//
// If neither field has an authored value, this will return 24, which is the
// final fallback value for both fields.
return GetFramesPerSecond();
}
bool
SdfLayer::HasTimeCodesPerSecond() const
{
return HasField(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->TimeCodesPerSecond);
}
void
SdfLayer::ClearTimeCodesPerSecond()
{
return EraseField(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->TimeCodesPerSecond);
}
void
SdfLayer::SetFramesPerSecond( double newVal )
{
_SetValue(SdfFieldKeys->FramesPerSecond, newVal);
}
double
SdfLayer::GetFramesPerSecond() const
{
return _GetValue<double>(SdfFieldKeys->FramesPerSecond);
}
bool
SdfLayer::HasFramesPerSecond() const
{
return HasField(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->FramesPerSecond);
}
void
SdfLayer::ClearFramesPerSecond()
{
return EraseField(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->FramesPerSecond);
}
void
SdfLayer::SetFramePrecision( int newVal )
{
_SetValue(SdfFieldKeys->FramePrecision, newVal);
}
int
SdfLayer::GetFramePrecision() const
{
return _GetValue<int>(SdfFieldKeys->FramePrecision);
}
bool
SdfLayer::HasFramePrecision() const
{
return HasField(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->FramePrecision);
}
void
SdfLayer::ClearFramePrecision()
{
return EraseField(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->FramePrecision);
}
string
SdfLayer::GetOwner() const
{
return _GetValue<string>(SdfFieldKeys->Owner);
}
void
SdfLayer::SetOwner(const std::string& newVal)
{
_SetValue(SdfFieldKeys->Owner, newVal);
}
bool
SdfLayer::HasOwner() const
{
return HasField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->Owner);
}
void
SdfLayer::ClearOwner()
{
return EraseField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->Owner);
}
string
SdfLayer::GetSessionOwner() const
{
return _GetValue<string>(SdfFieldKeys->SessionOwner);
}
void
SdfLayer::SetSessionOwner(const std::string& newVal)
{
_SetValue(SdfFieldKeys->SessionOwner, newVal);
}
bool
SdfLayer::HasSessionOwner() const
{
return HasField(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->SessionOwner);
}
void
SdfLayer::ClearSessionOwner()
{
return EraseField(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->SessionOwner);
}
bool
SdfLayer::GetHasOwnedSubLayers() const
{
return _GetValue<bool>(SdfFieldKeys->HasOwnedSubLayers);
}
void
SdfLayer::SetHasOwnedSubLayers(bool newVal)
{
_SetValue(SdfFieldKeys->HasOwnedSubLayers, newVal);
}
VtDictionary
SdfLayer::GetCustomLayerData() const
{
return _GetValue<VtDictionary>(SdfFieldKeys->CustomLayerData);
}
void
SdfLayer::SetCustomLayerData(const VtDictionary& dict)
{
_SetValue(SdfFieldKeys->CustomLayerData, dict);
}
bool
SdfLayer::HasCustomLayerData() const
{
return HasField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->CustomLayerData);
}
void
SdfLayer::ClearCustomLayerData()
{
EraseField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->CustomLayerData);
}
SdfPrimSpecHandle
SdfLayer::GetPseudoRoot() const
{
return SdfPrimSpecHandle(
_idRegistry.Identify(SdfPath::AbsoluteRootPath()));
}
SdfLayer::RootPrimsView
SdfLayer::GetRootPrims() const
{
return GetPseudoRoot()->GetNameChildren();
}
void
SdfLayer::SetRootPrims( const SdfPrimSpecHandleVector &newComps )
{
return GetPseudoRoot()->SetNameChildren(newComps);
}
bool
SdfLayer::InsertRootPrim( const SdfPrimSpecHandle & prim, int index )
{
return GetPseudoRoot()->InsertNameChild(prim, index);
}
void
SdfLayer::RemoveRootPrim(const SdfPrimSpecHandle & prim)
{
GetPseudoRoot()->RemoveNameChild(prim);
}
SdfNameOrderProxy
SdfLayer::GetRootPrimOrder() const
{
return GetPseudoRoot()->GetNameChildrenOrder();
}
void
SdfLayer::SetRootPrimOrder( const vector<TfToken>& names )
{
GetPseudoRoot()->SetNameChildrenOrder(names);
}
void
SdfLayer::InsertInRootPrimOrder( const TfToken & name, int index )
{
GetPseudoRoot()->InsertInNameChildrenOrder(name, index);
}
void
SdfLayer::RemoveFromRootPrimOrder( const TfToken & name )
{
GetPseudoRoot()->RemoveFromNameChildrenOrder(name);
}
void
SdfLayer::RemoveFromRootPrimOrderByIndex(int index)
{
GetPseudoRoot()->RemoveFromNameChildrenOrderByIndex(index);
}
void
SdfLayer::ApplyRootPrimOrder( vector<TfToken>* vec ) const
{
GetPseudoRoot()->ApplyNameChildrenOrder(vec);
}
SdfSubLayerProxy
SdfLayer::GetSubLayerPaths() const
{
boost::shared_ptr<Sdf_ListEditor<SdfSubLayerTypePolicy>>
editor(new Sdf_SubLayerListEditor(_self));
return SdfSubLayerProxy(editor, SdfListOpTypeOrdered);
}
void
SdfLayer::SetSubLayerPaths(const vector<string>& newPaths)
{
GetSubLayerPaths() = newPaths;
}
size_t
SdfLayer::GetNumSubLayerPaths() const
{
return GetSubLayerPaths().size();
}
void
SdfLayer::InsertSubLayerPath(const string& path, int index)
{
SdfSubLayerProxy proxy = GetSubLayerPaths();
if (index == -1) {
index = static_cast<int>(proxy.size());
}
proxy.Insert(index, path);
}
void
SdfLayer::RemoveSubLayerPath(int index)
{
GetSubLayerPaths().Erase(index);
}
SdfLayerOffsetVector
SdfLayer::GetSubLayerOffsets() const
{
return GetFieldAs<SdfLayerOffsetVector>(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->SubLayerOffsets);
}
SdfLayerOffset
SdfLayer::GetSubLayerOffset(int index) const
{
SdfLayerOffsetVector offsets = GetSubLayerOffsets();
if (index < 0 || static_cast<size_t>(index) >= offsets.size()) {
TF_CODING_ERROR("Invalid sublayer index");
return SdfLayerOffset();
}
return offsets[index];
}
void
SdfLayer::SetSubLayerOffset(const SdfLayerOffset& offset, int index)
{
SdfLayerOffsetVector offsets = GetFieldAs<SdfLayerOffsetVector>(
SdfPath::AbsoluteRootPath(), SdfFieldKeys->SubLayerOffsets);
if (index < 0 || static_cast<size_t>(index) >= offsets.size()) {
TF_CODING_ERROR("Invalid sublayer index");
return;
}
offsets[index] = offset;
SetField(SdfPath::AbsoluteRootPath(), SdfFieldKeys->SubLayerOffsets,
VtValue(offsets));
}
bool
SdfLayer::_CanGetSpecAtPath(
const SdfPath& path,
SdfPath* canonicalPath, SdfSpecType* specType) const
{
if (path.IsEmpty()) {
return false;
}
// We need to always call MakeAbsolutePath, even if relativePath is
// already absolute, because we also need to absolutize target paths
// within the path.
SdfPath const *absPath = &path;
if (ARCH_UNLIKELY(!path.IsAbsolutePath() || path.ContainsTargetPath())) {
*canonicalPath = path.MakeAbsolutePath(SdfPath::AbsoluteRootPath());
absPath = canonicalPath;
}
// Grab the object type stored in the SdfData hash table. If no type has
// been set, this path doesn't point to a valid location.
*specType = GetSpecType(*absPath);
return *specType != SdfSpecTypeUnknown;
}
template <class Spec>
SdfHandle<Spec>
SdfLayer::_GetSpecAtPath(const SdfPath& path)
{
SdfPath canonicalPath;
SdfSpecType specType;
if (!_CanGetSpecAtPath(path, &canonicalPath, &specType) ||
!Sdf_SpecType::CanCast(specType, typeid(Spec))) {
return TfNullPtr;
}
if (ARCH_UNLIKELY(!canonicalPath.IsEmpty())) {
return SdfHandle<Spec>(_idRegistry.Identify(canonicalPath));
}
return SdfHandle<Spec>(_idRegistry.Identify(path));
}
SdfSpecHandle
SdfLayer::GetObjectAtPath(const SdfPath &path)
{
// This function is exactly the same as _GetSpecAtPath, but skips the
// CanCast(...) check since all specs can be represented by SdfSpecHandles.
// In addition, this avoids issues when dealing with things like
// relationship target specs where an SdfSpecType value is defined, but
// no C++ SdfSpec class exists. In that case, consumers should still be
// able to get a generic SdfSpecHandle.
SdfPath canonicalPath;
SdfSpecType specType;
if (!_CanGetSpecAtPath(path, &canonicalPath, &specType)) {
return TfNullPtr;
}
if (ARCH_UNLIKELY(!canonicalPath.IsEmpty())) {
return SdfSpecHandle(_idRegistry.Identify(canonicalPath));
}
return SdfSpecHandle(_idRegistry.Identify(path));
}
SdfPrimSpecHandle
SdfLayer::GetPrimAtPath(const SdfPath& path)
{
// Special-case attempts to look up the pseudo-root via this function.
if (path == SdfPath::AbsoluteRootPath()) {
return GetPseudoRoot();
}
return _GetSpecAtPath<SdfPrimSpec>(path);
}
SdfPropertySpecHandle
SdfLayer::GetPropertyAtPath(const SdfPath &path)
{
return _GetSpecAtPath<SdfPropertySpec>(path);
}
SdfAttributeSpecHandle
SdfLayer::GetAttributeAtPath(const SdfPath &path)
{
return _GetSpecAtPath<SdfAttributeSpec>(path);
}
SdfRelationshipSpecHandle
SdfLayer::GetRelationshipAtPath(const SdfPath &path)
{
return _GetSpecAtPath<SdfRelationshipSpec>(path);
}
bool
SdfLayer::PermissionToEdit() const
{
return _permissionToEdit && !IsMuted();
}
bool
SdfLayer::PermissionToSave() const
{
return _permissionToSave &&
!IsAnonymous() &&
!IsMuted() &&
Sdf_CanWriteLayerToPath(GetRealPath());
}
void
SdfLayer::SetPermissionToEdit(bool allow)
{
_permissionToEdit = allow;
}
void
SdfLayer::SetPermissionToSave(bool allow)
{
_permissionToSave = allow;
}
static
bool
_HasObjectAtPath(const SdfLayerHandle& layer, const SdfPath& path)
{
return layer->GetObjectAtPath(path);
}
static
bool
_CanEdit(
const SdfLayerHandle& layer,
const SdfNamespaceEdit& edit,
std::string* detail)
{
if (edit.currentPath.IsPrimPath()) {
if (edit.newPath.IsEmpty()) {
// Remove prim child.
return Sdf_ChildrenUtils<Sdf_PrimChildPolicy>::
CanRemoveChildForBatchNamespaceEdit(
layer, edit.currentPath.GetParentPath(),
edit.currentPath.GetNameToken(),
detail);
}
else {
// Insert prim child.
return Sdf_ChildrenUtils<Sdf_PrimChildPolicy>::
CanMoveChildForBatchNamespaceEdit(
layer, edit.newPath.GetParentPath(),
layer->GetPrimAtPath(edit.currentPath),
edit.newPath.GetNameToken(),
edit.index,
detail);
}
}
else {
if (edit.newPath.IsEmpty()) {
if (edit.currentPath.IsRelationalAttributePath()) {
// Remove relational attribute.
return Sdf_ChildrenUtils<Sdf_AttributeChildPolicy>::
CanRemoveChildForBatchNamespaceEdit(
layer, edit.currentPath.GetParentPath(),
edit.currentPath.GetNameToken(),
detail);
}
else {
// Remove prim property.
return Sdf_ChildrenUtils<Sdf_PropertyChildPolicy>::
CanRemoveChildForBatchNamespaceEdit(
layer, edit.currentPath.GetParentPath(),
edit.currentPath.GetNameToken(),
detail);
}
}
else if (edit.newPath.IsRelationalAttributePath()) {
if (SdfAttributeSpecHandle attr =
layer->GetAttributeAtPath(edit.currentPath)) {
// Move a prim or relational attribute to be a relational
// attribute.
return Sdf_ChildrenUtils<Sdf_AttributeChildPolicy>::
CanMoveChildForBatchNamespaceEdit(
layer, edit.newPath.GetParentPath(),
attr,
edit.newPath.GetNameToken(),
edit.index,
detail);
}
else {
// Trying to make a non-attribute into a relational attribute.
if (detail) {
*detail = "Object is not an attribute";
}
return false;
}
}
else {
// Move a prim property or relational attribute to be a prim
// property
return Sdf_ChildrenUtils<Sdf_PropertyChildPolicy>::
CanMoveChildForBatchNamespaceEdit(
layer, edit.newPath.GetParentPath(),
layer->GetPropertyAtPath(edit.currentPath),
edit.newPath.GetNameToken(),
edit.index,
detail);
}
}
}
static
void
_DoEdit(const SdfLayerHandle& layer, const SdfNamespaceEdit& edit)
{
if (edit.currentPath.IsPrimPath()) {
if (edit.newPath.IsEmpty()) {
// Remove prim child.
Sdf_ChildrenUtils<Sdf_PrimChildPolicy>::
RemoveChildForBatchNamespaceEdit(
layer, edit.currentPath.GetParentPath(),
edit.currentPath.GetNameToken());
}
else {
// Insert prim child.
Sdf_ChildrenUtils<Sdf_PrimChildPolicy>::
MoveChildForBatchNamespaceEdit(
layer, edit.newPath.GetParentPath(),
layer->GetPrimAtPath(edit.currentPath),
edit.newPath.GetNameToken(),
edit.index);
}
}
else {
if (edit.newPath.IsEmpty()) {
if (edit.currentPath.IsRelationalAttributePath()) {
// Remove relational attribute.
Sdf_ChildrenUtils<Sdf_AttributeChildPolicy>::
RemoveChildForBatchNamespaceEdit(
layer, edit.currentPath.GetParentPath(),
edit.currentPath.GetNameToken());
}
else {
// Remove prim property.
Sdf_ChildrenUtils<Sdf_PropertyChildPolicy>::
RemoveChildForBatchNamespaceEdit(
layer, edit.currentPath.GetParentPath(),
edit.currentPath.GetNameToken());
}
}
else {
if (edit.newPath.IsRelationalAttributePath()) {
// Move a prim or relational attribute to be a relational
// attribute.
Sdf_ChildrenUtils<Sdf_AttributeChildPolicy>::
MoveChildForBatchNamespaceEdit(
layer, edit.newPath.GetParentPath(),
layer->GetAttributeAtPath(edit.currentPath),
edit.newPath.GetNameToken(),
edit.index);
}
else {
// Move a prim property or relational attribute to be a prim
// property
Sdf_ChildrenUtils<Sdf_PropertyChildPolicy>::
MoveChildForBatchNamespaceEdit(
layer, edit.newPath.GetParentPath(),
layer->GetPropertyAtPath(edit.currentPath),
edit.newPath.GetNameToken(),
edit.index);
}
}
}
}
SdfNamespaceEditDetail::Result
SdfLayer::CanApply(
const SdfBatchNamespaceEdit& edits,
SdfNamespaceEditDetailVector* details) const
{
SdfNamespaceEditDetail::Result result = SdfNamespaceEditDetail::Okay;
static const bool fixBackpointers = true;
if (!edits.Process(NULL,
std::bind(&_HasObjectAtPath, _self, ph::_1),
std::bind(&_CanEdit, _self, ph::_1, ph::_2),
details, !fixBackpointers)) {
result = CombineError(result);
}
return result;
}
bool
SdfLayer::Apply(const SdfBatchNamespaceEdit& edits)
{
if (!PermissionToEdit()) {
return false;
}
static const bool fixBackpointers = true;
SdfNamespaceEditVector final;
if (!edits.Process(&final,
std::bind(&_HasObjectAtPath, _self, ph::_1),
std::bind(&_CanEdit, _self, ph::_1, ph::_2),
NULL, !fixBackpointers)) {
return false;
}
SdfChangeBlock block;
for (const auto& edit : final) {
_DoEdit(_self, edit);
}
return true;
}
void
SdfLayer::ScheduleRemoveIfInert(const SdfSpec& spec)
{
Sdf_ChangeManager::Get().RemoveSpecIfInert(spec);
}
void
SdfLayer::_RemoveIfInert(const SdfSpec& spec)
{
if (!spec.IsDormant()) {
SdfSpecHandle specHandle(spec);
if (SdfPrimSpecHandle prim =
TfDynamic_cast<SdfPrimSpecHandle>(specHandle)) {
// We only want to call RemovePrimIfInert if the prim itself is
// inert because RemovePrimIfInert first removes any inert children
// before checking if the prim is inert, but we don't want to touch
// the children. We only want to concern ourselves with the
// specified spec without modifying its children first.
if (prim->IsInert()) {
RemovePrimIfInert(prim);
}
}
else if(SdfPropertySpecHandle property =
TfDynamic_cast<SdfPropertySpecHandle>(specHandle)) {
RemovePropertyIfHasOnlyRequiredFields(property);
}
}
}
void
SdfLayer::RemovePrimIfInert(SdfPrimSpecHandle prim)
{
if (prim && _RemoveInertDFS(prim))
_RemoveInertToRootmost(prim);
}
void
SdfLayer::RemovePropertyIfHasOnlyRequiredFields(SdfPropertySpecHandle prop)
{
if (!(prop && prop->HasOnlyRequiredFields()))
return;
if (SdfPrimSpecHandle owner =
TfDynamic_cast<SdfPrimSpecHandle>(prop->GetOwner())) {
owner->RemoveProperty(prop);
_RemoveInertToRootmost(owner);
}
else if (SdfAttributeSpecHandle attr =
TfDynamic_cast<SdfAttributeSpecHandle>(prop)) {
Sdf_ChildrenUtils<Sdf_AttributeChildPolicy>::RemoveChild(
_self, attr->GetPath().GetParentPath(), attr->GetNameToken());
}
else if (SdfRelationshipSpecHandle rel =
TfDynamic_cast<SdfRelationshipSpecHandle>(prop)) {
Sdf_ChildrenUtils<Sdf_RelationshipChildPolicy>::RemoveChild(
_self, rel->GetPath().GetParentPath(), rel->GetNameToken());
}
//XXX: We may want to do something like
// _RemoveInertToRootmost here, but that would currently
// exacerbate bug 23878. Until we have a solution for that bug,
// we won't automatically clean up our parents in this case.
}
void
SdfLayer::RemoveInertSceneDescription()
{
SdfChangeBlock block;
_RemoveInertDFS(GetPseudoRoot());
}
bool
SdfLayer::_RemoveInertDFS(SdfPrimSpecHandle prim)
{
bool inert = prim->IsInert();
if (!inert) {
// Child prims
SdfPrimSpecHandleVector removedChildren;
TF_FOR_ALL(it, prim->GetNameChildren()) {
SdfPrimSpecHandle child = *it;
if (_RemoveInertDFS(child) &&
!SdfIsDefiningSpecifier(child->GetSpecifier()))
removedChildren.push_back(child);
}
TF_FOR_ALL(it, removedChildren) {
prim->RemoveNameChild(*it);
}
// Child prims inside variants
SdfVariantSetsProxy variantSetMap = prim->GetVariantSets();
TF_FOR_ALL(varSetIt, variantSetMap) {
const SdfVariantSetSpecHandle &varSetSpec = varSetIt->second;
const SdfVariantSpecHandleVector &variants =
varSetSpec->GetVariantList();
TF_FOR_ALL(varIt, variants) {
_RemoveInertDFS((*varIt)->GetPrimSpec());
}
}
}
return inert ? inert : prim->IsInert();
}
void
SdfLayer::_RemoveInertToRootmost(SdfPrimSpecHandle prim)
{
while (prim &&
!SdfIsDefiningSpecifier(prim->GetSpecifier()) &&
prim->IsInert()) {
SdfPrimSpecHandle parent = prim->GetRealNameParent();
if (parent) {
parent->RemoveNameChild(prim);
}
// Recurse.
prim = parent;
}
}
bool
SdfLayer::SplitIdentifier(
const string& identifier,
string* layerPath,
FileFormatArguments* arguments)
{
return Sdf_SplitIdentifier(identifier, layerPath, arguments);
}
std::string
SdfLayer::CreateIdentifier(
const string& layerPath,
const FileFormatArguments& arguments)
{
return Sdf_CreateIdentifier(layerPath, arguments);
}
const string&
SdfLayer::GetIdentifier() const
{
return _assetInfo->identifier;
}
void
SdfLayer::SetIdentifier(const string &identifier)
{
TRACE_FUNCTION();
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::SetIdentifier('%s')\n",
identifier.c_str());
string oldLayerPath, oldArguments;
if (!TF_VERIFY(Sdf_SplitIdentifier(
GetIdentifier(), &oldLayerPath, &oldArguments))) {
return;
}
string newLayerPath, newArguments;
if (!Sdf_SplitIdentifier(identifier, &newLayerPath, &newArguments)) {
TF_CODING_ERROR("Invalid identifier '%s'", identifier.c_str());
return;
}
if (oldArguments != newArguments) {
TF_CODING_ERROR(
"Identifier '%s' contains arguments that differ from the layer's "
"current arguments ('%s').",
identifier.c_str(), GetIdentifier().c_str());
return;
}
#if AR_VERSION == 1
// When changing a layer's identifier, assume that relative identifiers are
// relative to the current working directory.
const string absIdentifier = ArGetResolver().IsRelativePath(identifier) ?
TfAbsPath(identifier) : identifier;
#else
// Create an identifier for the layer based on the desired identifier
// that was passed in. Since this may identifier may point to an asset
// that doesn't exist yet, use CreateIdentifierForNewAsset.
const string absIdentifier =
ArGetResolver().CreateIdentifierForNewAsset(identifier);
#endif
const ArResolvedPath oldResolvedPath = GetResolvedPath();
// Hold open a change block to defer identifier-did-change
// notification until the mutex is unlocked.
SdfChangeBlock block;
{
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
_InitializeFromIdentifier(absIdentifier);
}
// If this layer has changed where it's stored, reset the modification
// time. Note that the new identifier may not resolve to an existing
// location, and we get an empty timestamp from the resolver.
// This is OK -- this means the layer hasn't been serialized to this
// new location yet.
const ArResolvedPath newResolvedPath = GetResolvedPath();
if (oldResolvedPath != newResolvedPath) {
_assetModificationTime = ArGetResolver().GetModificationTimestamp(
GetIdentifier(), newResolvedPath);
}
}
#if AR_VERSION == 1
void
SdfLayer::UpdateAssetInfo(const string &fileVersion)
{
TRACE_FUNCTION();
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::UpdateAssetInfo('%s')\n",
fileVersion.c_str());
// Hold open a change block to defer identifier-did-change
// notification until the mutex is unlocked.
SdfChangeBlock block;
{
// If the layer has a resolve info with a non-empty asset name, this
// means that the layer identifier is a search-path to a layer within
// an asset, which last resolved to a pinnable location. Bind the
// original context found in the resolve info within this block so the
// layer's search path identifier can be properly re-resolved within
// _InitializeFromIdentifier.
std::unique_ptr<ArResolverContextBinder> binder;
if (!GetAssetName().empty()) {
binder.reset(new ArResolverContextBinder(
_assetInfo->resolverContext));
}
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
_InitializeFromIdentifier(GetIdentifier(),
/* realPath */ std::string(), fileVersion);
}
}
#else
void
SdfLayer::UpdateAssetInfo()
{
TRACE_FUNCTION();
TF_DEBUG(SDF_LAYER).Msg("SdfLayer::UpdateAssetInfo()\n");
// Hold open a change block to defer identifier-did-change
// notification until the mutex is unlocked.
SdfChangeBlock block;
{
// If the layer has a resolve info with a non-empty asset name, this
// means that the layer identifier is a search-path to a layer within
// an asset, which last resolved to a pinnable location. Bind the
// original context found in the resolve info within this block so the
// layer's search path identifier can be properly re-resolved within
// _InitializeFromIdentifier.
std::unique_ptr<ArResolverContextBinder> binder;
if (!GetAssetName().empty()) {
binder.reset(new ArResolverContextBinder(
_assetInfo->resolverContext));
}
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
_InitializeFromIdentifier(GetIdentifier());
}
}
#endif // AR_VERSION
string
SdfLayer::GetDisplayName() const
{
return GetDisplayNameFromIdentifier(GetIdentifier());
}
const ArResolvedPath&
SdfLayer::GetResolvedPath() const
{
return _assetInfo->resolvedPath;
}
const string&
SdfLayer::GetRealPath() const
{
return _assetInfo->resolvedPath.GetPathString();
}
string
SdfLayer::GetFileExtension() const
{
string ext = Sdf_GetExtension(GetRealPath());
if (ext.empty())
ext = GetFileFormat()->GetPrimaryFileExtension();
return ext;
}
const string&
SdfLayer::GetRepositoryPath() const
{
return _assetInfo->assetInfo.repoPath;
}
const string&
SdfLayer::GetVersion() const
{
return _assetInfo->assetInfo.version;
}
const VtValue&
SdfLayer::GetAssetInfo() const
{
return _assetInfo->assetInfo.resolverInfo;
}
const string&
SdfLayer::GetAssetName() const
{
return _assetInfo->assetInfo.assetName;
}
SdfLayerHints
SdfLayer::GetHints() const
{
// Hints are invalidated by any authoring operation but we don't want to
// incur the cost of resetting the _hints object at authoring time.
// Instead, we return a default SdfLayerHints here if the layer is dirty.
return IsDirty() ? SdfLayerHints{} : _hints;
}
SdfDataRefPtr
SdfLayer::GetMetadata() const
{
SdfDataRefPtr result = TfCreateRefPtr(new SdfData);
SdfPath const &absRoot = SdfPath::AbsoluteRootPath();
// The metadata for this layer is the data at the absolute root path.
// Here, we copy it into 'result'.
//
// XXX: This is copying more than just the metadata. This includes things
// like name children, etc. We should probably be filtering this to
// just fields tagged as metadata in the schema.
result->CreateSpec(absRoot, SdfSpecTypePseudoRoot);
const TfTokenVector tokenVec = ListFields(absRoot);
for (auto const &token : tokenVec) {
const VtValue &value = GetField(absRoot, token);
result->Set(absRoot, token, value);
}
return result;
}
string
SdfLayer::ComputeAbsolutePath(const string &relativePath)
{
if (relativePath.empty()
|| Sdf_IsAnonLayerIdentifier(relativePath)){
return relativePath;
}
// Make it relative to the repository path, if available, so that path
// resolution will work for references.
const string relativeToPath = GetRepositoryPath().empty() ?
GetRealPath() : GetRepositoryPath();
return ArGetResolver().AnchorRelativePath(relativeToPath, relativePath);
}
string
SdfLayer::_GetMutedPath() const
{
return GetRepositoryPath().empty()
? GetIdentifier()
: GetRepositoryPath();
}
set<string>
SdfLayer::GetMutedLayers()
{
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
return *_mutedLayers;
}
void
SdfLayer::SetMuted(bool muted)
{
// XXX Racy...
if (muted == IsMuted()) {
return;
}
if (muted) {
AddToMutedLayers(_GetMutedPath());
}
else {
RemoveFromMutedLayers(_GetMutedPath());
}
}
bool
SdfLayer::IsMuted() const
{
// Read the current muted revision number. If it's up-to-date we return our
// cache. It's possible that this is racy, but the whole thing is racy
// regardless. Even with a pure locking implementation, say we found this
// layer in the muted set -- by the time we return to the caller with
// 'true', some other thread may have removed this layer from the muted set.
size_t curRev = _mutedLayersRevision;
if (ARCH_UNLIKELY(_mutedLayersRevisionCache != curRev)) {
string mutedPath = _GetMutedPath();
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
// Read again, since this is guaranteed to give us the current value
// because we have the lock. _mutedLayersRevision only changes with the
// lock held.
_mutedLayersRevisionCache = _mutedLayersRevision;
_isMutedCache = _mutedLayers->count(mutedPath);
}
return _isMutedCache;
}
/*static*/
bool
SdfLayer::IsMuted(const string &path)
{
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
return _mutedLayers->count(path);
}
/*static*/
void
SdfLayer::AddToMutedLayers(const string &path)
{
bool didChange = false;
{
// Racy...
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
++_mutedLayersRevision;
didChange = _mutedLayers->insert(path).second;
}
if (didChange) {
if (SdfLayerHandle layer = Find(path)) {
if (layer->IsDirty()) {
SdfFileFormatConstPtr format = layer->GetFileFormat();
SdfAbstractDataRefPtr initializedData =
format->InitData(layer->GetFileFormatArguments());
if (layer->_data->StreamsData()) {
// See the discussion in TransferContent()
// about streaming layers; the same concerns
// apply here. We must swap out the actual data
// ownership and tell clients the entire data
// store has changed.
{
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
TF_VERIFY((*_mutedLayerData).find(path) ==
(*_mutedLayerData).end());
(*_mutedLayerData)[path] = layer->_data;
}
// _SetData() takes ownership of initializedData and sends
// change notification.
layer->_SetData(initializedData);
} else {
// Copy the dirty layer data to an in-memory store
// that will be owned by _mutedLayerData.
SdfAbstractDataRefPtr mutedData =
format->InitData(layer->GetFileFormatArguments());
mutedData->CopyFrom(layer->_data);
{
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
TF_VERIFY((*_mutedLayerData).find(path) ==
(*_mutedLayerData).end());
std::swap( (*_mutedLayerData)[path], mutedData );
}
// Mutate the layer's data to the initialized state.
// This enables efficient change processing downstream.
layer->_SetData(initializedData);
}
TF_VERIFY(layer->IsDirty());
} else {
// Reload as muted.
layer->_Reload(/* force */ true);
}
}
SdfNotice::LayerMutenessChanged(path, /* wasMuted = */ true).Send();
}
}
/*static*/
void
SdfLayer::RemoveFromMutedLayers(const string &path)
{
bool didChange = false;
{
// Racy...
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
++_mutedLayersRevision;
didChange = _mutedLayers->erase(path);
}
if (didChange) {
if (SdfLayerHandle layer = Find(path)) {
if (layer->IsDirty()) {
SdfAbstractDataRefPtr mutedData;
{
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
_MutedLayerDataMap::iterator i =
_mutedLayerData->find(path);
if (TF_VERIFY(i != _mutedLayerData->end())) {
std::swap(mutedData, i->second);
_mutedLayerData->erase(i);
}
}
if (TF_VERIFY(mutedData)) {
// If SdfAbstractData::StreamsData() is true, this re-takes
// ownership of the mutedData object. Otherwise, this
// mutates the existing data container to match its
// contents.
layer->_SetData(mutedData);
}
TF_VERIFY(layer->IsDirty());
} else {
// Reload as unmuted.
layer->_Reload(/* force */ true);
}
}
SdfNotice::LayerMutenessChanged(path, /* wasMuted = */ false).Send();
}
}
bool
SdfLayer::_ShouldNotify() const
{
// Only notify if this layer has been successfully initialized.
// (If initialization is not yet complete, do not notify.)
return _initializationWasSuccessful.get_value_or(false);
}
void
SdfLayer::Clear()
{
if (!PermissionToEdit()) {
TF_CODING_ERROR("Clear: Permission denied.");
return;
}
const bool isStreamingLayer = _data->StreamsData();
_SetData(GetFileFormat()->InitData(GetFileFormatArguments()));
if (isStreamingLayer) {
_stateDelegate->_MarkCurrentStateAsDirty();
}
}
bool
SdfLayer::IsDirty() const
{
return (TF_VERIFY(_stateDelegate) ? _stateDelegate->IsDirty() : false);
}
bool
SdfLayer::_UpdateLastDirtinessState() const
{
// Did not change since last call...
if (IsDirty() == _lastDirtyState)
return false;
// It did change, update last saved changed state...
_lastDirtyState = IsDirty();
return true;
}
SdfLayerStateDelegateBasePtr
SdfLayer::GetStateDelegate() const
{
return _stateDelegate;
}
void
SdfLayer::SetStateDelegate(const SdfLayerStateDelegateBaseRefPtr& delegate)
{
// A layer can never have an invalid state delegate, as it relies
// on it to track dirtiness.
if (!delegate) {
TF_CODING_ERROR("Invalid layer state delegate");
return;
}
_stateDelegate->_SetLayer(SdfLayerHandle());
_stateDelegate = delegate;
_stateDelegate->_SetLayer(_self);
if (_lastDirtyState) {
_stateDelegate->_MarkCurrentStateAsDirty();
}
else {
_stateDelegate->_MarkCurrentStateAsClean();
}
}
void
SdfLayer::_MarkCurrentStateAsClean() const
{
if (TF_VERIFY(_stateDelegate)) {
_stateDelegate->_MarkCurrentStateAsClean();
}
if (_UpdateLastDirtinessState()) {
SdfNotice::LayerDirtinessChanged().Send(_self);
}
}
bool
SdfLayer::IsEmpty() const
{
// XXX: What about documentation/frames? I don't
// think these get composed or exposed through composition, so I don't think
// they matter for the sake of this query.
return GetRootPrims().empty() &&
GetRootPrimOrder().empty() &&
GetSubLayerPaths().empty();
}
void
SdfLayer::TransferContent(const SdfLayerHandle& layer)
{
if (!PermissionToEdit()) {
TF_RUNTIME_ERROR("TransferContent of '%s': Permission denied.",
GetDisplayName().c_str());
return;
}
// Two concerns apply here:
//
// If we need to notify about the changes, we need to use the
// _SetData() API to get incremental change notification;
// otherwise we can just blindly copy the SdfAbstractData.
//
// If this is a streaming layer, _SetData will simply take
// ownership of the data object passed to it. We don't want
// multiple layers to be sharing the same data object, so we
// have to make a copy of the data here.
//
bool notify = _ShouldNotify();
bool isStreamingLayer = _data->StreamsData();
SdfAbstractDataRefPtr newData;
if (!notify || isStreamingLayer) {
newData = GetFileFormat()->InitData(GetFileFormatArguments());
newData->CopyFrom(layer->_data);
}
else {
newData = layer->_data;
}
if (notify) {
_SetData(newData, &(layer->GetSchema()));
} else {
_data = newData;
}
// Copy hints from other layer
_hints = layer->_hints;
// If this is a "streaming" layer, we must mark it dirty.
if (isStreamingLayer) {
_stateDelegate->_MarkCurrentStateAsDirty();
}
}
static void
_GatherPrimAssetReferences(const SdfPrimSpecHandle &prim,
set<string> *assetReferences)
{
if (prim != prim->GetLayer()->GetPseudoRoot()) {
// Prim references
for (const SdfReference &ref:
prim->GetReferenceList().GetAddedOrExplicitItems()) {
assetReferences->insert(ref.GetAssetPath());
}
// Prim payloads
for (const SdfPayload &payload:
prim->GetPayloadList().GetAddedOrExplicitItems()) {
assetReferences->insert(payload.GetAssetPath());
}
// Prim variants
SdfVariantSetsProxy variantSetMap = prim->GetVariantSets();
TF_FOR_ALL(varSetIt, variantSetMap) {
const SdfVariantSetSpecHandle &varSetSpec = varSetIt->second;
const SdfVariantSpecHandleVector &variants =
varSetSpec->GetVariantList();
TF_FOR_ALL(varIt, variants) {
_GatherPrimAssetReferences( (*varIt)->GetPrimSpec(),
assetReferences );
}
}
}
// Recurse on nameChildren
TF_FOR_ALL(child, prim->GetNameChildren()) {
_GatherPrimAssetReferences(*child, assetReferences);
}
}
set<string>
SdfLayer::GetExternalReferences() const
{
SdfSubLayerProxy subLayers = GetSubLayerPaths();
set<string> results(subLayers.begin(), subLayers.end());
_GatherPrimAssetReferences(GetPseudoRoot(), &results);
return results;
}
bool
SdfLayer::UpdateExternalReference(
const string &oldLayerPath,
const string &newLayerPath)
{
if (oldLayerPath.empty())
return false;
// Search sublayers and rename if found...
SdfSubLayerProxy subLayers = GetSubLayerPaths();
size_t index = subLayers.Find(oldLayerPath);
if (index != (size_t)-1) {
RemoveSubLayerPath(index);
// If new layer path given, do rename, otherwise it's a delete.
if (!newLayerPath.empty()) {
InsertSubLayerPath(newLayerPath, index);
}
return true; // sublayers are unique, do no more...
}
_UpdateReferencePaths(GetPseudoRoot(), oldLayerPath, newLayerPath);
return true;
}
std::set<std::string>
SdfLayer::GetExternalAssetDependencies() const
{
return _fileFormat->GetExternalAssetDependencies(*this);
}
// ModifyItemEdits() callback that updates a reference's or payload's
// asset path for SdfReferenceListEditor and SdfPayloadListEditor.
template <class RefOrPayloadType>
static boost::optional<RefOrPayloadType>
_UpdateRefOrPayloadPath(
const string &oldLayerPath,
const string &newLayerPath,
const RefOrPayloadType &refOrPayload)
{
if (refOrPayload.GetAssetPath() == oldLayerPath) {
// Delete if new layer path is empty, otherwise rename.
if (newLayerPath.empty()) {
return boost::optional<RefOrPayloadType>();
} else {
RefOrPayloadType updatedRefOrPayload = refOrPayload;
updatedRefOrPayload.SetAssetPath(newLayerPath);
return updatedRefOrPayload;
}
}
return refOrPayload;
}
void
SdfLayer::_UpdateReferencePaths(
const SdfPrimSpecHandle &prim,
const string &oldLayerPath,
const string &newLayerPath)
{
TF_AXIOM(!oldLayerPath.empty());
// Prim references
prim->GetReferenceList().ModifyItemEdits(std::bind(
&_UpdateRefOrPayloadPath<SdfReference>, oldLayerPath, newLayerPath,
ph::_1));
// Prim payloads
prim->GetPayloadList().ModifyItemEdits(std::bind(
&_UpdateRefOrPayloadPath<SdfPayload>, oldLayerPath, newLayerPath,
ph::_1));
// Prim variants
SdfVariantSetsProxy variantSetMap = prim->GetVariantSets();
for (const auto& setNameAndSpec : variantSetMap) {
const SdfVariantSetSpecHandle &varSetSpec = setNameAndSpec.second;
const SdfVariantSpecHandleVector &variants =
varSetSpec->GetVariantList();
for (const auto& variantSpec : variants) {
_UpdateReferencePaths(
variantSpec->GetPrimSpec(), oldLayerPath, newLayerPath);
}
}
// Recurse on nameChildren
for (const auto& primSpec : prim->GetNameChildren()) {
_UpdateReferencePaths(primSpec, oldLayerPath, newLayerPath);
}
}
/*static*/
void
SdfLayer::DumpLayerInfo()
{
tbb::queuing_rw_mutex::scoped_lock
lock(_GetLayerRegistryMutex(), /*write=*/false);
std::cerr << "Layer Registry Dump:" << std::endl
<< *_layerRegistry << std::endl;
}
bool
SdfLayer::WriteDataFile(const string &filename)
{
std::ofstream file(filename.c_str());
_data->WriteToStream(file);
return file.good();
}
/*static*/
set<SdfLayerHandle>
SdfLayer::GetLoadedLayers()
{
tbb::queuing_rw_mutex::scoped_lock
lock(_GetLayerRegistryMutex(), /*write=*/false);
return _layerRegistry->GetLayers();
}
/* static */
template <class Lock>
SdfLayerRefPtr
SdfLayer::_OpenLayerAndUnlockRegistry(
Lock &lock,
const _FindOrOpenLayerInfo& info,
bool metadataOnly)
{
TfAutoMallocTag2 tag("Sdf", "SdfLayer::_OpenLayerAndUnlockRegistry "
+ info.identifier);
TRACE_FUNCTION();
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::_OpenLayerAndUnlockRegistry('%s', '%s', '%s', '%s', "
"metadataOnly=%s)\n",
info.identifier.c_str(), info.layerPath.c_str(),
info.fileFormat ?
info.fileFormat->GetFormatId().GetText() : "unknown file format",
TfStringify(info.fileFormatArgs).c_str(),
metadataOnly ? "True" : "False");
// XXX: Is this really a coding error? SdfLayer avoids issuing errors if
// given a non-existent file, for instance. Should we be following the
// same policy here?
if (!info.fileFormat) {
TF_CODING_ERROR("Cannot determine file format for @%s@",
info.identifier.c_str());
lock.release();
return TfNullPtr;
}
// Create a new layer of the appropriate format.
SdfLayerRefPtr layer = _CreateNewWithFormat(
info.fileFormat, info.identifier, info.resolvedLayerPath,
info.assetInfo, info.fileFormatArgs);
// The layer constructor sets _initializationComplete to false, which will
// block any other threads trying to use the layer until we complete
// initialization. But now that the layer is in the registry, we release
// the registry lock to avoid blocking progress of threads working with
// other layers.
TF_VERIFY(_layerRegistry->
FindByIdentifier(layer->GetIdentifier()) == layer,
"Could not find %s", layer->GetIdentifier().c_str());
lock.release();
// From this point on, we need to be sure to call
// layer->_FinishInitialization() with either success or failure,
// in order to unblock any other threads waiting for initialization
// to finish.
if (info.isAnonymous != layer->IsAnonymous()) {
if (info.isAnonymous) {
TF_CODING_ERROR("Opened anonymous layer ('%s' with format id '%s') "
"but resulting layer is not anonymous.",
info.identifier.c_str(),
info.fileFormat->GetFormatId().GetText());
}
else {
TF_CODING_ERROR("Opened layer without anonymous prefix "
"('%s' with format id '%s') but resulting layer is "
"anonymous.",
info.identifier.c_str(),
info.fileFormat->GetFormatId().GetText());
}
layer->_FinishInitialization(/* success = */ false);
return TfNullPtr;
}
// This is in support of specialized file formats that piggyback
// on anonymous layer functionality. If the layer is anonymous,
// pass the original assetPath to the reader, otherwise, pass the
// resolved path of the layer.
const string readFilePath =
info.isAnonymous ? info.layerPath : info.resolvedLayerPath;
if (!layer->IsMuted()) {
// Run the file parser to read in the file contents.
if (!layer->_Read(info.identifier, readFilePath, metadataOnly)) {
layer->_FinishInitialization(/* success = */ false);
return TfNullPtr;
}
}
// Grab the modification time even if layer is muted and not being
// read. Since a muted layer may become unmuted later, there needs
// to be a non-empty timestamp so it will not be misidentified as
// a newly created non-serialized layer.
if (!info.isAnonymous) {
// Grab modification timestamp.
VtValue timestamp = ArGetResolver().GetModificationTimestamp(
info.identifier, ArResolvedPath(readFilePath));
if (timestamp.IsEmpty()) {
TF_CODING_ERROR(
"Unable to get modification timestamp for '%s (%s)'",
info.identifier.c_str(), readFilePath.c_str());
layer->_FinishInitialization(/* success = */ false);
return TfNullPtr;
}
layer->_assetModificationTime.Swap(timestamp);
}
// Store any external asset dependencies so we have an initial state to
// compare during reload.
layer->_externalAssetModificationTimes =
_GetExternalAssetModificationTimes(*layer);
layer->_MarkCurrentStateAsClean();
// Layer initialization is complete.
layer->_FinishInitialization(/* success = */ true);
return layer;
}
bool
SdfLayer::HasSpec(const SdfPath& path) const
{
return _data->HasSpec(path);
}
SdfSpecType
SdfLayer::GetSpecType(const SdfPath& path) const
{
return _data->GetSpecType(path);
}
vector<TfToken>
SdfLayer::ListFields(const SdfPath& path) const
{
return _ListFields(GetSchema(), *get_pointer(_data), path);
}
vector<TfToken>
SdfLayer::_ListFields(SdfSchemaBase const &schema,
SdfAbstractData const &data, const SdfPath& path)
{
// Invoke List() on the underlying data implementation but be sure to
// include all required fields too.
// Collect the list from the data implemenation.
vector<TfToken> dataList = data.List(path);
// Determine spec type. If unknown, return early.
SdfSpecType specType = data.GetSpecType(path);
if (ARCH_UNLIKELY(specType == SdfSpecTypeUnknown)) {
return dataList;
}
// Collect required fields.
vector<TfToken> const &req = schema.GetRequiredFields(specType);
// Union them together, but retain order of dataList, since it influences
// the output ordering in some file writers.
auto dataListBegin = dataList.begin(), dataListEnd = dataList.end();
bool mightAlloc = (dataList.size() + req.size()) > dataList.capacity();
for (size_t reqIdx = 0, reqSz = req.size(); reqIdx != reqSz; ++reqIdx) {
TfToken const &reqName = req[reqIdx];
auto iter = std::find(dataListBegin, dataListEnd, reqName);
if (iter == dataListEnd) {
// If the required field name is not already present, append it.
// Make sure we have capacity for all required fields so we do no
// more than one additional allocation here.
if (mightAlloc && dataList.size() == dataList.capacity()) {
dataList.reserve(dataList.size() + (reqSz - reqIdx));
dataListBegin = dataList.begin(), dataListEnd = dataList.end();
mightAlloc = false;
}
dataList.push_back(reqName);
}
}
return dataList;
}
SdfSchema::FieldDefinition const *
SdfLayer::_GetRequiredFieldDef(const SdfPath &path,
const TfToken &fieldName,
SdfSpecType specType) const
{
SdfSchemaBase const &schema = GetSchema();
if (ARCH_UNLIKELY(schema.IsRequiredFieldName(fieldName))) {
// Get the spec definition.
if (specType == SdfSpecTypeUnknown) {
specType = GetSpecType(path);
}
if (SdfSchema::SpecDefinition const *
specDef = schema.GetSpecDefinition(specType)) {
// If this field is required for this spec type, look up the
// field definition.
if (specDef->IsRequiredField(fieldName)) {
return schema.GetFieldDefinition(fieldName);
}
}
}
return nullptr;
}
SdfSchema::FieldDefinition const *
SdfLayer::_GetRequiredFieldDef(const SdfSchemaBase &schema,
const TfToken &fieldName,
SdfSpecType specType)
{
if (ARCH_UNLIKELY(schema.IsRequiredFieldName(fieldName))) {
if (SdfSchema::SpecDefinition const *
specDef = schema.GetSpecDefinition(specType)) {
// If this field is required for this spec type, look up the
// field definition.
if (specDef->IsRequiredField(fieldName)) {
return schema.GetFieldDefinition(fieldName);
}
}
}
return nullptr;
}
bool
SdfLayer::_HasField(const SdfSchemaBase &schema,
const SdfAbstractData &data,
const SdfPath& path,
const TfToken& fieldName,
VtValue *value)
{
SdfSpecType specType;
if (data.HasSpecAndField(path, fieldName, value, &specType)) {
return true;
}
if (specType == SdfSpecTypeUnknown) {
return false;
}
// Otherwise if this is a required field, and the data has a spec here,
// return the fallback value.
if (SdfSchema::FieldDefinition const *def =
_GetRequiredFieldDef(schema, fieldName, specType)) {
if (value)
*value = def->GetFallbackValue();
return true;
}
return false;
}
bool
SdfLayer::HasField(const SdfPath& path, const TfToken& fieldName,
VtValue *value) const
{
SdfSpecType specType;
if (_data->HasSpecAndField(path, fieldName, value, &specType)) {
return true;
}
if (specType == SdfSpecTypeUnknown) {
return false;
}
// Otherwise if this is a required field, and the data has a spec here,
// return the fallback value.
if (SdfSchema::FieldDefinition const *def =
_GetRequiredFieldDef(path, fieldName, specType)) {
if (value)
*value = def->GetFallbackValue();
return true;
}
return false;
}
bool
SdfLayer::HasField(const SdfPath& path, const TfToken& fieldName,
SdfAbstractDataValue *value) const
{
SdfSpecType specType;
if (_data->HasSpecAndField(path, fieldName, value, &specType)) {
return true;
}
if (specType == SdfSpecTypeUnknown) {
return false;
}
// Otherwise if this is a required field, and the data has a spec here,
// return the fallback value.
if (SdfSchema::FieldDefinition const *def =
_GetRequiredFieldDef(path, fieldName, specType)) {
if (value)
return value->StoreValue(def->GetFallbackValue());
return true;
}
return false;
}
bool
SdfLayer::HasFieldDictKey(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath,
VtValue *value) const
{
if (_data->HasDictKey(path, fieldName, keyPath, value))
return true;
// Otherwise if this is a required field, and the data has a spec here,
// return the fallback value.
if (SdfSchema::FieldDefinition const *def =
_GetRequiredFieldDef(path, fieldName)) {
VtValue const &fallback = def->GetFallbackValue();
if (fallback.IsHolding<VtDictionary>()) {
VtDictionary const &dict = fallback.UncheckedGet<VtDictionary>();
if (VtValue const *v = dict.GetValueAtPath(keyPath)) {
if (value)
*value = *v;
return true;
}
}
}
return false;
}
bool
SdfLayer::HasFieldDictKey(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath,
SdfAbstractDataValue *value) const
{
if (_data->HasDictKey(path, fieldName, keyPath, value))
return true;
// Otherwise if this is a required field, and the data has a spec here,
// return the fallback value.
if (SdfSchema::FieldDefinition const *def =
_GetRequiredFieldDef(path, fieldName)) {
VtValue const &fallback = def->GetFallbackValue();
if (fallback.IsHolding<VtDictionary>()) {
VtDictionary const &dict = fallback.UncheckedGet<VtDictionary>();
if (VtValue const *v = dict.GetValueAtPath(keyPath)) {
if (value)
return value->StoreValue(*v);
return true;
}
}
}
return false;
}
VtValue
SdfLayer::GetField(const SdfPath& path,
const TfToken& fieldName) const
{
VtValue result;
HasField(path, fieldName, &result);
return result;
}
VtValue
SdfLayer::_GetField(const SdfSchemaBase &schema,
const SdfAbstractData &data,
const SdfPath& path,
const TfToken& fieldName)
{
VtValue result;
_HasField(schema, data, path, fieldName, &result);
return result;
}
VtValue
SdfLayer::GetFieldDictValueByKey(const SdfPath& path,
const TfToken& fieldName,
const TfToken &keyPath) const
{
VtValue result;
HasFieldDictKey(path, fieldName, keyPath, &result);
return result;
}
static bool
_IsValidFieldForLayer(
const SdfLayer& layer, const SdfPath& path,
const TfToken& fieldName)
{
return layer.GetSchema().IsValidFieldForSpec(
fieldName, layer.GetSpecType(path));
}
void
SdfLayer::SetField(const SdfPath& path, const TfToken& fieldName,
const VtValue& value)
{
if (value.IsEmpty())
return EraseField(path, fieldName);
if (ARCH_UNLIKELY(!PermissionToEdit())) {
TF_CODING_ERROR("Cannot set %s on <%s>. Layer @%s@ is not editable.",
fieldName.GetText(), path.GetText(),
GetIdentifier().c_str());
return;
}
if (ARCH_UNLIKELY(_validateAuthoring) &&
!_IsValidFieldForLayer(*this, path, fieldName)) {
TF_ERROR(SdfAuthoringErrorUnrecognizedFields,
"Cannot set %s on <%s>. Field is not valid for layer @%s@.",
fieldName.GetText(), path.GetText(),
GetIdentifier().c_str());
return;
}
VtValue oldValue = GetField(path, fieldName);
if (value != oldValue)
_PrimSetField(path, fieldName, value, &oldValue);
}
void
SdfLayer::SetField(const SdfPath& path, const TfToken& fieldName,
const SdfAbstractDataConstValue& value)
{
if (value.IsEqual(VtValue()))
return EraseField(path, fieldName);
if (ARCH_UNLIKELY(!PermissionToEdit())) {
TF_CODING_ERROR("Cannot set %s on <%s>. Layer @%s@ is not editable.",
fieldName.GetText(), path.GetText(),
GetIdentifier().c_str());
return;
}
if (ARCH_UNLIKELY(_validateAuthoring) &&
!_IsValidFieldForLayer(*this, path, fieldName)) {
TF_ERROR(SdfAuthoringErrorUnrecognizedFields,
"Cannot set %s on <%s>. Field is not valid for layer @%s@.",
fieldName.GetText(), path.GetText(),
GetIdentifier().c_str());
return;
}
VtValue oldValue = GetField(path, fieldName);
if (!value.IsEqual(oldValue))
_PrimSetField(path, fieldName, value, &oldValue);
}
void
SdfLayer::SetFieldDictValueByKey(const SdfPath& path,
const TfToken& fieldName,
const TfToken& keyPath,
const VtValue& value)
{
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot set %s:%s on <%s>. Layer @%s@ is not editable.",
fieldName.GetText(), keyPath.GetText(),
path.GetText(),
GetIdentifier().c_str());
return;
}
if (ARCH_UNLIKELY(_validateAuthoring) &&
!_IsValidFieldForLayer(*this, path, fieldName)) {
TF_ERROR(SdfAuthoringErrorUnrecognizedFields,
"Cannot set %s:%s on <%s>. Field is not valid for layer @%s@.",
fieldName.GetText(), keyPath.GetText(),
path.GetText(), GetIdentifier().c_str());
return;
}
VtValue oldValue = GetFieldDictValueByKey(path, fieldName, keyPath);
if (value == oldValue)
return;
_PrimSetFieldDictValueByKey(path, fieldName, keyPath, value, &oldValue);
}
void
SdfLayer::SetFieldDictValueByKey(const SdfPath& path,
const TfToken& fieldName,
const TfToken& keyPath,
const SdfAbstractDataConstValue& value)
{
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot set %s:%s on <%s>. Layer @%s@ is not editable.",
fieldName.GetText(), keyPath.GetText(),
path.GetText(),
GetIdentifier().c_str());
return;
}
if (ARCH_UNLIKELY(_validateAuthoring) &&
!_IsValidFieldForLayer(*this, path, fieldName)) {
TF_ERROR(SdfAuthoringErrorUnrecognizedFields,
"Cannot set %s:%s on <%s>. Field is not valid for layer @%s@.",
fieldName.GetText(), keyPath.GetText(),
path.GetText(), GetIdentifier().c_str());
return;
}
VtValue oldValue = GetFieldDictValueByKey(path, fieldName, keyPath);
if (value.IsEqual(oldValue))
return;
_PrimSetFieldDictValueByKey(path, fieldName, keyPath, value, &oldValue);
}
void
SdfLayer::EraseField(const SdfPath& path, const TfToken& fieldName)
{
if (ARCH_UNLIKELY(!PermissionToEdit())) {
TF_CODING_ERROR("Cannot erase %s on <%s>. Layer @%s@ is not editable.",
fieldName.GetText(), path.GetText(),
GetIdentifier().c_str());
return;
}
if (!_data->Has(path, fieldName)) {
return;
}
// If this is a required field, only perform the set if the current value
// differs from the fallback. Required fields behave as if they're always
// authored, so the effect of an "erase" is to set the value to the fallback
// value.
if (SdfSchema::FieldDefinition const *def =
_GetRequiredFieldDef(path, fieldName)) {
if (GetField(path, fieldName) == def->GetFallbackValue())
return;
}
// XXX:
// Note that with this implementation, erasing a field and undoing that
// operation will not restore the underlying SdfData exactly to its
// previous state. Specifically, this may cause the order of the fields
// for the given spec to change. There are no semantics attached to this
// ordering, so this should hopefully be OK.
_PrimSetField(path, fieldName, VtValue());
}
void
SdfLayer::EraseFieldDictValueByKey(const SdfPath& path,
const TfToken& fieldName,
const TfToken &keyPath)
{
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot erase %s:%s on <%s>. Layer @%s@ is not editable.",
fieldName.GetText(), keyPath.GetText(),
path.GetText(),
GetIdentifier().c_str());
return;
}
if (!_data->HasDictKey(path, fieldName, keyPath,
static_cast<VtValue *>(NULL))) {
return;
}
// XXX:
// Note that with this implementation, erasing a field and undoing that
// operation will not restore the underlying SdfData exactly to its
// previous state. Specifically, this may cause the order of the fields
// for the given spec to change. There are no semantics attached to this
// ordering, so this should hopefully be OK.
_PrimSetFieldDictValueByKey(path, fieldName, keyPath, VtValue());
}
SdfAbstractDataConstPtr
SdfLayer::_GetData() const
{
return _data;
}
void
SdfLayer::_SwapData(SdfAbstractDataRefPtr &data)
{
_data.swap(data);
}
void
SdfLayer::_SetData(const SdfAbstractDataPtr &newData,
const SdfSchemaBase *newDataSchema)
{
TRACE_FUNCTION();
TF_DESCRIBE_SCOPE("Setting layer data");
// Guard against setting an empty SdfData, which is invalid.
TF_VERIFY(!newData->IsEmpty() );
// This code below performs a series of specific edits to mutate _data
// to match newData. This approach provides fine-grained change
// notification, which allows more efficient invalidation in clients
// of Sd. Do all this in a single changeblock.
SdfChangeBlock block;
// If this layer streams its data on demand, we cannot perform
// fine-grained change notification because that would cause all of
// the data in the layer to be streamed in from disk.
// So, all we can do is move the new data into place and
// notify the world that this layer may have changed arbitrarily.
if (_data->StreamsData()) {
_data = newData;
Sdf_ChangeManager::Get().DidReplaceLayerContent(_self);
return;
}
// Remove specs that no longer exist or whose required fields changed.
{
// Collect specs to delete, ordered by namespace.
struct _SpecsToDelete : public SdfAbstractDataSpecVisitor {
_SpecsToDelete(const SdfAbstractDataPtr& newData_)
: newData(newData_) { }
virtual bool VisitSpec(
const SdfAbstractData& oldData, const SdfPath& path)
{
if (!newData->HasSpec(path) ||
(newData->GetSpecType(path) != oldData.GetSpecType(path))) {
paths.insert(path);
}
return true;
}
virtual void Done(const SdfAbstractData&)
{
// Do nothing
}
const SdfAbstractDataRefPtr newData;
std::set<SdfPath> paths;
};
_SpecsToDelete specsToDelete(newData);
_data->VisitSpecs(&specsToDelete);
// Delete specs bottom-up to provide optimal diffs.
// Erase fields first, to take advantage of the more efficient
// update possible when removing inert specs.
TF_REVERSE_FOR_ALL(i, specsToDelete.paths) {
const SdfPath &path = *i;
std::vector<TfToken> fields = ListFields(path);
SdfSpecType specType = _data->GetSpecType(path);
const SdfSchema::SpecDefinition* specDefinition =
GetSchema().GetSpecDefinition(specType);
TF_FOR_ALL(field, fields) {
if (!specDefinition->IsRequiredField(*field))
_PrimSetField(path, *field, VtValue());
}
_PrimDeleteSpec(*i, _IsInertSubtree(*i));
}
}
// Create new specs.
{
// Collect specs to create, ordered by namespace.
struct _SpecsToCreate : public SdfAbstractDataSpecVisitor {
_SpecsToCreate(const SdfAbstractData& oldData_)
: oldData(oldData_) { }
virtual bool VisitSpec(
const SdfAbstractData& newData, const SdfPath& path)
{
if (!oldData.HasSpec(path)) {
paths.insert(path);
}
return true;
}
virtual void Done(const SdfAbstractData&)
{
// Do nothing
}
const SdfAbstractData& oldData;
std::set<SdfPath> paths;
};
_SpecsToCreate specsToCreate(*boost::get_pointer(_data));
newData->VisitSpecs(&specsToCreate);
bool differentSchema = newDataSchema && newDataSchema != &GetSchema();
SdfPath unrecognizedSpecTypePaths[SdfNumSpecTypes];
// Create specs top-down to provide optimal diffs.
TF_FOR_ALL(i, specsToCreate.paths) {
const SdfPath& path = *i;
// Determine if the spec is inert based on its fields.
//
// XXX We should consolidate this with the logic
// in the spec _New() methods.
bool inert = false;
if (path.IsPrimPath()) {
// Prims are considered inert if they are an 'over' with
// no typename. Make sure we specify the expected fallback
// values in case newData does not explicitly store a value
// for these fields.
inert =
(newData->GetAs<SdfSpecifier>(path, SdfFieldKeys->Specifier,
SdfSpecifierOver)
== SdfSpecifierOver)
&& (newData->GetAs<TfToken>(path, SdfFieldKeys->TypeName,
TfToken())
.IsEmpty());
} else if (path.IsPropertyPath()) {
// Properties are considered inert if they are custom.
inert = !newData->GetAs<bool>(path, SdfFieldKeys->Custom,
false);
}
SdfSpecType specType = newData->GetSpecType(path);
// If this is a cross-schema _SetData call, check to see if the spec
// type is known to this layer's schema. If not, skip creating it
// and record it to issue an error later.
if (differentSchema && !GetSchema().GetSpecDefinition(specType)) {
// Record the path where this spec type was first encountered.
if (unrecognizedSpecTypePaths[specType].IsEmpty()) {
unrecognizedSpecTypePaths[specType] = path;
}
}
else {
_PrimCreateSpec(path, specType, inert);
}
}
// If there were unrecognized specTypes, issue an error.
if (differentSchema) {
vector<string> specDescrs;
for (int i = 0; i != SdfSpecTypeUnknown; ++i) {
if (unrecognizedSpecTypePaths[i].IsEmpty()) {
continue;
}
specDescrs.push_back(
TfStringPrintf(
"'%s' first seen at <%s>",
TfStringify(static_cast<SdfSpecType>(i)).c_str(),
unrecognizedSpecTypePaths[i].GetAsString().c_str()));
}
if (!specDescrs.empty()) {
TF_ERROR(SdfAuthoringErrorUnrecognizedSpecType,
"Omitted unrecognized spec types setting data on "
"@%s@: %s", GetIdentifier().c_str(),
TfStringJoin(specDescrs, "; ").c_str());
}
}
}
// Update spec fields.
{
struct _SpecUpdater : public SdfAbstractDataSpecVisitor {
_SpecUpdater(SdfLayer* layer_,
const SdfSchemaBase &newDataSchema_)
: layer(layer_)
, newDataSchema(newDataSchema_) {}
virtual bool VisitSpec(
const SdfAbstractData& newData, const SdfPath& path)
{
const TfTokenVector oldFields = layer->ListFields(path);
const TfTokenVector newFields =
_ListFields(newDataSchema, newData, path);
const SdfSchemaBase &thisLayerSchema = layer->GetSchema();
bool differentSchema = &thisLayerSchema != &newDataSchema;
// If this layer has a different schema from newDataSchema, then
// it's possible there is no corresponding spec for the path, in
// case the spec type is not supported. Check for this, and
// skip field processing if so.
if (differentSchema && !layer->HasSpec(path)) {
return true;
}
// Remove empty fields.
for (TfToken const &field: oldFields) {
// This is O(N^2) in number of fields in each spec, but
// we expect a small max N, around 10.
if (std::find(newFields.begin(), newFields.end(), field)
== newFields.end()) {
layer->_PrimSetField(path, field, VtValue());
}
}
// Set field values.
for (TfToken const &field: newFields) {
VtValue newValue =
_GetField(newDataSchema, newData, path, field);
VtValue oldValue = layer->GetField(path, field);
if (oldValue != newValue) {
if (differentSchema && oldValue.IsEmpty() &&
!thisLayerSchema.IsValidFieldForSpec(
field, layer->GetSpecType(path))) {
// This field might not be valid for the target
// schema. If that's the case record it (if it's
// not already recorded) and skip setting it.
unrecognizedFields.emplace(field, path);
}
else {
layer->_PrimSetField(path, field,
newValue, &oldValue);
}
}
}
return true;
}
virtual void Done(const SdfAbstractData&)
{
// Do nothing
}
SdfLayer* layer;
const SdfSchemaBase &newDataSchema;
std::map<TfToken, SdfPath> unrecognizedFields;
};
// If no newDataSchema is supplied, we assume the newData adheres to
// this layer's schema.
_SpecUpdater updater(
this, newDataSchema ? *newDataSchema : GetSchema());
newData->VisitSpecs(&updater);
// If there were unrecognized fields, report an error.
if (!updater.unrecognizedFields.empty()) {
vector<string> fieldDescrs;
fieldDescrs.reserve(updater.unrecognizedFields.size());
for (std::pair<TfToken, SdfPath> const &tokenPath:
updater.unrecognizedFields) {
fieldDescrs.push_back(
TfStringPrintf("'%s' first seen at <%s>",
tokenPath.first.GetText(),
tokenPath.second.GetAsString().c_str()));
}
TF_ERROR(SdfAuthoringErrorUnrecognizedFields,
"Omitted unrecognized fields setting data on @%s@: %s",
GetIdentifier().c_str(),
TfStringJoin(fieldDescrs, "; ").c_str());
}
}
// Verify that the result matches.
// TODO Enable in debug builds.
if (0) {
TRACE_SCOPE("SdfLayer::_SetData - Verify result");
TF_VERIFY(_data->Equals(newData));
}
}
template <class T>
void
SdfLayer::_PrimSetField(const SdfPath& path,
const TfToken& fieldName,
const T& value,
const VtValue *oldValuePtr,
bool useDelegate)
{
if (useDelegate && TF_VERIFY(_stateDelegate)) {
_stateDelegate->SetField(path, fieldName, value, oldValuePtr);
return;
}
const VtValue& oldValue =
oldValuePtr ? *oldValuePtr : GetField(path, fieldName);
const VtValue& newValue = _GetVtValue(value);
// Send notification when leaving the change block.
SdfChangeBlock block;
Sdf_ChangeManager::Get().DidChangeField(
_self, path, fieldName, oldValue, newValue);
_data->Set(path, fieldName, value);
}
template void SdfLayer::_PrimSetField(
const SdfPath&, const TfToken&,
const VtValue&, const VtValue *, bool);
template void SdfLayer::_PrimSetField(
const SdfPath&, const TfToken&,
const SdfAbstractDataConstValue&, const VtValue *, bool);
template <class T>
void
SdfLayer::_PrimPushChild(const SdfPath& parentPath,
const TfToken& fieldName,
const T& value,
bool useDelegate)
{
if (!HasField(parentPath, fieldName)) {
_PrimSetField(parentPath, fieldName,
VtValue(std::vector<T>(1, value)));
return;
}
if (useDelegate && TF_VERIFY(_stateDelegate)) {
_stateDelegate->PushChild(parentPath, fieldName, value);
return;
}
// A few efficiency notes:
//
// - We want to push the child onto the existing vector. Since
// VtValue is copy-on-write, we avoid incurring a copy fault
// by retrieving the value from the data store and then
// erasing the field before modifying the vector. Similarly,
// we swap the vector<T> out of the type-erased VtValue box,
// modify that, then swap it back in.
//
// - Do not record a field change entry with Sdf_ChangeManager.
// Doing so would require us to provide both the old & new
// values for the vector. Note tha the the changelist protocol
// already has special affordances for spec add/remove events,
// and child fields are essentially an implementation detail.
//
VtValue box = _data->Get(parentPath, fieldName);
_data->Erase(parentPath, fieldName);
std::vector<T> vec;
if (box.IsHolding<std::vector<T>>()) {
box.Swap(vec);
} else {
// If the value isn't a vector, we replace it with an empty one.
}
vec.push_back(value);
box.Swap(vec);
_data->Set(parentPath, fieldName, box);
}
template void SdfLayer::_PrimPushChild(
const SdfPath&, const TfToken&,
const TfToken &, bool);
template void SdfLayer::_PrimPushChild(
const SdfPath&, const TfToken&,
const SdfPath &, bool);
template <class T>
void
SdfLayer::_PrimPopChild(const SdfPath& parentPath,
const TfToken& fieldName,
bool useDelegate)
{
if (useDelegate && TF_VERIFY(_stateDelegate)) {
std::vector<T> vec = GetFieldAs<std::vector<T> >(parentPath, fieldName);
if (!vec.empty()) {
T oldValue = vec.back();
_stateDelegate->PopChild(parentPath, fieldName, oldValue);
} else {
TF_CODING_ERROR("SdfLayer::_PrimPopChild failed: field %s is "
"empty vector", fieldName.GetText());
}
return;
}
// See efficiency notes in _PrimPushChild().
VtValue box = _data->Get(parentPath, fieldName);
_data->Erase(parentPath, fieldName);
if (!box.IsHolding<std::vector<T>>()) {
TF_CODING_ERROR("SdfLayer::_PrimPopChild failed: field %s is "
"non-vector", fieldName.GetText());
return;
}
std::vector<T> vec;
box.Swap(vec);
if (vec.empty()) {
TF_CODING_ERROR("SdfLayer::_PrimPopChild failed: %s is empty",
fieldName.GetText());
return;
}
vec.pop_back();
box.Swap(vec);
_data->Set(parentPath, fieldName, box);
}
template void SdfLayer::_PrimPopChild<TfToken>(
const SdfPath&, const TfToken&, bool);
template void SdfLayer::_PrimPopChild<SdfPath>(
const SdfPath&, const TfToken&, bool);
template <class T>
void
SdfLayer::_PrimSetFieldDictValueByKey(const SdfPath& path,
const TfToken& fieldName,
const TfToken& keyPath,
const T& value,
const VtValue *oldValuePtr,
bool useDelegate)
{
if (useDelegate && TF_VERIFY(_stateDelegate)) {
_stateDelegate->SetFieldDictValueByKey(
path, fieldName, keyPath, value, oldValuePtr);
return;
}
// Send notification when leaving the change block.
SdfChangeBlock block;
// This can't only use oldValuePtr currently, since we need the entire
// dictionary, not just they key being set. If we augment change
// notification to be as granular as dict-key-path, we could use it.
VtValue oldValue = GetField(path, fieldName);
_data->SetDictValueByKey(path, fieldName, keyPath, value);
VtValue newValue = GetField(path, fieldName);
Sdf_ChangeManager::Get().DidChangeField(
_self, path, fieldName, oldValue, newValue);
}
template void SdfLayer::_PrimSetFieldDictValueByKey(
const SdfPath&, const TfToken&, const TfToken &,
const VtValue&, const VtValue *, bool);
template void SdfLayer::_PrimSetFieldDictValueByKey(
const SdfPath&, const TfToken&, const TfToken &,
const SdfAbstractDataConstValue&, const VtValue *, bool);
bool
SdfLayer::_MoveSpec(const SdfPath &oldPath, const SdfPath &newPath)
{
TRACE_FUNCTION();
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot move <%s> to <%s>. Layer @%s@ is not editable.",
oldPath.GetText(), newPath.GetText(),
GetIdentifier().c_str());
return false;
}
if (oldPath.IsEmpty() || newPath.IsEmpty()) {
TF_CODING_ERROR("Cannot move <%s> to <%s>. "
"Source and destination must be non-empty paths",
oldPath.GetText(), newPath.GetText());
return false;
}
if (oldPath.HasPrefix(newPath) || newPath.HasPrefix(oldPath)) {
TF_CODING_ERROR("Cannot move <%s> to <%s>. "
"Source and destination must not overlap",
oldPath.GetText(), newPath.GetText());
return false;
}
if (!_data->HasSpec(oldPath)) {
// Cannot move; nothing at source.
return false;
}
if (_data->HasSpec(newPath)) {
// Cannot move; destination exists.
return false;
}
_PrimMoveSpec(oldPath, newPath);
return true;
}
static void
_MoveSpecInternal(
SdfAbstractDataRefPtr data, Sdf_IdentityRegistry* idReg,
const SdfPath& oldSpecPath,
const SdfPath& oldRootPath, const SdfPath& newRootPath)
{
const SdfPath newSpecPath =
oldSpecPath.ReplacePrefix(
oldRootPath, newRootPath, /* fixTargets = */ false);
data->MoveSpec(oldSpecPath, newSpecPath);
idReg->MoveIdentity(oldSpecPath, newSpecPath);
}
void
SdfLayer::_PrimMoveSpec(const SdfPath& oldPath, const SdfPath& newPath,
bool useDelegate)
{
if (useDelegate && TF_VERIFY(_stateDelegate)) {
_stateDelegate->MoveSpec(oldPath, newPath);
return;
}
SdfChangeBlock block;
Sdf_ChangeManager::Get().DidMoveSpec(_self, oldPath, newPath);
Traverse(oldPath, std::bind(_MoveSpecInternal, _data,
&_idRegistry, ph::_1, oldPath, newPath));
}
static bool
_IsValidSpecForLayer(
const SdfLayer& layer, SdfSpecType specType)
{
const SdfSchemaBase::SpecDefinition* specDef =
layer.GetSchema().GetSpecDefinition(specType);
return static_cast<bool>(specDef);
}
bool
SdfLayer::_CreateSpec(const SdfPath& path, SdfSpecType specType, bool inert)
{
if (specType == SdfSpecTypeUnknown) {
return false;
}
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot create spec at <%s>. Layer @%s@ is not editable.",
path.GetText(),
GetIdentifier().c_str());
return false;
}
if (_validateAuthoring && !_IsValidSpecForLayer(*this, specType)) {
TF_ERROR(SdfAuthoringErrorUnrecognizedSpecType,
"Cannot create spec at <%s>. %s is not a valid spec type "
"for layer @%s@",
path.GetText(), TfEnum::GetName(specType).c_str(),
GetIdentifier().c_str());
return false;
}
if (_data->HasSpec(path)) {
TF_CODING_ERROR(
"Cannot create spec <%s> because it already exists in @%s@",
path.GetText(), GetIdentifier().c_str());
return false;
}
_PrimCreateSpec(path, specType, inert);
return true;
}
bool
SdfLayer::_DeleteSpec(const SdfPath &path)
{
if (!PermissionToEdit()) {
TF_CODING_ERROR("Cannot delete <%s>. Layer @%s@ is not editable",
path.GetText(),
GetIdentifier().c_str());
return false;
}
if (!HasSpec(path)) {
return false;
}
std::vector<SdfPath> inertSpecs;
if (_IsInertSubtree(path, &inertSpecs)) {
// If the subtree is inert, delete each inert spec from the
// bottom up to send a notification for each inert spec in the
// subtree. This is necessary since inert specs notices don't
//imply anything about descendant specs. See also _SetData.
SdfChangeBlock block;
for (const SdfPath& inertSpecPath : inertSpecs) {
if (inertSpecPath.IsPrimPath()) {
// Clear out prim and property children fields before calling
// _PrimDeleteSpec so that function doesn't try to recursively
// delete specs we've already deleted (since we're deleting
// from the bottom up).
VtValue val;
if (HasField(inertSpecPath,
SdfChildrenKeys->PrimChildren, &val)) {
_PrimSetField(
inertSpecPath, SdfChildrenKeys->PrimChildren,
VtValue(), &val);
}
if (HasField(inertSpecPath,
SdfChildrenKeys->PropertyChildren, &val)) {
_PrimSetField(
inertSpecPath, SdfChildrenKeys->PropertyChildren,
VtValue(), &val);
}
}
_PrimDeleteSpec(inertSpecPath, /* inert = */ true);
}
}
else {
_PrimDeleteSpec(path, /* inert = */ false);
}
return true;
}
template<typename ChildPolicy>
void
SdfLayer::_TraverseChildren(const SdfPath &path, const TraversalFunction &func)
{
std::vector<typename ChildPolicy::FieldType> children =
GetFieldAs<std::vector<typename ChildPolicy::FieldType> >(
path, ChildPolicy::GetChildrenToken(path));
TF_FOR_ALL(i, children) {
Traverse(ChildPolicy::GetChildPath(path, *i), func);
}
}
void
SdfLayer::Traverse(const SdfPath &path, const TraversalFunction &func)
{
std::vector<TfToken> fields = ListFields(path);
TF_FOR_ALL(i, fields) {
if (*i == SdfChildrenKeys->PrimChildren) {
_TraverseChildren<Sdf_PrimChildPolicy>(path, func);
} else if (*i == SdfChildrenKeys->PropertyChildren) {
_TraverseChildren<Sdf_PropertyChildPolicy>(path, func);
} else if (*i == SdfChildrenKeys->MapperChildren) {
_TraverseChildren<Sdf_MapperChildPolicy>(path, func);
} else if (*i == SdfChildrenKeys->MapperArgChildren) {
_TraverseChildren<Sdf_MapperArgChildPolicy>(path, func);
} else if (*i == SdfChildrenKeys->VariantChildren) {
_TraverseChildren<Sdf_VariantChildPolicy>(path, func);
} else if (*i == SdfChildrenKeys->VariantSetChildren) {
_TraverseChildren<Sdf_VariantSetChildPolicy>(path, func);
} else if (*i == SdfChildrenKeys->ConnectionChildren) {
_TraverseChildren<Sdf_AttributeConnectionChildPolicy>(path, func);
} else if (*i == SdfChildrenKeys->RelationshipTargetChildren) {
_TraverseChildren<Sdf_RelationshipTargetChildPolicy>(path, func);
} else if (*i == SdfChildrenKeys->ExpressionChildren) {
_TraverseChildren<Sdf_ExpressionChildPolicy>(path, func);
}
}
func(path);
}
static void
_EraseSpecAtPath(SdfAbstractData* data, const SdfPath& path)
{
data->EraseSpec(path);
}
void
SdfLayer::_PrimDeleteSpec(const SdfPath &path, bool inert, bool useDelegate)
{
if (useDelegate && TF_VERIFY(_stateDelegate)) {
_stateDelegate->DeleteSpec(path, inert);
return;
}
SdfChangeBlock block;
Sdf_ChangeManager::Get().DidRemoveSpec(_self, path, inert);
TraversalFunction eraseFunc =
std::bind(&_EraseSpecAtPath, boost::get_pointer(_data), ph::_1);
Traverse(path, eraseFunc);
}
void
SdfLayer::_PrimCreateSpec(const SdfPath &path,
SdfSpecType specType, bool inert,
bool useDelegate)
{
if (useDelegate && TF_VERIFY(_stateDelegate)) {
_stateDelegate->CreateSpec(path, specType, inert);
return;
}
SdfChangeBlock block;
Sdf_ChangeManager::Get().DidAddSpec(_self, path, inert);
_data->CreateSpec(path, specType);
}
bool
SdfLayer::_IsInert(const SdfPath &path, bool ignoreChildren,
bool requiredFieldOnlyPropertiesAreInert) const
{
// If the spec has only the required SpecType field (stored
// separately from other fields), then it doesn't affect the scene.
const std::vector<TfToken> fields = ListFields(path);
if (fields.empty()) {
return true;
}
// If the spec is custom it affects the scene.
if (GetFieldAs<bool>(path, SdfFieldKeys->Custom, false)) {
return false;
}
// Special cases for determining whether a spec affects the scene.
const SdfSpecType specType = GetSpecType(path);
// Prims that are defs or with a specific typename always affect the scene
// since they bring a prim into existence.
if (specType == SdfSpecTypePrim) {
const SdfSpecifier specifier = GetFieldAs<SdfSpecifier>(
path, SdfFieldKeys->Specifier, SdfSpecifierOver);
if (SdfIsDefiningSpecifier(specifier)) {
return false;
}
const TfToken type = GetFieldAs<TfToken>(path, SdfFieldKeys->TypeName);
if (!type.IsEmpty()) {
return false;
}
}
// If we're not considering required-field-only properties as inert, then
// properties should never be considered inert because they might exist to
// instantiate an on-demand property.
if (!requiredFieldOnlyPropertiesAreInert &&
(specType == SdfSpecTypeAttribute ||
specType == SdfSpecTypeRelationship)) {
return false;
}
// Prims and properties don't affect the scene if they only contain
// opinions about required fields.
if (specType == SdfSpecTypePrim ||
specType == SdfSpecTypeAttribute ||
specType == SdfSpecTypeRelationship) {
const SdfSchema::SpecDefinition* specDefinition =
GetSchema().GetSpecDefinition(specType);
if (!TF_VERIFY(specDefinition)) {
return false;
}
TF_FOR_ALL(field, fields) {
// If specified, skip over prim name children and properties.
// This is a special case to allow _IsInertSubtree to process
// these children separately.
if (specType == SdfSpecTypePrim && ignoreChildren) {
if (*field == SdfChildrenKeys->PrimChildren ||
*field == SdfChildrenKeys->PropertyChildren) {
continue;
}
}
if (specDefinition->IsRequiredField(*field)) {
continue;
}
return false;
}
return true;
}
return false;
}
bool
SdfLayer::_IsInertSubtree(
const SdfPath &path,
std::vector<SdfPath>* inertSpecs)
{
if (!_IsInert(path, true /*ignoreChildren*/,
true /* requiredFieldOnlyPropertiesAreInert */)) {
return false;
}
if (path.IsPrimPath()) {
std::vector<TfToken> prims;
if (HasField(path, SdfChildrenKeys->PrimChildren, &prims)) {
for (const TfToken& child : prims) {
if (!_IsInertSubtree(path.AppendChild(child), inertSpecs)) {
return false;
}
}
}
std::vector<TfToken> properties;
if (HasField(path, SdfChildrenKeys->PropertyChildren, &properties)) {
for (const TfToken& prop : properties) {
const SdfPath propPath = path.AppendProperty(prop);
if (!_IsInert(propPath,
/* ignoreChildren = */ false,
/* requiredFieldOnlyPropertiesAreInert = */ true)) {
return false;
}
else if (inertSpecs) {
inertSpecs->push_back(propPath);
}
}
}
}
if (inertSpecs) {
inertSpecs->push_back(path);
}
return true;
}
bool
SdfLayer::ExportToString( std::string *result ) const
{
TRACE_FUNCTION();
TF_DESCRIBE_SCOPE("Writing layer @%s@", GetIdentifier().c_str());
return GetFileFormat()->WriteToString(*this, result);
}
bool
SdfLayer::_WriteToFile(const string & newFileName,
const string &comment,
SdfFileFormatConstPtr fileFormat,
const FileFormatArguments& args) const
{
TRACE_FUNCTION();
TF_DESCRIBE_SCOPE("Writing layer @%s@", GetIdentifier().c_str());
if (newFileName.empty())
return false;
if ((newFileName == GetRealPath()) && !PermissionToSave()) {
TF_RUNTIME_ERROR("Cannot save layer @%s@, saving not allowed",
newFileName.c_str());
return false;
}
// If a file format was explicitly provided, use that regardless of the
// file extension, else discover the file format from the file extension.
if (!fileFormat) {
const string ext = Sdf_GetExtension(newFileName);
if (!ext.empty())
fileFormat = SdfFileFormat::FindByExtension(ext);
if (!fileFormat) {
// Some parts of the system generate temp files
// with garbage extensions, furthermore we do not restrict
// users from writing to arbitrary file names, so here we must fall
// back to the current file format associated with the layer.
fileFormat = GetFileFormat();
}
}
// Disallow saving or exporting package layers via the Sdf API.
if (Sdf_IsPackageOrPackagedLayer(fileFormat, newFileName)) {
TF_CODING_ERROR("Cannot save layer @%s@: writing %s %s layer "
"is not allowed through this API.",
newFileName.c_str(),
fileFormat->IsPackage() ? "package" : "packaged",
fileFormat->GetFormatId().GetText());
return false;
}
if (!TF_VERIFY(fileFormat)) {
TF_RUNTIME_ERROR("Unknown file format when attempting to write '%s'",
newFileName.c_str());
return false;
}
if (!ArGetResolver().CreatePathForLayer(newFileName)) {
TF_RUNTIME_ERROR(
"Cannot create path to write '%s'",
newFileName.c_str());
return false;
}
// XXX Check for schema compatibility here...
bool ok = fileFormat->WriteToFile(*this, newFileName, comment, args);
// If we wrote to the backing file then we're now clean.
if (ok && newFileName == GetRealPath())
_MarkCurrentStateAsClean();
return ok;
}
bool
SdfLayer::Export(const string& newFileName, const string& comment,
const FileFormatArguments& args) const
{
return _WriteToFile(newFileName, comment, TfNullPtr, args);
}
bool
SdfLayer::Save(bool force) const
{
return _Save(force);
}
bool
SdfLayer::_Save(bool force) const
{
TRACE_FUNCTION();
if (IsMuted()) {
TF_CODING_ERROR("Cannot save muted layer @%s@",
GetIdentifier().c_str());
return false;
}
if (IsAnonymous()) {
TF_CODING_ERROR("Cannot save anonymous layer @%s@",
GetIdentifier().c_str());
return false;
}
const ArResolvedPath path = GetResolvedPath();
if (path.empty())
return false;
// Skip saving if the file exists and the layer is clean.
if (!force && !IsDirty() && TfPathExists(path))
return true;
if (!_WriteToFile(path, std::string(),
GetFileFormat(), GetFileFormatArguments()))
return false;
// Layer hints are invalidated by authoring so _hints must be reset now
// that the layer has been marked as clean. See GetHints().
_hints = SdfLayerHints{};
// Record modification timestamp.
VtValue timestamp = ArGetResolver().GetModificationTimestamp(
GetIdentifier(), path);
if (timestamp.IsEmpty()) {
TF_CODING_ERROR(
"Unable to get modification timestamp for '%s (%s)'",
GetIdentifier().c_str(), path.GetPathString().c_str());
return false;
}
_assetModificationTime.Swap(timestamp);
SdfNotice::LayerDidSaveLayerToFile().Send(_self);
return true;
}
PXR_NAMESPACE_CLOSE_SCOPE
|
//
// Copyright (C) 2018 Susan H. Leung
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include "MolStandardize.h"
#include "Normalize.h"
#include "Fragment.h"
#include "Charge.h"
#include "Metal.h"
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/ROMol.h>
#include <iostream>
using namespace RDKit;
void testCleanup() {
BOOST_LOG(rdInfoLog) << "-----------------------\n test cleanup" << std::endl;
MolStandardize::CleanupParameters params;
// Test covalent metal is disconnected during standardize.
{
RWMOL_SPTR m = "CCC(=O)O[Na]"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CCC(=O)[O-].[Na+]");
}
// Test metal ion is untouched during standardize.
{
RWMOL_SPTR m = "CCC(=O)[O-].[Na+]"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CCC(=O)[O-].[Na+]");
}
// Test Hg is disconnected from O during standardize.
{
RWMOL_SPTR m = "CCC(=O)O[Hg]"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CCC(=O)[O-].[Hg+]")
}
// Test dimethylmercury is not disconnected during standardize.
{
RWMOL_SPTR m = "C[Hg]C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "C[Hg]C")
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
}
void testStandardizeSm() {
BOOST_LOG(rdInfoLog) << "-----------------------\n test standardize smiles"
<< std::endl;
// check aromaticity
{
std::string smi = "C1=CC=CC=C1";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "c1ccccc1");
}
// both rings should be aromatic
{
std::string smi = "C[N]1C=NC2=C1C(=O)N(C)C(=O)N2C";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "Cn1c(=O)c2c(ncn2C)n(C)c1=O");
}
// both rings should be aromatic
{
std::string smi = "C=Cc1ccc2c(c1)[nH]c(=O)/c/2=C\\c1ccc[nH]1";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "C=Cc1ccc2c(c1)NC(=O)/C2=C\\c1ccc[nH]1");
}
// check stereochemistry is correctly perceived
{
std::string smi = "Cl\\C=C/Cl";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "Cl/C=C\\Cl");
}
// Break metal-organic covalent bonds
{
std::string smi = "[Na]OC(=O)c1ccccc1";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "O=C([O-])c1ccccc1.[Na+]");
}
// SMILES parsing error should stop tests
// std::string smi ="C1CCC1C(=O)O.Na";
// std::string ss6 = MolStandardize::standardizeSmiles(smi);
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testMetalDisconnector() {
BOOST_LOG(rdInfoLog) << "-----------------------\n test metal disconnector"
<< std::endl;
MolStandardize::MetalDisconnector md;
unsigned int failedOp;
// testing overloaded function
{
ROMOL_SPTR m("CCC(=O)O[Na]"_smiles);
TEST_ASSERT(m);
ROMOL_SPTR nm(md.disconnect(*m));
TEST_ASSERT(MolToSmiles(*nm) == "CCC(=O)[O-].[Na+]");
}
{
RWMOL_SPTR m("[Na]OC(=O)CCC(=O)O[Na]"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "O=C([O-])CCC(=O)[O-].[Na+].[Na+]");
}
{
RWMOL_SPTR m("c1ccccc1[Mg]Br"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "Br[Mg]c1ccccc1");
}
{
RWMOL_SPTR m("Br[Mg]c1ccccc1CCC(=O)O[Na]"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "O=C([O-])CCc1ccccc1[Mg]Br.[Na+]");
}
// test input own metal_non, metal_nof
// missing out Na
{
MolStandardize::MetalDisconnector md2;
ROMOL_SPTR metal_nof(
SmartsToMol("[Li,K,Rb,Cs,Fr,Be,Mg,Ca,Sr,Ba,Ra,Sc,Ti,V,Cr,Mn,Fe,Co,"
"Ni,Cu,Zn,Al,Ga,Y,Zr,Nb,Mo,Tc,Ru,Rh,Pd,Ag,Cd,In,Sn,Hf,Ta,"
"W,Re,Os,Ir,Pt,Au,Hg,Tl,Pb,Bi]~[#7,#8,F]"));
md2.setMetalNof(*metal_nof);
ROMOL_SPTR m("CCC(=O)O[Na]"_smiles);
TEST_ASSERT(m);
ROMOL_SPTR nm(md2.disconnect(*m));
TEST_ASSERT(MolToSmiles(*nm) == "CCC(=O)O[Na]"); // not disconnected
}
// test that metals are not assigned excess positive charge
{
RWMOL_SPTR m(SmilesToMol("[Be](F)(F)(F)OC", 0, false));
MolOps::sanitizeMol(*m, failedOp, MolOps::SANITIZE_CLEANUP);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "C[O-].[Be+2].[F-].[F-].[F-]");
}
// test that badly written complexes with 4ary nitrogen
// are not assigned a negative charge nor the metal is
// stolen electrons from
{
RWMOL_SPTR m(SmilesToMol("[Ru](SC)(SC)(SC)N(C)(C)C", 0, false));
MolOps::sanitizeMol(*m, failedOp, MolOps::SANITIZE_CLEANUP);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "CN(C)C.C[S-].C[S-].C[S-].[Ru+3]");
}
// test that badly written salts are not assigned excess formal charges
{
RWMOL_SPTR m(SmilesToMol("[Na+][O-]C(=O)C", 0, false));
MolOps::sanitizeMol(*m, failedOp, MolOps::SANITIZE_CLEANUP);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "CC(=O)[O-].[Na+]");
}
// test that badly specified dative bonds are perceived as such
{
RWMOL_SPTR m(
SmilesToMol("CC1=CC=CC2=[N]1[Cu+2]3[N](=C2)NC(=[S]3)N(C)C", 0, false));
MolOps::sanitizeMol(*m, failedOp, MolOps::SANITIZE_CLEANUP);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "CC1=CC=CC(C=NNC(=S)N(C)C)=N1.[Cu+2]");
}
// test that carbonyl complexes are not assigned excess formal charges
{
RWMOL_SPTR m(SmilesToMol("[Ni+2]([C]=O)([C]=O)([C]=O)([C]=O)([C]=O)[C]=O",
0, false));
MolOps::sanitizeMol(
*m, failedOp, MolOps::SANITIZE_CLEANUP | MolOps::SANITIZE_FINDRADICALS);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) ==
"[C]=O.[C]=O.[C]=O.[C]=O.[C]=O.[C]=O.[Ni+2]");
}
// test that dative bonds are handled appropriately
{
RWMOL_SPTR m("O->[Fe](<-O)(O)O"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "O.O.[Fe+2].[OH-].[OH-]");
}
// test that dative bonds are handled appropriately
{
RWMOL_SPTR m("[OH-]->[Co+3](<-[OH-])(<-O)<-O"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "O.O.[Co+3].[OH-].[OH-]");
}
// test that pre-existing formal charges on metals are honored (github #3625)
{
RWMOL_SPTR m("[Pd+]Cl"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "[Cl-].[Pd+2]");
}
{
RWMOL_SPTR m("[Pd+2]<-[Cl-]"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "[Cl-].[Pd+2]");
}
{
RWMOL_SPTR m("[Al](Cl)(Cl)Cl"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "[Al+3].[Cl-].[Cl-].[Cl-]");
}
{
RWMOL_SPTR m("[Al+](<-[Cl-])(Cl)Cl"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "[Al+3].[Cl-].[Cl-].[Cl-]");
}
{
RWMOL_SPTR m("[Al+](Cl)Cl"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "[Al+3].[Cl-].[Cl-]");
}
{
RWMOL_SPTR m("[Al+2]Cl"_smiles);
TEST_ASSERT(m);
md.disconnect(*m);
TEST_ASSERT(MolToSmiles(*m) == "[Al+3].[Cl-]");
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testNormalize() {
BOOST_LOG(rdInfoLog) << "-----------------------\n test normalize"
<< std::endl;
MolStandardize::CleanupParameters params;
std::string rdbase = getenv("RDBASE");
std::string transformFile =
rdbase + "/Data/MolStandardize/normalizations.txt";
params.normalizations = transformFile;
// Normalize nitro group.
{
RWMOL_SPTR m = "C1(=CC=CC=C1)[N+](=O)[O-]"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=[N+]([O-])c1ccccc1");
}
// Normalize nitro group.
{
RWMOL_SPTR m = "O=[N](=O)c1ccccc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=[N+]([O-])c1ccccc1");
}
// Normalize nitro group.
{
RWMOL_SPTR m = "[O-][N+](=O)c1ccccc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=[N+]([O-])c1ccccc1");
}
// Normalize nitro group.
{
RWMOL_SPTR m = "[N](=O)(=O)O"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=[N+]([O-])O");
}
// Normalize nitro group.
{
RWMOL_SPTR m = "O[N+](=O)[O-]"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=[N+]([O-])O");
}
// Normalize pyridine oxide.
{
RWMOL_SPTR m = "C1=[N](C=CC=C1)=O"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "[O-][n+]1ccccc1");
}
// Normalize pyridine oxide.
{
RWMOL_SPTR m = "O=n1ccccc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "[O-][n+]1ccccc1");
}
// normalize sulfone.
{
RWMOL_SPTR m = "C[S+2]([O-])([O-])C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CS(C)(=O)=O");
}
// normalize sulfone.
{
RWMOL_SPTR m = "C[S+2]([O-])([O-])O"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CS(=O)(=O)O");
}
// normalize sulfoxide..
{
RWMOL_SPTR m = "CS(=O)C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "C[S+](C)[O-]");
}
// normalize sulfoxide.
{
RWMOL_SPTR m =
"COC1=CC2=C(C=C1)[N]C(=N2)[S](=O)CC3=C(C(=C(C=N3)C)OC)C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) ==
"COc1ccc2c(c1)N=C([S+]([O-])Cc1ncc(C)c(OC)c1C)[N]2");
}
// Normalize sulfoxide.
{
RWMOL_SPTR m = "COc1ccc2c(c1)nc([nH]2)S(=O)Cc1ncc(c(c1C)OC)C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) ==
"COc1ccc2[nH]c([S+]([O-])Cc3ncc(C)c(OC)c3C)nc2c1");
}
// Normalize azide.
{
RWMOL_SPTR m = "C1(=CC=C(C=C1)N)N=[N]#N"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "[N-]=[N+]=Nc1ccc(N)cc1");
}
// Normalize diazo.
{
RWMOL_SPTR m = "[N](#N)=C1C(NC(N=C1)=O)=O"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "[N-]=[N+]=C1C=NC(=O)NC1=O");
}
// Normalize phosphate.
{
RWMOL_SPTR m = "C1=NC=C([N]1)CO[P+]([O-])([O-])[O-]"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=P([O-])([O-])OCC1=CN=C[N]1");
}
// Normalize hydrazine-diazonium.
{
RWMOL_SPTR m = "CNNC[N+]#N"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN=[NH+]CN=N");
}
// Normalize amidinium.
{
RWMOL_SPTR m = "[C+](C)(N)N"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CC(N)=[NH2+]");
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
}
void testNormalizeMultiFrags() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n test normalize multiple frags" << std::endl;
MolStandardize::CleanupParameters params;
std::string rdbase = getenv("RDBASE");
std::string transformFile =
rdbase + "/Data/MolStandardize/normalizations.txt";
params.normalizations = transformFile;
// All fragments should stay if one gets transformed by normalization.
{
RWMOL_SPTR m = "[Na]OC(=O)c1ccc(C[S+2]([O-])([O-]))cc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=C([O-])c1ccc(C[S](=O)=O)cc1.[Na+]");
}
// All fragments should stay if one gets transformed by normalization.
{
RWMOL_SPTR m = "[Na+].[O-]C(=O)c1ccc(C[S+2]([O-])([O-]))cc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=C([O-])c1ccc(C[S](=O)=O)cc1.[Na+]");
}
// Recombine non-aromatic 1,3-separated charges.
{
RWMOL_SPTR m = "C[N-]C(C)=[N+](C)C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN=C(C)N(C)C");
}
// Recombine aromatic 1,3-separated charges.
{
RWMOL_SPTR m = "[n-]1c(=[N+](C)C)cccc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN(C)c1ccccn1");
}
// Recombine aromatic 1,3-separated charges.
{
RWMOL_SPTR m = "C[n+]1c([N-](C))cccc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN=c1ccccn1C");
}
// Recombine aromatic 1,3-separated charges to form pyrimidone.
{
RWMOL_SPTR m = "[O-]c1[n+](C)cccc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "Cn1ccccc1=O");
}
// Recombine aromatic 1,3-separated charges to form pyrimidone.
{
RWMOL_SPTR m =
"COc1cc2ccc3c4c(OC)cc(OC)c(OC)c4c([O-])[n+](C)c3c2cc1OC"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) ==
"COc1cc2ccc3c4c(OC)cc(OC)c(OC)c4c(=O)n(C)c3c2cc1OC");
}
// Recombine non-aromatic 1,5-separated charges.
{
RWMOL_SPTR m = "C[N-]C=CC=[N+](C)C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN=CC=CN(C)C");
}
// Recombine aromatic 1,5-separated charges.
{
RWMOL_SPTR m = "[n-]1ccc(=[N+](C)C)cc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN(C)c1ccncc1");
}
// Recombine aromatic 1,5-separated charges.
{
RWMOL_SPTR m = "C[n+]1ccc([N-]C)cc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN=c1ccn(C)cc1");
}
// Shift positive charge from nonprotonated to protonated atom.
{
RWMOL_SPTR m = "CNC=[N+](C)C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "C[NH+]=CN(C)C");
}
// Shift positive charge from nonprotonated to protonated atom."
{
RWMOL_SPTR m = "CNC=CC=[N+](C)C"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "C[NH+]=CC=CN(C)C");
}
// Shift positive charge from nonprotonated to protonated atom."
{
RWMOL_SPTR m = "[nH]1ccc(=[N+](C)C)cc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN(C)c1cc[nH+]cc1");
}
// Ensure no transforms inadvertently breaks open rings.
{
RWMOL_SPTR m = "[O-]C1=CC=CC2=CC=CC=[N+]12"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "O=c1cccc2ccccn12");
}
// Shift positive charge from nonprotonated to protonated atom.
{
RWMOL_SPTR m = "[nH]1c(=[N+](C)C)cccc1"_smiles;
RWMOL_SPTR res(MolStandardize::cleanup(*m, params));
TEST_ASSERT(MolToSmiles(*res) == "CN(C)c1cccc[nH+]1");
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
}
void testCharge() {
BOOST_LOG(rdInfoLog) << "-----------------------\n test charges" << std::endl;
// Reionization should not infinitely loop forever on these molecules.
{
std::string smi = "CCCCCCCCCCCCCCCCCC(=O)CC(=C)C(=O)O[Ti](=O)(OC(C)C)C(C)C";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(
ss ==
"C=C(CC(=O)[CH-]CCCCCCCCCCCCCCCC)C(=O)[O-].CC(C)[O-].CCC.[O-2].[Ti+5]");
}
// Reionization should not infinitely loop forever on these molecules.
{
std::string smi =
"OP(=O)(O)[O-].OP(=O)([O-])[O-].[O-]S(=O)(=O)[O-].[Na+].[Na+].[Na+].["
"Mg+"
"2].[Cl-].[Cl-].[K+].[K+]";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(
ss ==
"O=P([O-])(O)O.O=P([O-])([O-])O.O=S(=O)([O-])[O-].[Cl-].[Cl-].[K+"
"].[K+].[Mg+2].[Na+].[Na+].[Na+]");
}
// Charge parent!!
// Test reionizer moves proton to weaker acid.
{
std::string smi = "[Na].[Na]";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "[Na+].[Na+]");
}
// TODO: Arguably should become selenite ion... O=[Se]([O-])[O-].
// Need an AcidBasePair?
{
std::string smi = "[Na].[Na].O[Se](O)=O";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "O=[Se](O)O.[Na+].[Na+]");
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
// Test that tetrazolate salts are not neutralised
{
std::string smi = "c1nn[n-]n1.[Na+]";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "[Na+].c1nn[n-]n1");
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
// Test that tetrazolate zwitterions are not neutralised
{
std::string smi = "CCCc1cc(-c2ccccc2)cc(CCC)[n+]1-c1nn[n-]n1";
std::string ss = MolStandardize::standardizeSmiles(smi);
TEST_ASSERT(ss == "CCCc1cc(-c2ccccc2)cc(CCC)[n+]1-c1nn[n-]n1");
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
}
void testEnumerateTautomerSmiles() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n test enumerate tautomer smiles"
<< std::endl;
MolStandardize::CleanupParameters params;
std::string smi = "c1(ccccc1)/C=C(/O)\\C";
std::vector<std::string> tsmiles =
MolStandardize::enumerateTautomerSmiles(smi, params);
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testMetalDisconnectorLigandExpo() {
BOOST_LOG(rdInfoLog) << "-----------------------\n test metal disconnector "
"on LigandExpo ligands"
<< std::endl;
std::list<std::pair<std::string, std::string>> ligandExpoSmiles{
{"[Be](O[P@@](=O)(O)O[P@](=O)(O)OCCCNc1ccc(cc1[N+](=O)[O-])[N+](=O)[O-])("
"F)(F)F",
"O=[N+]([O-])c1ccc(NCCCO[P@@](=O)(O)OP(=O)(O)O)c([N+](=O)[O-])c1"},
{"[Be](OP(=O)(O)OP(=O)(O)OC[C@@H]1[C@H]([C@H]([C@@H](O1)n2cnc3c2ncnc3N)O)"
"O)(F)(F)F",
"Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)O)[C@@H](O)[C@H]1O"},
{"[Be-](O[P@@](=O)(O)O[P@](=O)(O)OCCNc1cccc(c1)[N+](=O)[O-])(F)(F)F",
"O=[N+]([O-])c1cccc(NCCO[P@@](=O)(O)OP(=O)(O)O)c1"},
{"[Be-](O[P@@](=O)(O)O[P@](=O)(O)OCCNc1ccccc1[N+](=O)[O-])(F)(F)F",
"O=[N+]([O-])c1ccccc1NCCO[P@@](=O)(O)OP(=O)(O)O"},
{"[Be](O[P@@](=O)(O)O[P@](=O)(O)OCCNc1ccc(cc1)[N+](=O)[O-])(F)(F)F",
"O=[N+]([O-])c1ccc(NCCO[P@@](=O)(O)OP(=O)(O)O)cc1"},
{"[Be-](O[P@@](=O)(O)O[P@](=O)(O)OCCNc1ccc(cc1[N+](=O)[O-])[N+](=O)[O-])("
"F)(F)F",
"O=[N+]([O-])c1ccc(NCCO[P@@](=O)(O)OP(=O)(O)O)c([N+](=O)[O-])c1"},
{"[Be-](O[P@@](=O)(O)O[P@](=O)(O)OCC[N@@](C)c1ccccc1[N+](=O)[O-])(F)(F)F",
"CN(CCO[P@@](=O)(O)OP(=O)(O)O)c1ccccc1[N+](=O)[O-]"},
{"c1c2c3c4c(c1NC(=O)CI)C=CC=[N]4[Ru+2]56([N]3=CC=C2)([N]7=C(C=CC=C7)C8=["
"N]5C=CC=C8)[N]9=C(C=CC=C9)C1=CC=CC=[N]61",
"O=C(CI)Nc1cc2cccnc2c2ncccc12"},
{"c1c2c(cc3c1C4=[N]([Ru]356([S]7CC[S]5CC[S]6CC7)C#[O+])C=CC=C4)C(=O)NC2="
"O",
"O=C1NC(=O)c2cc(-c3ccccn3)c([Ru])cc21"},
{"c1c2c(cc3c1C4=[N]([Ru]356([S]7CC[S]5CC[S]6CC7)N=C=S)C=CC=C4)C(=O)NC2=O",
"O=C1NC(=O)c2cc(-c3ccccn3)c([Ru])cc21"},
{"C1=C2C(=C(C3=[N]2[Fe]45n6c1c(c(c6C=C7[N]4=C(C=C8N5C(=C3)C(=C8CCC(=O)O)"
"CC(=O)O)C(=C7CC(=O)O)CCC(=O)O)CC(=O)O)CCC(=O)O)CCC(=O)O)CC(=O)O",
"O=C(O)CCC1=C(CC(=O)O)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(CC(=O)O)c5CCC(="
"O)O)C(CCC(=O)O)=C4CC(=O)O)c(CC(=O)O)c3CCC(=O)O"},
{"C1=CC23=C4([Ru+]2567892%10([CH]3=[CH]5[CH]6=[CH]74)[CH]3=[CH]8C9[CH]2=["
"CH]%103)C=C1",
"c1ccc2ccccc2c1"},
{"c1cc2c3c4c1C=CC=[N]4[Ru]5678(C3=CNC2=O)(C9=C5[C]6C7=C89)C#O",
"O=c1[nH]ccc2c1ccc1cccnc12"},
{"c1cc2c3c4c1N=CC=[N]4[Ru+2]56([N]3=CC=N2)([N]7=C8C(=CC=C7)c9c(nc1cc(c("
"cc1n9)F)F)C1=CC=C[N]5=C18)[N]1=CC=Nc2c1c1c(cc2)N=CC=[N]61",
"Fc1cc2nc3c4cccnc4c4ncccc4c3nc2cc1F"},
{"c1cc2c(cc1c3ccc4c(c3)nc5c(n4)C6=CC=C[N]7=C6C8=[N]([Ru]791([N]3=CC="
"Cc4c3c3c(cc4)C=CC=[N]93)[N]3=CC=Cc4c3c3c(cc4)C=CC=[N]13)C=CC=C58)nc1c("
"n2)C2=CC=C[N]3=C2C2=[N]([Ru]334([N]5=CC=Cc6c5c5c(cc6)C=CC=[N]35)[N]3="
"CC=Cc5c3c3c(cc5)C=CC=[N]43)C=CC=C12",
"c1cnc2c(c1)c1nc3ccc(-c4ccc5nc6c7cccnc7c7ncccc7c6nc5c4)cc3nc1c1cccnc12"},
{"c1cc2c(cc1Cl)nc3c(n2)C4=C5C6=[N](C=CC=C36)[Ru+2]78([N]5=CC=C4)([N]9=CC="
"Nc1c9c2c(cc1)N=CC=[N]72)[N]1=CC=Nc2c1c1c(cc2)N=CC=[N]81",
"Clc1ccc2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"c1cc2c(cc1C(N)N)NC3=[N]2[Zn+2][N]4=C(C3=O)Nc5c4ccc(c5)C(N)N",
"NC(N)c1ccc2nc(C(=O)c3nc4ccc(C(N)N)cc4[nH]3)[nH]c2c1"},
{"c1cc2c(c(c1)[N+](=O)[OH-])nc3c4c5c6c(c3n2)C=CC=[N]6[Ru]78([N]5=CC=C4)(["
"N]9=C1C(=CC=C9)C=CC2=CC=C[N]7=C21)[N]1=C2C(=CC=C1)C=CC1=CC=C[N]8=C12",
"O=[N+]([1O-])c1cccc2nc3c4cccnc4c4ncccc4c3nc12"},
{"c1cc2c(cc1N(=O)=O)nc3c(n2)C4=CC=C[N]5=C4C6=[N]([Ru]578([N]9=CC="
"Cc1c9c2c(cc1)C=CC=[N]72)[N]1=CC=Cc2c1c1c(cc2)C=CC=[N]81)C=CC=C36",
"O=[N+]([O-])c1ccc2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"c1cc2c(cc1O)c3c4c(c5c6c3n2[Ru]7891([N]6=CC=C5)([CH]2=[CH]7C8[CH]9=[CH]"
"12)C#O)C(=O)NC4=O",
"O=C1NC(=O)c2c1c1cccnc1c1[nH]c3ccc(O)cc3c21"},
{"c1cc2c(cc1O)c3c4n2[Ru]56([N]7=C4C(=CC(=C7)F)C8=C3C(=O)NC8=O)([S]9CC[S]"
"5CC[S]6CC9)[N]CS",
"O=C1NC(=O)c2c1c1cc(F)cnc1c1[nH]c3ccc(O)cc3c21"},
{"c1cc2c(cc1OCCN3CCCCC3)O[Cu]45[N](=C2)c6cc(c(cc6[N]4=Cc7ccc(cc7O5)"
"OCCN8CCCCC8)F)F",
"Oc1cc(OCCN2CCCCC2)ccc1C=Nc1cc(F)c(F)cc1N=Cc1ccc(OCCN2CCCCC2)cc1O"},
{"c1cc2c(cc1OCCN3CCCCC3)O[Ni]45[N](=C2)c6cc(c(cc6[N]4=Cc7ccc(cc7O5)"
"OCCN8CCCCC8)F)F",
"Oc1cc(OCCN2CCCCC2)ccc1C=Nc1cc(F)c(F)cc1N=Cc1ccc(OCCN2CCCCC2)cc1O"},
{"c1cc2c(cc(c(c2cc1)N)/N=N/c3ccc(cc3)c4ccc(cc4)/N=N/"
"c5c(c6c(c(c5)S(=O)(=O)[O-][Na+])cccc6)N)S(=O)(=O)[O-][Na+]",
"Nc1c(/N=N/c2ccc(-c3ccc(/N=N/"
"c4cc(S(=O)(=O)O)c5ccccc5c4N)cc3)cc2)cc(S(=O)(=O)O)c2ccccc12"},
{"c1cc2n3c1C=C4C=CC5=[N]4[Fe]36[N]7=C(C=CC7=C2)C=C8N6C(=C5)C=C8",
"C1=Cc2cc3ccc(cc4nc(cc5ccc(cc1n2)[nH]5)C=C4)[nH]3"},
{"c1cc2n3c1C(=C4C=CC5=[N]4[Zn]36N7C(=C5C(F)(F)F)C=CC7=C(C8=[N]6C(=C2C(F)("
"F)F)C=C8)C(F)(F)F)C(F)(F)F",
"FC(F)(F)c1c2nc(c(C(F)(F)F)c3ccc([nH]3)c(C(F)(F)F)c3nc(c(C(F)(F)F)"
"c4ccc1[nH]4)C=C3)C=C2"},
{"C1=CC2=[N](C=C1)[Pt]34[N]5=C(C=CC=C5)NC6=CC=CC(=[N]63)C7=[N]4C(=CC=C7)"
"N2",
"c1ccc(Nc2cccc(-c3cccc(Nc4ccccn4)n3)n2)nc1"},
{"c1ccc2c(c1)c3c4c(c5c6c3n2[Ru]7([N]6=CC(=C5)N)(NCC8=[N]7C=CC=C8)(C#O)Cl)"
"C(=O)NC4=O",
"Nc1cnc2c(c1)c1c(c3c4ccccc4[nH]c23)C(=O)NC1=O"},
{"c1ccc2c(c1)-c3c4c(c5c6c3[NH]2[Ru]7891([N]6=CC=C5)([CH]2=[CH]7[CH]8=C9=["
"CH]12)C#O)C(=O)NC4=O",
"O=C1NC(=O)c2c1c1cccnc1c1[nH]c3ccccc3c21"},
{"c1ccc2c(c1)c3c4n2[Ru]5678(C9C5C6C7C89)([N]1=C4C(=CC(=C1)F)C1=C3C(=O)"
"NC1=O)C#[O+]",
"O=C1NC(=O)c2c1c1cc(F)cnc1c1[nH]c3ccccc3c21"},
{"c1ccc2c(c1)c3n4c2N=C5c6ccccc6C7=[N]5[Ga]48N9C(=NC1=[N]8C(=N3)c2c1cccc2)"
"c1ccccc1C9=N7",
"c1ccc2c(c1)-c1nc-2nc2[nH]c(nc3nc(nc4[nH]c(n1)c1ccccc41)-c1ccccc1-3)"
"c1ccccc21"},
{"c1ccc2c(c1)C(=CC3=[N]2[Ru]4567([C]8[C]4[C]5[C]6[C]78)(OC3=O)[O])N9CCN("
"CC9)C(=O)CCCC[C@H]1[C@@H]2[C@H](CS1)NC(=O)N2",
"O=C1N[C@@H]2[C@H](CCCCC(=O)N3CCN(c4cc(C(=O)O)nc5ccccc45)CC3)SC[C@@H]"
"2N1"},
{"c1ccc2c(c1)C=[N]3c4ccc(cc4O[Cr+]3O2)CCC(=O)O",
"O=C(O)CCc1ccc(N=Cc2ccccc2O)c(O)c1"},
{"c1ccc2c(c1)nc3c4c5c6c(c3n2)C=CC=[N]6[Ru]78([N]5=CC=C4)([N]9=CC="
"Cc1c9c2c(cc1)C=CC=[N]72)[N]1=CC=Cc2c1c1c(cc2)C=CC=[N]81",
"c1ccc2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"c1ccc2c(c1)nc3c4c5c6c(c3n2)C=CC=[N]6[Ru]78([N]5=CC=C4)([N]9=CC="
"Cc1c9c2c(cc1)C=CC=[N]72)[N]1=CC=Cc2c1c1c(cc2)C=CC=[N]81",
"c1ccc2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"c1ccc2c(c1)nc3c(n2)C4=CC=C[N]5=C4C6=[N]([Ru+2]578([N]9=C1C(=NC=C9)C="
"CC2=NC=C[N]7=C21)[N]1=C2C(=NC=C1)C=CC1=NC=C[N]8=C12)C=CC=C36",
"c1ccc2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"c1ccc2c(c1)nc3c(n2)C4=CC=C[N]5=C4C6=[N]([Ru]578([N]9=C(C=CC=C9)C1=CC="
"CC=[N]71)[N]1=CC=CC=C1C1=CC=CC=[N]81)C=CC=C36",
"c1ccc2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"c1ccc2c(c1)nc3c(n2)C4=CC=C[N]5=C4C6=[N]([Ru]578([N]9=C(C=CC=C9)C1=[N]"
"7C=CC=C1)[N]1=CC=CC=C1C1=CC=CC=[N]81)C=CC=C36",
"c1ccc2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"C1=CC(C=C1)[Ru@]2(N3C=CC=C4C3=C5[N]2=C6C=CC(=CC6=C5C7=C4C(=O)NC7=O)O)C#"
"O",
"O=C1NC(=O)c2c1c1ccc[nH]c1c1nc3ccc(O)cc3c21"},
{"c1c(c(cc2c1nc3c4c5c6c(c3n2)C=CC=[N]6[Ru]78([N]5=CC=C4)([N]9=C1C(=NC=C9)"
"C=CC2=NC=C[N]7=C21)[N]1=C2C(=NC=C1)C=CC1=NC=C[N]8=C12)C#N)C#N",
"N#Cc1cc2nc3c4cccnc4c4ncccc4c3nc2cc1C#N"},
{"c1ccc(cc1)C2=C3C=CC4=CC5=[N]6C(=C(c7ccc8n7[Zn]6(N43)[N]9=C2C=CC9=C8)"
"c1ccc(cc1)C(=O)O)C=C5",
"O=C(O)c1ccc(-c2c3nc(cc4ccc([nH]4)c(-c4ccccc4)c4nc(cc5ccc2[nH]5)C=C4)C="
"C3)cc1"},
{"c1ccc(cc1)C2=C3C=CC4=[N]3[Fe]56n7c2ccc7C=C8[N]5=C(C=C8)C(=C9N6C(="
"C4c1ccccc1)C=C9)c1ccccc1",
"C1=Cc2nc1cc1ccc([nH]1)c(-c1ccccc1)c1nc(c(-c3ccccc3)c3ccc([nH]3)c2-"
"c2ccccc2)C=C1"},
{"c1ccc(cc1)C2=C3C=CC4=[N]3[Fe]56n7c2ccc7C=C8[N]5=C(C=C8)C(=C9N6C(=C4)C="
"C9)c1ccccc1",
"C1=Cc2nc1cc1ccc([nH]1)c(-c1ccccc1)c1nc(cc3ccc([nH]3)c2-c2ccccc2)C=C1"},
{"c1ccc(cc1)C2=C3C=CC4=[N]3[Fe]56n7c2ccc7N=C8[N]5=C(C=C8)C(=C9N6C(=N4)C="
"C9)c1ccccc1",
"C1=Cc2nc1nc1ccc([nH]1)c(-c1ccccc1)c1nc(nc3ccc([nH]3)c2-c2ccccc2)C=C1"},
{"c1ccc(cc1)C2=C(C3=[N]4C(=C5C=CC6=C(C(=C7C=CC8=[N]7[Co]4(N56)n9c8ccc92)"
"c1ccccc1)c1ccccc1)C=C3)c1ccccc1",
"C1=Cc2nc1c(-c1ccccc1)c(-c1ccccc1)c1ccc([nH]1)c1nc(c(-c3ccccc3)c(-"
"c3ccccc3)c3ccc2[nH]3)C=C1"},
{"c1ccc(cc1)C[C@H]2C(=O)O[Cu]3[N]2=Cc4ccccc4O3",
"O=C(O)[C@H](Cc1ccccc1)N=Cc1ccccc1O"},
{"c1ccc(cc1)[C@H]2COC3=[N]2[Rh]4c5c3cccc5C6=[N]4[C@H](CO6)c7ccccc7",
"[Rh]c1c(C2=N[C@@H](c3ccccc3)CO2)cccc1C1=N[C@@H](c2ccccc2)CO1"},
{"c1cc(ccc1C[N@]23CCCN4[Ni]25N(CCCN5CC3)CC4)C[N@]67CCC[N@@]8[Ni@@]69[N@]("
"CCC[N@]9CC7)CC8",
"c1cc(CN2CCCNCCNCCCNCC2)ccc1CN1CCCNCCNCCCNCC1"},
{"c1cc(ccc1C[N@]23CCC[N@H]4[Cu@@]25[N@H](CCC[N@H]5CC3)CC4)C[N@@]67CCC[N@"
"H]8[Cu]69[N@H](CCC[N@H]9CC7)CC8",
"c1cc(CN2CCCNCCNCCCNCC2)ccc1CN1CCCNCCNCCCNCC1"},
{"c1cc(ccc1CNC(=O)C23[CH]4=[CH]5[Re]426([CH]5=[CH]63)(C#O)(C#O)C#O)S(=O)("
"=O)N",
"NS(=O)(=O)c1ccc(CNC(=O)C2C=CC=C2)cc1"},
{"c1cc(ccc1NC(=O)CCCC[C@H]2[C@@H]3[C@H](CS2)NC(=O)N3)S(=O)(=O)[N-]4CC["
"NH2][Ir+3]4",
"NCCNS(=O)(=O)c1ccc(NC(=O)CCCC[C@@H]2SC[C@@H]3NC(=O)N[C@H]23)cc1"},
{"c1cc(ccc1NC(=O)CCCC[C@H]2[C@@H]3[C@H](CS2)NC(=O)N3)S(=O)(=O)[N@@]4CCN["
"Ru]456789([CH]1=[CH]5[CH]6=[CH]7[CH]8=[CH]91)Cl",
"NCCNS(=O)(=O)c1ccc(NC(=O)CCCC[C@@H]2SC[C@@H]3NC(=O)N[C@H]23)cc1"},
{"C1CCC(CC1)[NH2][Pt+2][NH3]", "NC1CCCCC1"},
{"c1ccc(cc1)[P](c2ccccc2)(c3ccccc3)[Pt+2]4(c5ccccc5C6=CC=CC=[N]64)Cl",
"c1ccc(P(c2ccccc2)c2ccccc2)cc1"},
{"C1CC[C@@H]2[C@@H](C1)[N]34CC5=[N]([Fe]367([N]2(CC8=CC=CC=[N]68)CC(=O)"
"O7)OC(=O)C4)C=CC=C5",
"O=C(O)CN(Cc1ccccn1)[C@@H]1CCCC[C@H]1N(CC(=O)O)Cc1ccccn1"},
{"C1CC[C@@H]2[C@@H](C1)[NH2][Pt+2][NH2]2", "N[C@@H]1CCCC[C@H]1N"},
{"C1=CC=[N]2C(=C1)C3=CC=CC4=[N]3[Pt+]2([N]5=C4C=CC=C5)Cl",
"c1ccc(-c2cccc(-c3ccccn3)n2)nc1"},
{"C1=CC=[N]2C(=C1)C3=CC=CC=[N]3[Ru+2]245([N]6=C7C(=CC=C6)c8c(nc9c1c2c3c("
"c9n8)C=CC=[N]3[Ru+2]36([N]2=CC=C1)([N]1=C(C=CC=C1)C1=[N]3C=CC=C1)[N]1="
"C(C=CC=C1)C1=[N]6C=CC=C1)C1=CC=C[N]4=C17)[N]1=CC=CC=C1C1=CC=CC=[N]51",
"c1cnc2c(c1)c1nc3c4cccnc4c4ncccc4c3nc1c1cccnc12"},
{"C1=CC=[N]2C(=C1)C3=CC=CC=[N]3[Ru+2]245([N]6=C(C=CC=C6)C7=[N]4C=CC=C7)["
"N]8=C9C(=CC=C8)c1c(nc2c3c4c6c(c2n1)C=CC=[N]6[Ru+2]12([N]4=CC=C3)([N]3="
"C(C=CC=C3)C3=[N]1C=CC=C3)[N]1=C(C=CC=C1)C1=[N]2C=CC=C1)C1=C9[N]5=CC=C1",
"c1cnc2c(c1)c1nc3c4cccnc4c4ncccc4c3nc1c1cccnc12"},
{"C1=CC=[N]2C(=C1)C3=[N]4[Ru+2]25([N]6=C(C4=CC=C3)C=CC=C6)[N]7=C8C(=CC="
"C7)C=CC9=CC=C[N]5=C98",
"c1ccc(-c2cccc(-c3ccccn3)n2)nc1"},
{"C1=CC=[N]2C(=C1)N(C3=[N]([Ru]2Cl)C=CC=C3)CCCCCN",
"NCCCCCN(c1ccccn1)c1ccccn1"},
{"c1ccnc(c1)C2=[N](C=CC=C2)[Ru]([N]3=CNC=C3)[N]4=C(C=CC=C4)c5ccccn5",
"c1ccc(-c2ccccn2)nc1"},
{"C1=CC=[N](C=C1)[Pt+2]([NH3])([NH3])Cl", "c1ccncc1"},
{"C1CC(=O)N(C1=O)CCC23=[CH]4[Fe]2567891([CH]3=[CH]5[C@H]64)[CH]2=[CH]7C8["
"CH]9=[CH]12",
"O=C1CCC(=O)N1CCC1=CCC=C1"},
{"C1CC(=O)N(C1=O)CCCCCN2C3=[N](C=CC=C3)[Ru]([N]4=CC=CC=C42)Cl",
"O=C1CCC(=O)N1CCCCCN(c1ccccn1)c1ccccn1"},
{"C1[C@H]2[C@@H]([C@@H](S1)CCCCC(=O)NCCC3O[Co]45(O6[Co]7(O4[Co]8(O3)(O7["
"Co]6(O58)([N]9=CC=CC=C9)[O])([N]1=CC=CC=C1)[O])([N]1=CC=CC=C1)[O])[O])"
"NC(=O)N2",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCC(O)O"},
{"C1[C@H]2[C@@H]([C@@H](S1)CCCCC(=O)NCCC3O[Co]45(O6[Co]7(O4[Co]8(O3)(O7["
"Co]6(O58)([N]9=CC=CC=C9)([O])[O])([N]1=CC=CC=C1)[O])[N]1=CC=CC=C1)([N]"
"1=CC=CC=C1)[O])NC(=O)N2",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCC(O)O"},
{"C1[C@H]2[C@@H]([C@@H](S1)CCCCC(=O)NCCCO[C@]34C5=[N]6C(=CC=C5)C7=[N](["
"Co]68([N]9=CC=CC=C9C1=CC=CC3=[N]81)([N]1=CC=CC=C41)[O])C=CC=C7)NC(=O)"
"N2",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCCOC(c1ccccn1)(c1cccc(-"
"c2ccccn2)n1)c1cccc(-c2ccccn2)n1"},
{"C1[C@@H]([C@H](O[C@H]1N2C=[N](C3=C2N=C(NC3=O)N)[Pt](N)(N)[N]4=C5C=CC="
"CC5=C6C=CC=CC6=C4)COP(=O)(O)O)O",
"Nc1nc2c(ncn2[C@H]2C[C@H](O)[C@@H](COP(=O)(O)O)O2)c(=O)[nH]1"},
{"C1=C[N]2=C3C(=C1)C=CC4=CC=C[N](=C43)[Re]2(C#O)(C#O)C#O",
"c1cnc2c(c1)ccc1cccnc12"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2[N]4=C1C=CC=C4)CCCNC(=O)CCCC[C@H]5[C@@H]6["
"C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2([N]4=C1C=CC=C4)N=[N+]=[NH-])CCNC(=O)CCCC["
"C@H]5[C@@H]6[C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2([N]4=C1C=CC=C4)(N=[N+]=[NH-])[O])CCCNC(=O)"
"CCCC[C@H]5[C@@H]6[C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2([N]4=C1C=CC=C4)[O])CCCNC(=O)CCCC[C@H]5[C@@"
"H]6[C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2([N]4=C1C=CC=C4)[O])CCNC(=O)CCCC[C@H]5[C@@"
"H]6[C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2([N]4=C1C=CC=C4)([O])[O])CCNC(=O)CCCC[C@H]"
"5[C@@H]6[C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2([N]4=C1C=CC=C4)OO)CCNC(=O)CCCC[C@H]5[C@@H]"
"6[C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2([N]4=C1C=CC=C4)([O])OO)CCNC(=O)CCCC[C@H]5["
"C@@H]6[C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=CC=CC=[N]3[Cu]2[N]4=CC=CC=C41)CCCCNC(=O)CCCC[C@H]5[C@@H]6["
"C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1C[N]2(CCC3=[N]([Cu]2[N]4=C1C=CC=C4)C=CC=C3)CCNC(=O)CCCC[C@H]5[C@@H]6["
"C@H](CS5)NC(=O)N6",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCN(CCc1ccccn1)CCc1ccccn1"},
{"C1=C[N](=CN1)[Cu+]([N]2=CNC=C2)([N]3=CNC=C3)([N]4=CNC=C4)([OH2])[OH2]",
"c1c[nH]cn1"},
{"c1cn(cn1)[Os+2]23([N]4=C(C=CC=C4)C5=CC=CC=[N]52)[N]6=C(C=CC=C6)C7=CC="
"CC=[N]37",
"c1ccc(-c2ccccn2)nc1"},
{"c1cn(cn1)[Os+2]23([N]4=C(C=CC=C4)C5=CC=CC=[N]52)[N]6=CC=CC=C6C7=CC=CC=["
"N]37",
"c1ccc(-c2ccccn2)nc1"},
{"C1=C[N](=CN1)[Re+](C#O)(C#O)(C#O)[OH2]", "c1c[nH]cn1"},
{"c1cn(cn1)[Ru+2]23([N]4=C(C=CC=C4)C5=CC=CC=[N]52)[N]6=CC=CC=C6C7=CC=CC=["
"N]37",
"c1ccc(-c2ccccn2)nc1"},
{"c1cn(cn1)[Ru+2]23([N]4=C(C=CC=C4)C5=[N]2C=CC=C5)[N]6=CC=CC=C6C7=CC=CC=["
"N]37",
"c1ccc(-c2ccccn2)nc1"},
{"C1C[N@@H]2CC[N@@H]3[Cu]24[N@@H](C1)CC[N@@H]4CCC3", "C1CNCCNCCCNCCNC1"},
{"C1C[NH2][Pt+]2([NH2]1)I[Pt+]3(I2)[NH2]CC[NH2]3", "NCCN"},
{"C1C[N][Ru]23456([N]1)(C7=C2C38=C4(C5=C67)CC9=C(C8)CC=CC9)Cl",
"C1=CCC2=C(C1)Cc1ccccc1C2"},
{"C1C([O@@H][Fe]234[O@H]C(C[C@@]56[OH]2[Fe]7([OH]3[C@]1(CC([O@@H]7)[O])C("
"[O@@H]4)[O])([O@H]C(C5)[O])[O@H]C6[O])[O])[O]",
"[O]C(O)CC(O)(CC([O])O)C([O])O"},
{"C1C[O@@H][Y]234[N]1(CC[O@@H]2)C(C[OH]3)(C[O@@H]4)CO",
"OCCN(CCO)C(CO)(CO)CO"},
{"C[As-](C)(O)OC1=[O+][Na]2345OC(=O)C[O+]2c6c7cc(cc6Cc8cc(cc(c8[O+]3CC(="
"O)O)Cc9cc(cc(c9[O+]4C1)Cc1cc(cc(c1[O+]5CC(=O)O)C7)S(=O)(=O)O)S(=O)(=O)"
"O)S(=O)(=O)O)S(=O)(=O)O",
"C[AsH](C)(O)OC(=O)COc1c2cc(S(=O)(=O)O)cc1Cc1cc(S(=O)(=O)O)cc(c1OCC(=O)"
"O)Cc1cc(S(=O)(=O)O)cc(c1OCC(=O)O)Cc1cc(S(=O)(=O)O)cc(c1OCC(=O)O)C2"},
{"C[C-]12C3(=C4([Ir+3]1356(C2(=C54C)C)([N-](CC7=[N]6C=CC(=C7)c8ccc(cc8)S("
"=O)(=O)N)S(=O)(=O)c9ccccc9)[Cl-])C)C",
"NS(=O)(=O)c1ccc(-c2ccnc(CNS(=O)(=O)c3ccccc3)c2)cc1"},
{"CC12C3([Ir]1456(C2(C4(C53C)C)C)([N]7=C(C=CC=C7)C(=O)N6CCc8ccc(cc8)S(=O)"
"(=O)N)Cl)C",
"NS(=O)(=O)c1ccc(CCNC(=O)c2ccccn2)cc1"},
{"CC12C3([Ir]1456(C2(C4(C53C)C)C)[N]7=CC=C(C=C7C(=O)[N]6(CCCc8ccc(cc8)S(="
"O)(=O)N)Cl)O)C",
"NS(=O)(=O)c1ccc(CCCN(Cl)C(=O)c2cc(O)ccn2)cc1"},
{"CC12C3([Ir]1456(C2(C4(C53C)C)C)([N]7=CC=C(C=C7C(=O)N6CC(=O)Nc8ccc(cc8)"
"S(=O)(=O)N)O)Cl)C",
"NS(=O)(=O)c1ccc(NC(=O)CNC(=O)c2cc(O)ccn2)cc1"},
{"CC12C3([Ir]1456(C2(C4(C53C)C)C)([N]7=C(C=C(C=C7)O)C(=O)N6CCc8ccc(cc8)S("
"=O)(=O)N)Cl)C",
"NS(=O)(=O)c1ccc(CCNC(=O)c2cc(O)ccn2)cc1"},
{"CC12=C3([Ir]145C2(=C4(C53C)C)C)C", "CC1=C(C)C(C)C(C)=C1C"},
{"CC12=C3([Rh+]145(C2(=C4(C53C)CCNC(=O)CCCCC6C7C(CS6)NC(=O)N7)C)(Cl)(Cl)"
"Cl)C",
"CC1=C(C)C(C)C(CCNC(=O)CCCCC2SCC3NC(=O)NC32)=C1C"},
{"C[C@@]12CC(=O)N[C@@]13C[C@H]4[C@H]([C@](C5=[N]4[Ni+]67[N]3=C([C@H]2CCC("
"=O)O)C=C8N6C(=C9C1=[N]7[C@H](C5)[C@H]([C@@H]1C[C@@H](C9=O)SC)CC(=O)O)["
"C@H]([C@@H]8CC(=O)O)CCC(=O)O)(C)CC(=O)N)CCC(=O)O",
"CS[C@H]1C[C@@H]2C3=N[C@H](CC4=N[C@@H](C[C@@]56N=C(C=C7NC(=C3C1=O)[C@@H]"
"(CCC(=O)O)[C@@H]7CC(=O)O)[C@@H](CCC(=O)O)[C@]5(C)CC(=O)N6)[C@@H](CCC(="
"O)O)[C@]4(C)CC(N)=O)[C@H]2CC(=O)O"},
{"C[C@@]12CC(=O)N[C@@]13C[C@H]4[C@H]([C@](C5=[N]4[Ni+]67[N]3=C([C@H]2CCC("
"=O)O)C=C8N6C(=C9C(=O)CC[C@@H]1C9=[N]7[C@H](C5)[C@H]1CC(=O)O)[C@H]([C@@"
"H]8CC(=O)O)CCC(=O)O)(C)CC(=O)N)CCC(=O)O",
"C[C@@]1(CC(N)=O)C2=N[C@@H](C[C@@]34N=C(C=C5NC(=C6C(=O)CC[C@@H]7C6=N[C@"
"H](C2)[C@H]7CC(=O)O)[C@@H](CCC(=O)O)[C@@H]5CC(=O)O)[C@@H](CCC(=O)O)[C@]"
"3(C)CC(=O)N4)[C@H]1CCC(=O)O"},
{"Cc1c2cc3[n+]4c(cc5c(c(c6n5[Ga+3]47n2c(c1CCC(=O)O)cc8[n+]7c(c6)C(=C8CCC("
"=O)O)C)C=C)C)C(=C3C)C=C",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5C=C)C(C)=C4CCC(=O)O)c("
"CCC(=O)O)c3C"},
{"Cc1c2cc3[n+]4c(cc5c(c(c6n5[Mg@]47n2c(c1CCC(=O)O)cc8[n+]7c(c6)C(=C8CCC(="
"O)O)C)C)C=C)C(=C3C=C)C",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C)c3C=C"},
{"CC1=C2C=CC3=C4C2=[N](C=C1)[Re]([N]4=CC=C3C)(C#O)(C#O)C#O",
"Cc1ccnc2c1ccc1c(C)ccnc12"},
{"CC1=C2[C@]([C@H]([C@H]3[N-]2[Co+2]45[N]6=C1[C@H](C(C6=CC7=[N]4C(=C(C8=["
"N]5[C@@]3([C@@]([C@@H]8CCC(=O)N)(C)CC(=O)N)C)C)[C@@]([C@@H]7CCC(=O)N)("
"C)CC(=O)N)(C)C)CCC(=O)N)CC(=O)N)(C)CCC(=O)NC[C@@H](C)O",
"CC1=C2N=C(C=C3N=C(C(C)=C4N[C@H]([C@H](CC(N)=O)[C@@]4(C)CCC(=O)NC[C@@H]("
"C)O)[C@]4(C)N=C1[C@@H](CCC(N)=O)[C@]4(C)CC(N)=O)[C@@H](CCC(N)=O)C3(C)C)"
"[C@@H](CCC(N)=O)[C@]2(C)CC(N)=O"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=CC6=[N]7[Fe@]3(N45)[N]8=C(C=C7C(=C6CCC(=O)O)"
"C=O)C(=C(C8=C2)[C@H](CC\\C=C(/C)\\CC\\C=C(/C)\\CC\\C=C(/"
"C)\\CCC=C(C)C)O)C)CCC(=O)O)C",
"C=Cc1c(C)c2cc3nc(cc4nc(cc5[nH]c(cc1[nH]2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C=O)C(C)=C3[C@@H](O)CC/C=C(\\C)CC/C=C(\\C)CC/C=C(\\C)CCC=C(C)C"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=[N]4[Cr]36[N]7=C(C=C8N6C(=C5)C(=C8CCC(=O)O)"
"C)C(=C(C7=C2)C)CCC(=O)O)C=C)C",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C)c3C=C"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=[N]4[Fe@@]36[N]7=C(C=C8N6C(=C5)C(=C8C)CCC(="
"O)O)C(=C(C7C2)C=C)C)CCC(=O)O)C",
"C=CC1=C(C)C2=NC1Cc1[nH]c(c(C=C)c1C)C=C1N=C(C=c3[nH]c(c(C)c3CCC(=O)O)="
"C2)C(CCC(=O)O)=C1C"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C)CCC(=O)"
"O)C(=C(C7=C2)[C@H](C)OO)C)CCC(=O)O)C",
"C=Cc1c(C)c2cc3nc(cc4[nH]c(cc5nc(cc1[nH]2)C(C)=C5CCC(=O)O)c(CCC(=O)O)"
"c4C)C(C)=C3[C@H](C)OO"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C)CCC(=O)"
"O)C(=C(C7=C2)C=O)C)CCC(=O)O)C",
"C=Cc1c(C)c2cc3nc(cc4[nH]c(cc5nc(cc1[nH]2)C(C)=C5CCC(=O)O)c(CCC(=O)O)"
"c4C)C(C)=C3C=O"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=[N]4[Fe]36([N]7=C(C=C8N6C(=C5)C(=C8CCC(=O)O)"
"C)C(=C(C7=C2)C)CCC(=O)O)c9ccccc9)C=C)C",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C)c3C=C"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=[N]4[Fe]36([N]7=C(C=C8N6C(=C5)C(=C8CCC(=O)O)"
"C)C(=C(C7=C2)C)CCC(=O)O)c9ccc(cc9)Cl)C=C)C",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C)c3C=C"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C=O)CCC(="
"O)O)C(=C(C7=C2)[C@H](CC/C=C(\\C)/CC/C=C(\\C)/CCC=C(C)C)O)C)CCC(=O)O)C",
"C=Cc1c(C)c2cc3nc(cc4[nH]c(cc5nc(cc1[nH]2)C(C)=C5CCC(=O)O)c(CCC(=O)O)"
"c4C=O)C(C)=C3[C@@H](O)CC/C=C(\\C)CC/C=C(\\C)CCC=C(C)C"},
{"Cc1c2n3c(c1C=C)C=C4C(=C(C5=[N]4[Zn]36[N]7=C(C=C8N6C(=C5)C(=C8C)CCC(=O)"
"O)C(=C(C7=C2)C=C)C)CCC(=O)O)C",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5C=C)C(C)=C4CCC(=O)O)c("
"CCC(=O)O)c3C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=CC6=[N]7[Fe]3(N45)[N]8=C(C=C7[C@@](C6="
"O)(C)CC(=O)O)C(=O)[C@](C8=C2)(C)CC(=O)O)C)CCC(=O)O",
"Cc1c(CCC(=O)O)c2cc3[nH]c(cc4nc(cc5nc(cc1[nH]2)C(=O)[C@]5(C)CC(=O)O)C(="
"O)[C@]4(C)CC(=O)O)c(C)c3CCC(=O)O"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Co]36[N]7=C(C=C8N6C(=C5)C(=C8C=C)"
"C)C(=C(C7=C2)C=C)C)C)CCC(=O)O",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C)c3C=C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Fe+2]36[N]7=C(C(C(C7=C2)C=C)C)C(="
"C8N6C(=C5)C(=C8C=C)C)c9ccccc9)C)CCC(=O)O",
"C=Cc1c(C)c2cc3nc(cc4[nH]c(cc5nc(c(-c6ccccc6)c1[nH]2)C(C)C5C=C)c(C)"
"c4CCC(=O)O)C(CCC(=O)O)=C3C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C=C)"
"C)[C@]9(C(C7=C2)C=CS9)C)C)CCC(=O)O",
"C=Cc1c(C)c2cc3nc(cc4[nH]c(cc5nc(cc1[nH]2)[C@]1(C)SC=CC51)c(C)c4CCC(=O)"
"O)C(CCC(=O)O)=C3C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C)C="
"C)C(=C(C7=C2)C)C=C)C)CCC(=O)O",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5C=C)C(C)=C4CCC(=O)O)c("
"CCC(=O)O)c3C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C)C="
"C)C(=C(C7=C2)C)/C=C/[N+](=O)[O-])C)CCC(=O)O",
"C=Cc1c(C)c2cc3nc(cc4[nH]c(cc5nc(cc1[nH]2)C(C)=C5CCC(=O)O)c(CCC(=O)O)"
"c4C)C(C)=C3/C=C/[N+](=O)[O-]"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C)"
"CCC(=O)O)C(=C(C7=C2)C)C=C)C)CCC(=O)O",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(C)=C4CCC(=O)"
"O)c(CCC(=O)O)c3C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[In]36[N]7=C(C=C8N6C(=C5)C(=C8C)C="
"C)C(=C(C7=C2)C)C=C)C)CCC(=O)O",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5C=C)C(C)=C4CCC(=O)O)c("
"CCC(=O)O)c3C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Mg]36[N]7=C(C=C8N6C(=C5)C(=C8)C)C("
"=CC7=C2)C)C)CCC(=O)O",
"CC1=Cc2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)cc5C)C(C)=C4CCC(=O)O)c(CCC(=O)O)"
"c3C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Mn]36[N]7=C(C=C8N6C(=C5)C(=C8C)"
"CCC(=O)O)C(=C(C7=C2)CCC(=O)O)C)CCC(=O)O)C",
"CC1=C(CCC(=O)O)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)"
"O)=C4C)c(CCC(=O)O)c3C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Ni]36[N]7=C(C=C8N6C(=C5)C(=C8C=C)"
"C)C(=C(C7=C2)C=C)C)C)CCC(=O)O",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C)c3C=C"},
{"Cc1c2n3c(c1CCC(=O)O)C=C4C(=C(C5=[N]4[Zn]36[N]7=C(C=C(C7=C2)C)C=C8N6C(="
"C5)C=C8C)C)CCC(=O)O",
"CC1=Cc2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)=C4C)"
"cc3C"},
{"Cc1c2n3c(c1C=C)[O+]=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C(C7=C2)C)C=C8N6C(=C5)"
"C(=C8CCC(=O)O)C)C=C)C",
"C=CC1=C(C)c2nc1cc1[nH]c(cc3nc(cc4[n-]c([o+]2)c(C=C)c4C)C(C)=C3)c(CCC(="
"O)O)c1C"},
{"Cc1c2n3c(c1C(=C)OO)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8CCC(="
"O)O)C)C(=C(C7=C2)C)CCC(=O)O)C=C)C",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C)c3C(=C)OO"},
{"Cc1c2n3c(c1C(=O)C)C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C)CCC(="
"O)O)C(=C(C7=C2)C(=C)O)C)CCC(=O)O)C",
"C=C(O)C1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5C(C)=O)C(C)=C4CCC(="
"O)O)c(CCC(=O)O)c3C"},
{"CC1=C([C@]2([C@@]3(C(=C(C4=[N]3[Co+]56[N]2=C1C=C7N5C(=CC8=[N]6C(=C4)C(="
"C8CCC(=O)O)C)C(=C7C)CCC(=O)O)C)C)C)C)C",
"CC1=C(CCC(=O)O)C2=NC1=CC1=N[C@@](C)(C(C)=C1C)[C@@]1(C)N=C(C=c3[nH]c(c("
"CCC(=O)O)c3C)=C2)C(C)=C1C"},
{"CC1=C([C@@]2([C@]3(C(=C(C4=[N]3[Co+]56[N]2=C1C=C7N5C(=CC8=[N]6C(=C4)C(="
"C8CCC(=O)O)C)C(=C7C)CCC(=O)O)C)C)C)C)C",
"CC1=C(CCC(=O)O)C2=NC1=CC1=N[C@](C)(C(C)=C1C)[C@]1(C)N=C(C=c3[nH]c(c("
"CCC(=O)O)c3C)=C2)C(C)=C1C"},
{"Cc1cc2c(cc1C)N3C=[N]2[Co]456([N]7=C8C(=C9[N]4=C(C=C1[N]5=C(C(=C2N6C("
"C7C(C8(CCC(=O)NCC(OP(=O)(OC4C(OC3C4O)CO)O)C)C)CC(=O)N)(C(C2CCC(=O)N)(C)"
"CC(=O)N)C)C)C(C1CCC(=O)N)(C)CC(=O)N)C(C9CCC(=O)N)(C)C)C)CC1C(C(C(O1)"
"n1cnc2c1ncnc2N)O)O",
"CC1=C2N=C(C=C3N=C(C(C)=C4NC(C)(C5N=C1C(C)(CCC(=O)NCC(C)OP(=O)(O)OC1C("
"CO)OC(n6cnc7cc(C)c(C)cc76)C1O)C5CC(N)=O)C(C)(CC(N)=O)C4CCC(N)=O)C(C)("
"CC(N)=O)C3CCC(N)=O)C(C)(C)C2CCC(N)=O"},
{"Cc1cc2c(cc1C)N3C=[N]2[Co]456(N7[C@@H]8[C@@H]([C@](C7=C(C9=[N]4C(=CC1=["
"N]5C(=C(C2=[N]6[C@@]8([C@@]([C@@H]2CCC(=O)N)(C)CC(=O)N)C)C)[C@@]([C@@H]"
"1/C=C/"
"C(=O)N)(C)CC(=O)N)C([C@@H]9CCC(=O)N)(C)C)C)(CCC(=O)NC[C@H](OP(=O)(O[C@@"
"H]1[C@H](O[C@H]3[C@@H]1O)CO)O)C)C)CC(=O)N)O",
"CC1=C2N=C(C=C3N=C(C(C)=C4N[C@H]([C@H](CC(N)=O)[C@@]4(C)CCC(=O)NC[C@@H]("
"C)OP(=O)(O)O[C@@H]4[C@@H](CO)O[C@H](n5cnc6cc(C)c(C)cc65)[C@@H]4O)[C@]4("
"C)N=C1[C@@H](CCC(N)=O)[C@]4(C)CC(N)=O)[C@@H](CCC(N)=O)C3(C)C)[C@@H](/"
"C=C/C(N)=O)[C@]2(C)CC(N)=O"},
{"Cc1cc2c(cc1C)n(cn2)C3C(C(C(O3)CO)OP(=O)(O)OC(C)CNC(=O)CCC4(C(C5C6(C(C("
"C7=[N]6[Co+2]89[N]5=C4C(=C1[NH]8C(=CC2=[N]9C(=C7C)C(C2CCC(=O)N)(C)CC(="
"O)N)C(C1CCC(=O)N)(C)C)C)CCC(=O)N)(C)CC(=O)N)C)CC(=O)N)C)O",
"CC1=C2NC(=CC3=NC(=C(C)C4=NC(C)(C5N=C1C(C)(CCC(=O)NCC(C)OP(=O)(O)OC1C("
"CO)OC(n6cnc7cc(C)c(C)cc76)C1O)C5CC(N)=O)C(C)(CC(N)=O)C4CCC(N)=O)C(C)("
"CC(N)=O)C3CCC(N)=O)C(C)(C)C2CCC(N)=O"},
{"Cc1cc2c(cc1C)n(cn2)[C@@H]3[C@@H]([C@@H]([C@H](O3)CO)O[P@@](=O)(O)O[C@H]"
"(C)CNC(=O)CC[C@@]4([C@H](C5=[N-]6C4=C(C7=[N]8[Co+2]69([N]1=C(C=C8C([C@@"
"H]7CCC(=O)N)(C)C)[C@H]([C@](C1=C(C1=[N]9[C@@]5([C@@]([C@@H]1CCC(=O)N)("
"C)CC(=O)N)C)C)(C)CC(=O)N)CCC(=O)N)C)C)CC(=O)N)C)O",
"CC1=C2N=C(C=C3N=C(C(C)=C4N=C([C@H](CC(N)=O)[C@@]4(C)CCC(=O)NC[C@@H](C)"
"O[P@](=O)(O)O[C@@H]4[C@@H](CO)O[C@H](n5cnc6cc(C)c(C)cc65)[C@@H]4O)[C@]"
"4(C)N=C1[C@@H](CCC(N)=O)[C@]4(C)CC(N)=O)[C@@H](CCC(N)=O)C3(C)C)[C@@H]("
"CCC(N)=O)[C@]2(C)CC(N)=O"},
{"Cc1cc2c(cc1C)n(cn2)[C@@H]3[C@@H]([C@@H]([C@H](O3)CO)O[P@@](=O)(O)O[C@H]"
"(C)CNC(=O)CC[C@@]4([C@H](C5=[N-]6C4=C(C7=[N]8[Co+2]69([N]1=C(C=C8C([C@@"
"H]7CCC(=O)N)(C)C)[C@H]([C@](C1=C(C1=[N]9[C@@]5([C@@]([C@@H]1CCC(=O)N)("
"C)CC(=O)N)C)C)(C)CC(=O)N)CCC(=O)N)C#N)C)CC(=O)N)C)O",
"CC1=C2N=C(C=C3N=C(C(C)=C4N=C([C@H](CC(N)=O)[C@@]4(C)CCC(=O)NC[C@@H](C)"
"O[P@](=O)(O)O[C@@H]4[C@@H](CO)O[C@H](n5cnc6cc(C)c(C)cc65)[C@@H]4O)[C@]"
"4(C)N=C1[C@@H](CCC(N)=O)[C@]4(C)CC(N)=O)[C@@H](CCC(N)=O)C3(C)C)[C@@H]("
"CCC(N)=O)[C@]2(C)CC(N)=O"},
{"Cc1cc2c(cc1C)n(cn2)[C@@H]3[C@@H]([C@@H]([C@H](O3)CO)O[P@@](=O)(O)O[C@H]"
"(C)CNC(=O)CC[C@@]4([C@H]([C@@H]5[C@]6([C@@]([C@@H](C7=C([C@H]8[C@@]([C@"
"@H](C9=CC1C([C@@H](C2=C(C4[N-]5[Co+2](N12)(N89)(N76)"
"CCCCCn1cnc2c1ncnc2N)C)CCC(=O)N)(C)C)CCC(=O)N)(C)CC(=O)N)C)CCC(=O)N)(C)"
"CC(=O)N)C)CC(=O)N)C)O",
"CC1=C2NC(C=C3N[C@@H](C(C)=C4N[C@@](C)([C@@H]5NC1[C@](C)(CCC(=O)NC[C@@H]"
"(C)O[P@](=O)(O)O[C@@H]1[C@@H](CO)O[C@H](n6cnc7cc(C)c(C)cc76)[C@@H]1O)["
"C@H]5CC(N)=O)[C@@](C)(CC(N)=O)[C@@H]4CCC(N)=O)[C@@](C)(CC(N)=O)[C@@H]"
"3CCC(N)=O)C(C)(C)[C@@H]2CCC(N)=O"},
{"CC1=C(C2=[N]3C1=Cc4c(c(c5n4[Fe]36[N]7=C(C=C8N6C(=C2)C(=C8C)CCC(=O)O)C(="
"C(C7=C5)C=C)C=C)C=C)C=C)CCC(=O)O",
"C=CC1=C(C=C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C=C)c3C=C"},
{"Cc1cc2n3c1C=C4C=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8CCC(=O)O)C)C(=C("
"C7=C2)C)CCC(=O)O)C",
"CC1=Cc2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)=C4C)"
"cc3C"},
{"Cc1c(c2n3c1C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8C(=O)O)C)C(=C("
"C7=C2)C)C(=O)O)C)C)C",
"CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5C)C(C)=C4C(=O)O)c(C(=O)O)"
"c3C"},
{"Cc1c(c2n3c1C(=C4C(=C(C5=[N]4[Zn]36[N]7=C(C=C8N6C(=C5)C(=C8C=C)C)C(=C("
"C7=C2)CCC(=O)O)C)C=C)C)O)CCC(=O)O",
"C=CC1=C(C)c2nc1cc1[nH]c(cc3nc(cc4[nH]c(c(C)c4CCC(=O)O)c2O)C(CCC(=O)O)="
"C3C)c(C=C)c1C"},
{"Cc1cc(c2c(c1)nc3c4c5c6c(c3n2)C=CC=[N]6[Ru]78([N]5=CC=C4)([N]9=CC="
"Nc1c9c2c(cc1)N=CC=[N]72)[N]1=CC=Nc2c1c1c(cc2)N=CC=[N]81)C",
"Cc1cc(C)c2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"Cc1ccc2c(c1)nc3c4c5c6c(c3n2)C=CC=[N]6[Ru]78([N]5=CC=C4)([N]9=CC="
"Nc1c9c2c(cc1)N=CC=[N]72)[N]1=CC=Nc2c1c1c(cc2)N=CC=[N]81",
"Cc1ccc2nc3c4cccnc4c4ncccc4c3nc2c1"},
{"CC1=CC=C2C=CC3=CC=C([N]4=C3C2=[N]1[Pt]45([C][C]5)C)C",
"Cc1ccc2ccc3ccc(C)nc3c2n1"},
{"CC1=CC=C2C=CC3=CC=C([N]4=C3C2=[N]1[Pt]45(CC5)[N]6=CN(C(=C6)c7cn(nn7)[C@"
"@H]8[C@H]([C@H]([C@H]([C@H](O8)O)O)O)O)C)C",
"Cn1cncc1-c1cn([C@H]2O[C@H](O)[C@H](O)[C@H](O)[C@@H]2O)nn1"},
{"Cc1cccc2c1nc3c(n2)C4=CC=C[N]5=C4C6=C3C=CC=[N]6[Ru+2]578([N]9=CC="
"Nc1c9c2c(cc1)N=CC=[N]72)[N]1=CC=Nc2c1c1c(cc2)N=CC=[N]81",
"Cc1cccc2nc3c4cccnc4c4ncccc4c3nc12"},
{"CC1=CC=CC2=[N]1[Cu]3[N](=C2)NC(=[S]3)N(C)C",
"Cc1cccc(C=NNC(=S)N(C)C)n1"},
{"Cc1ccc(cc1)C(C)C.c1ccc(cc1)NC2=[S][Os]([N]3=C2C=CC=C3)Cl",
"S=C(Nc1ccccc1)c1ccccn1"},
{"Cc1cccc(c1)[Fe]234n5c6c(c(c5C=C7[N]2=C(C=C8N3C(=CC9=[N]4C(=C6)C(=C9C)C="
"C)C(=C8CCC(=O)O)C)C(=C7C)CCC(=O)O)C=C)C",
"C=CC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5C=C)C(C)=C4CCC(=O)O)c("
"CCC(=O)O)c3C"},
{"CC1=CC=[N]2C(=C1)C3=CC(=CC=[N]3[Fe]2(C#N)(C#N)(C#N)C#N)CNC(=O)CCCC[C@H]"
"4[C@@H]5[C@H](CS4)NC(=O)N5",
"Cc1ccnc(-c2cc(CNC(=O)CCCC[C@@H]3SC[C@@H]4NC(=O)N[C@H]34)ccn2)c1"},
{"CC1=[CH]2C=C3([Ru+]24([CH]1=C3)([NH2][C@@H]5CN(C[C@H]5[NH2]4)C(=O)CCCC["
"C@H]6[C@@H]7[C@H](CS6)NC(=O)N7)Cl)C(C)C",
"N[C@@H]1CN(C(=O)CCCC[C@@H]2SC[C@@H]3NC(=O)N[C@H]23)C[C@H]1N"},
{"Cc1nc2cc3c(cc2c(n1)N)C4=CC=CC=[N]4[Ru]3([C-]#[O+])C5(C=CC=C5)C(=O)Oc6c("
"cccc6OC)OC",
"COc1cccc(OC)c1OC(=O)C1C=CC=C1"},
{"CC1O[Co]23(O4[Co]5(O1)(O2[Co]67(O3[Co]4(O56)(OC(O7)CCNC(=O)CCCC[C@H]8["
"C@@H]9[C@H](CS8)NC(=O)N9)([N]1=CC=CC=C1)[O])([N]1=CC=CC=C1)[O])([N]1="
"CC=CC=C1)[O])[N]1=CC=CC=C1",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCC(O)O"},
{"CC1O[Co]23(O4[Co]5(O1)(O2[Co]67(O3[Co]4(O56)(OC(O7)CCNC(=O)CCCC[C@H]8["
"C@@H]9[C@H](CS8)NC(=O)N9)([N]1=CC=CC=C1)[O])([N]1=CC=CC=C1)[O])[O])[N]"
"1=CC=CC=C1",
"O=C(CCCC[C@@H]1SC[C@@H]2NC(=O)N[C@H]12)NCCC(O)O"},
{"CC1=O[Ga]2345O=C(N(O2)CCC[C@H]6C(=O)NCC(=O)N[C@H](C(=O)NCC(=O)N[C@@H]("
"CCCN1O3)C(=O)N[C@@H](CCCN(O4)C(=O5)C)C(=O)N6)CO)C",
"CC(=O)N(O)CCC[C@@H]1NC(=O)CNC(=O)[C@H](CO)NC(=O)CNC(=O)[C@H](CCCN(O)C("
"C)=O)NC(=O)[C@H](CCCN(O)C(C)=O)NC1=O"},
{"C\\C=C/"
"1\\c2cc3c(c4c5n3[Mg]67[n+]2c(cc8n6c(cc9[n+]7c(c5[C@H](C4=O)C(=O)OC)[C@"
"H]([C@@H]9C)CCC(=O)OC\\C=C(/"
"C)\\CCC[C@H](C)CCC[C@H](C)CCCC(C)C)c(c8C(=O)C)C)[C@@H]1C)C",
"C/C=C1/"
"c2cc3[nH]c4c(c3C)C(=O)[C@H](C(=O)OC)c4c3nc(cc4[nH]c(cc(n2)[C@@H]1C)c(C("
"C)=O)c4C)[C@@H](C)[C@@H]3CCC(=O)OC/"
"C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C"},
{"C#CC1=C2C=CC3=C(C4=[N]5C(=Cc6ccc7n6[Fe]5(N23)[N]8=C1C=CC8=C7c9ccccc9)C="
"C4)c1ccccc1",
"C#Cc1c2nc(c(-c3ccccc3)c3ccc(cc4nc(c(-c5ccccc5)c5ccc1[nH]5)C=C4)[nH]3)C="
"C2"},
{"C#CC1=C2C=CC3=[N]2[Fe]45n6c1ccc6C(=C7[N]4=C(C=C7)C(=C8N5C(=C3c9ccccc9)"
"C=C8)C#C)c1ccccc1",
"C#Cc1c2nc(c(-c3ccccc3)c3ccc([nH]3)c(C#C)c3nc(c(-c4ccccc4)c4ccc1[nH]4)C="
"C3)C=C2"},
{"CCC1=C(C2=CC3=C(C(=C4[N@]3([Cu@@]56[N]2=C1C=C7N5C(=CC8=[N]6C(=C4)C(="
"C8CCC(=O)O)C)C(=C7C)CCC(=O)O)C)C)CC)C",
"CCC1=C(C)c2cc3c(CC)c(C)c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)"
"O)=C4C)n3C"},
{"CCC1=C(C2=Cc3c(c(c4n3[Fe]56[N]2=C1C=C7N5C8=C(CC(=O)C8=C7C)C9=[N]6C(=C4)"
"[C@H]([C@@H]9CCC(=O)OC)C)C)C=C)C",
"C=Cc1c(C)c2cc3nc(c4c5[nH]c(cc6nc(cc1[nH]2)C(C)=C6CC)c(C)c5C(=O)C4)[C@@"
"H](CCC(=O)OC)[C@@H]3C"},
{"CCC1=C(C2=Cc3c(c(c4n3[Mg]56N2C1=Cc7n5c8c(c7C)C(=O)[C@@H](C8=C9N6C(=C4)["
"C@H]([C@@H]9CCC(=O)OC/C=C(\\C)/"
"CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C)C(=O)OC)C)C=O)C",
"CCc1c(C)c2[nH]c1=Cc1[nH]c3c(c1C)C(=O)[C@H](C(=O)OC)C3=C1NC(=Cc3[nH]c(c("
"C=O)c3C)C=2)[C@@H](C)[C@@H]1CCC(=O)OC/"
"C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C"},
{"CCC1=C(c2cc3c(c(c4n3[Mg]56[n+]2c1cc7n5c8c(c9[n+]6c(c4)C(C9CCC(=O)OC/"
"C=C(\\C)/"
"CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C)[C@@H](C(=O)c8c7C)C(=O)OC)C)C=C)C",
"C=Cc1c(C)c2cc3nc(c4c5[nH]c(cc6nc(cc1[nH]2)C(C)=C6CC)c(C)c5C(=O)[C@H]4C("
"=O)OC)C(CCC(=O)OC/C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C3C"},
{"CCC1=C(c2cc3c(c(c4n3[Mg]56[n+]2c1cc7n5c8c(c9[n+]6c(c4)C(C9CCC(=O)OC/"
"C=C(\\C)/"
"CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C)[C@H](C(=O)c8c7C)C(=O)OC)C)C=C)C=O",
"C=Cc1c(C)c2cc3nc(c4c5[nH]c(cc6nc(cc1[nH]2)C(C=O)=C6CC)c(C)c5C(=O)[C@@H]"
"4C(=O)OC)C(CCC(=O)OC/C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C3C"},
{"CCC1=C(c2cc3c(c(c4n3[Mg]56[n+]2c1cc7n5c8c(c9[n+]6c(c4)C(=C9CCC(=O)O)C)["
"C@H](C(=O)c8c7C)C(=O)OC)C)C=C)C",
"C=Cc1c(C)c2cc3nc(c4c5[nH]c(cc6nc(cc1[nH]2)C(C)=C6CC)c(C)c5C(=O)[C@@H]"
"4C(=O)OC)C(CCC(=O)O)=C3C"},
{"CCC1=C(c2cc3c(c(c4n3[Mg]56[n+]2c1cc7n5c8c(c9[n+]6c(c4)[C@H]([C@@H]9CCC("
"=O)OC/C=C(\\C)/"
"CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C)[C@H](C(=O)c8c7C)C(=O)OC)C)C=C)C",
"C=Cc1c(C)c2cc3nc(c4c5[nH]c(cc6nc(cc1[nH]2)C(C)=C6CC)c(C)c5C(=O)[C@@H]"
"4C(=O)OC)[C@@H](CCC(=O)OC/"
"C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C)[C@@H]3C"},
{"CCC1=C(c2cc3c(c(c4n3[Mg]56[n+]2c1cc7n5c8c(c9[n+]6c(c4)[C@H]([C@@H]9CCC("
"=O)OC/C=C(\\C)/"
"CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C)[C@H](C(=O)c8c7C)C(=O)OC)C)C=C)C",
"C=Cc1c(C)c2cc3nc(c4c5[nH]c(cc6nc(cc1[nH]2)C(C)=C6CC)c(C)c5C(=O)[C@@H]"
"4C(=O)OC)[C@@H](CCC(=O)OC/"
"C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C)[C@@H]3C"},
{"CCC1=C(c2cc3c(c(c4n3[Mg]56[n+]2c1cc7n5c8c(c9[n+]6c(c4)[C@H]([C@@H]9CCC("
"=O)OC/C=C(\\C)/"
"CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C)[C@H](C(=O)c8c7C)C(=O)OC)C)C=C)C",
"C=Cc1c(C)c2cc3nc(c4c5[nH]c(cc6nc(cc1[nH]2)C(C)=C6CC)c(C)c5C(=O)[C@@H]"
"4C(=O)OC)[C@@H](CCC(=O)OC/"
"C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C)[C@@H]3C"},
{"CCC1=C(C2=Cc3c(c(c4n3[Zn]56[N]2=C1C=C7N5C8=C(C(=C(C8=C7C)O)C(=O)OC)C9=["
"N]6C(=C4)C(=C9CCC(=O)OC/C=C(\\C)/"
"CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C)C)C(=O)C)C",
"CCC1=C(C)c2cc3[nH]c(cc4nc(c5c6[nH]c(cc1n2)c(C)c6C(O)=C5C(=O)OC)C(CCC(="
"O)OC/C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C)=C4C)c(C)c3C(C)=O"},
{"CCC1=C(C2=CC3=[N]4C(=CC5=[N]6[Fe]47[N]2=C1C=C8[N]7=C(C=C6C(=C5CCC(=O)O)"
"C)C(=C8C)CC)C(=C3C)CCC(=O)O)C",
"CCC1=C(C)C2=CC3=NC(=CC4=NC(=CC5=NC(=CC1=N2)C(C)=C5CC)C(C)=C4CCC(=O)O)C("
"CCC(=O)O)=C3C"},
{"CCc1c(c2n3c1C=C4C(=C5C6=[N]4[Mg]37[N]8=C(C=C9N7C(=C6[C@](C5=O)(C(=O)OC)"
"O)C(=C9C)CCC(=O)OCC=C(C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C(=C(C8=C2)CC)C)"
"C)C",
"CCC1=C(C)c2cc3[nH]c(c(CCC(=O)OCC=C(C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C)"
"c3C)c3c4nc(cc5[nH]c(cc1n2)c(C)c5CC)C(C)=C4C(=O)[C@]3(O)C(=O)OC"},
{"CCc1c(c2n3c1C=C4C(=C5C(=O)[C@@H](C6=C7C(=C(C8=CC9=[N]([Mg]3(N87)[N]4="
"C65)C(=C2)C(=C9C)CC)C)CCC(=O)OC/C=C(/C)\\CC/C=C(\\C)/"
"CCC=C(C)C)C(=O)OC)C)C",
"CCC1=C(C)c2cc3[nH]c(c(CCC(=O)OC/C=C(/C)CC/"
"C=C(\\C)CCC=C(C)C)c3C)c3c4nc(cc5[nH]c(cc1n2)c(C)c5CC)C(C)=C4C(=O)[C@@H]"
"3C(=O)OC"},
{"CCc1c(c2n3c1C=C4C(=C5C(=O)[C@H](C6=C7C(=C(C8=CC9=[N]([Mg]3(N87)[N]4="
"C65)C(=C2)C(=C9C)CC)C)CCC(=O)OC/C=C(\\C)/CC/C=C(\\C)/"
"CCC=C(C)C)C(=O)OC)C)C",
"CCC1=C(C)c2cc3[nH]c(c(CCC(=O)OC/C=C(\\C)CC/"
"C=C(\\C)CCC=C(C)C)c3C)c3c4nc(cc5[nH]c(cc1n2)c(C)c5CC)C(C)=C4C(=O)[C@H]"
"3C(=O)OC"},
{"CCc1c(c2n3c1C=C4C(=C5C(=O)[C@@H](C6=C7C(=C(C8=CC9=[N]([Mg]3(N87)[N]4="
"C65)C(=C2)C(=C9C=O)C=C)C)CCC(=O)OC/C=C(\\C)/"
"CCC[C@H](C)CCCC(C)CCCC(C)C)C(=O)OC)C)C",
"C=CC1=C(C=O)c2cc3[nH]c(c(CCC(=O)OC/"
"C=C(\\C)CCC[C@H](C)CCCC(C)CCCC(C)C)c3C)c3c4nc(cc5[nH]c(cc1n2)c(C)c5CC)"
"C(C)=C4C(=O)[C@@H]3C(=O)OC"},
{"CCC1=C(C2=[N]3C1=Cc4c(c(c5n4[Fe]36[N]7=C(C=C8N6C(=C2)C(=C8CCC(=O)O)C)C("
"=C(C7=C5)C)CCC(=O)O)C=C)C)C",
"C=Cc1c(C)c2cc3nc(cc4[nH]c(cc5nc(cc1[nH]2)C(C)=C5CCC(=O)O)c(CCC(=O)O)"
"c4C)C(C)=C3CC"},
{"CCc1c(c2n3c1C=C4C(=C(C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8CCC(=O)O)C)C("
"=C(C7=C2)C)CCC(=O)O)CC)C(F)(F)F)C",
"CCC1=C(C(F)(F)F)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(="
"O)O)=C4C)c(C)c3CC"},
{"CCC1=C(C2=[N-]3C1=Cc4c(c(c5n4[Mg]36[N-]7=C8C(=C9N6C(=C2)[C@H]([C@@H]"
"9CCC(=O)OC/C=C(\\C)/CC/C=C(\\C)/"
"CCC=C(C)C)C)[C@H](C(=O)C8=C(C7=C5)C)C(=O)OC)[C@H](C)O)C)C",
"CCC1=C(C)c2cc3[nH]c(c4c5nc(cc6[nH]c(cc1n2)c(C)c6[C@H](C)O)C(C)=C5C(=O)["
"C@@H]4C(=O)OC)[C@@H](CCC(=O)OC/C=C(\\C)CC/C=C(\\C)CCC=C(C)C)[C@@H]3C"},
{"CCc1c(c2n3c1C=C4C(=C(C5=[N]4[Mo]36(=O)[N]7=C(C=C8N6C(=C5)C(=C8C)CCC(=O)"
"O)C(=C(C7=C2)CC)C)CCC(=O)O)C)C",
"CCC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CC)C(C)=C4CCC(=O)O)c("
"CCC(=O)O)c3C"},
{"CCc1c(c2n3c1C=C4C(=C(C5=[N]4[Rh]36[N]7=C(C=C8N6C(=C5)C(=C8CCC(=O)O)C)C("
"=C(C7=C2)C)CCC(=O)O)CC)C)C",
"CCC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CCC(=O)O)C(CCC(=O)O)="
"C4C)c(C)c3CC"},
{"CCc1c(c2n3c1C=C4C(=C(C5=[N]4[Ru@@]36[N]7=C(C=C8N6C(=C5)C(=C8C)CCC(=O)O)"
"C(=C(C7=C2)CC)C)CCC(=O)O)C)C",
"CCC1=C(C)c2cc3[nH]c(cc4nc(cc5[nH]c(cc1n2)c(C)c5CC)C(C)=C4CCC(=O)O)c("
"CCC(=O)O)c3C"},
{"CCc1c(c2n3c1C=C4[C@](C(=O)C5=[N]4[Fe]36[N]7=C(C=C8N6C(=C5)C(=C8CCC(=O)"
"O)C)C(=C(C7=C2)C)CCC(=O)O)(C)CC)C",
"CCc1c(C)c2cc3nc(cc4[nH]c(cc5nc(cc1[nH]2)[C@](C)(CC)C5=O)c(C)c4CCC(=O)O)"
"C(CCC(=O)O)=C3C"},
{"CCCC12C3([Ir]1456(C3(C4(C52C)C)C)(N(CC7=[N]6C=CC(=C7)c8ccc(cc8)S(=O)(="
"O)N)S(=O)(=O)c9ccccc9)Cl)C",
"NS(=O)(=O)c1ccc(-c2ccnc(CNS(=O)(=O)c3ccccc3)c2)cc1"},
{"CC(C)C12=C3[Os]1456(C2=C4C5(=C63)C)(Cl)Cl", "Cc1ccc(C(C)C)cc1"},
{"CC(C)C12=C3[Ru]1456(C2=C4C5(=C63)C)([P]78CN9CN(C7)CN(C9)C8)(Cl)Cl",
"Cc1ccc(C(C)C)cc1"},
{"CC(C)C12=CC=C([Os]1([N]3=C(C=CC=C3)C(=S)Nc4ccc(cc4)F)Cl)(C=C2)C",
"Fc1ccc(NC(=S)c2ccccn2)cc1"},
{"CC(C)C12=[CH]3[Ru]1456([CH]2=[CH]4C5(=[CH]63)C)(Cl)Cl",
"Cc1ccc(C(C)C)cc1"},
{"CCCCCCCCCCCC(=O)N1C2=[N](C=CC=C2)[Rh][N]3=CC=CC=C31",
"CCCCCCCCCCCC(=O)N(c1ccccn1)c1ccccn1"},
{"CCCCCC[NH2][Pt]([NH3])([NH3])[NH2]CCCCCC", "CCCCCCN"},
{"CC(C)C[C@H]1C(=O)O[Cu]2[N]1=Cc3ccccc3O2",
"CC(C)C[C@H](N=Cc1ccccc1O)C(=O)O"},
{"C(CCC[NH2][Pt]([NH3])([NH3])[NH3])CCN", "NCCCCCCN"},
{"CC[C@@H]1[C@H](C2=CC3=C(C(=C4[N-]3[Mg@+2]56[N]2=C1C=C7[N-]5C8=C([C@H]("
"C(=O)C8=C7C)C(=O)OC)C9=[N]6C(=C4)[C@H]([C@@H]9CCC(=O)OC\\C=C(/"
"C)\\CCC[C@H](C)CCC[C@H](C)CCCC(C)C)C)C)C(=O)C)C",
"CC[C@H]1c2cc3[nH]c4c(c3C)C(=O)[C@H](C(=O)OC)c4c3nc(cc4[nH]c(cc(n2)[C@@"
"H]1C)c(C(C)=O)c4C)[C@@H](C)[C@@H]3CCC(=O)OC/"
"C=C(\\C)CCC[C@H](C)CCC[C@H](C)CCCC(C)C"},
{"C(CC[NH2][Pt]([NH3])([NH3])Cl)C[NH2][Pt]([NH3])([NH3])Cl", "NCCCCN"},
{"CC(CO)(CO)NC(=O)C12[CH]3=[CH]4[Ru]3156([CH]4=[CH]52)(n7c8ccc("
"cc8c9c7c1c(c2c9C(=O)N(C2=O)C)C=C(C=[N]61)F)O)C#O",
"CN1C(=O)c2c(c3c4cc(O)ccc4[nH]c3c3ncc(F)cc23)C1=O"},
{"C[CH]12[CH]3([Ir+2]1456([CH]2(C4(=C53C)C)C)([NH2]CC[NH]6S(=O)(=O)c7ccc("
"cc7)NC(=O)CCCC[C@H]8[C@@H]9[C@H](CS8)NC(=O)N9)Cl)C",
"NCCNS(=O)(=O)c1ccc(NC(=O)CCCC[C@@H]2SC[C@@H]3NC(=O)N[C@H]23)cc1"},
{"C([C@@H]1C(=C([C@H]2[C@@H](O1)NC3=C(N2)C(=O)NC(=N3)N)S)S)O[P@](=O)(O)O["
"Mg]([OH2])([OH2])O[P@@](=O)(O)OC[C@@H]4C(=C([C@H]5[C@@H](O4)NC6=C(N5)C("
"=O)NC(=N6)N)S[W])S",
"Nc1nc2c(c(=O)[nH]1)N[C@H]1C(S)=C(S)[C@@H](COP(=O)(O)O)O[C@H]1N2"},
{"C[C@@H]1C[N]2=CC3=[N]([Ni]24[N]1=CC5=CC=CC=[N]45)C=CC=C3",
"C[C@H](CN=Cc1ccccn1)N=Cc1ccccn1"},
{"C([C@H]1C(=O)O[Re+]([NH2]1)(C#O)(C#O)C#O)O", "N[C@@H](CO)C(=O)O"},
{"CCOC(=O)C12[C@@H]3[Ru]1456([C@@H]3[C@H]4[C@H]52)(n7c8ccc(cc8c9c7c1c("
"c2c9C(=O)NC2=O)C=CC=[N]61)O)[CH]#O",
"O=C1NC(=O)c2c1c1cccnc1c1[nH]c3ccc(O)cc3c21"},
{"CC[O@@H][Ca+2]([OH2])([OH2])([OH2])([OH2])([OH2])[OH2]", "CCO"},
{"CCO[P@@](=O)(CCCc1cc2c3c(c1)C[N]([Pt]3([N](C2)(C)C)Cl)(C)C)Oc4ccc(cc4)["
"N+](=O)[O-]",
"CCO[P@@](=O)(CCCc1cc(CN(C)C)c([Pt+])c(CN(C)C)c1)Oc1ccc([N+](=O)[O-])"
"cc1"},
{"[CH]12=[CH]3[Ru]1456[CH]2=[CH]4[CH]5=[CH]63", "c1ccccc1"},
{"[CH]12=[CH]3[Ru]1456([CH]2=[CH]4[CH]5=[CH]63)(Cl)Cl", "c1ccccc1"},
{"[CH2]1=[CH2][Pt+2]1([Cl-])([Cl-])[Cl-]", "C=C"},
{"C[N@]12CC3=CC=CC=[N]3[Fe+2]145[N]6=CC=CC=C6C[N@@]4(CC(=O)O5)[C@@H]7[C@@"
"H]2CCCC7",
"CN(Cc1ccccn1)[C@H]1CCCC[C@@H]1N(CC(=O)O)Cc1ccccn1"},
{"C[N]12CC[N]34[Fe+2]1([N]5=C(C2)C=CC=C5)([N]6=CC=CC=C6C3)OC(=O)C4",
"CN(CCN(CC(=O)O)Cc1ccccn1)Cc1ccccn1"},
{"C[N@@]12[C@H]3CS[C@@H]1[C@H]4CSC5=[N]4[Fe]2(Oc6c5cccc6)OC3=O",
"CN1[C@H](C(=O)O)CS[C@@H]1[C@H]1CSC(c2ccccc2O)=N1"},
{"CNC1C[S]2CC[S]3[Ru]24(n5c6ccc(cc6c7c5c8c(c9c7C(=O)NC9=O)C=C(C=[N]48)F)"
"OC)([S](C1)CC3)[N]CS",
"COc1ccc2[nH]c3c4ncc(F)cc4c4c(c3c2c1)C(=O)NC4=O"},
{"CNC(=[S][Pt+2]1[NH2]CC[NH2]1)N(C)CCNc2c3ccccc3[nH+]c4c2cccc4",
"CNC(=S)N(C)CCNc1c2ccccc2nc2ccccc12"},
{"COc1cc(cc(c1O)OC)[C@@H]2c3cc4c(cc3[C@@H]([C@@H]5[C@@H]2C(=O)OC5)NC(=O)"
"CC[C@@H]6C[NH2][Pt]([NH2]6)(Cl)Cl)OCO4",
"COc1cc([C@@H]2c3cc4c(cc3[C@H](NC(=O)CC[C@@H](N)CN)[C@H]3COC(=O)[C@@H]"
"32)OCO4)cc(OC)c1O"},
{"COc1cc(cc(c1O)OC)[C@@H]2c3cc4c(cc3[C@@H]([C@@H]5[C@@H]2C(=O)OC5)NC(=O)"
"CC[C@H]6C[NH2][Pt]([NH2]6)(Cl)Cl)OCO4",
"COc1cc([C@@H]2c3cc4c(cc3[C@H](NC(=O)CC[C@H](N)CN)[C@H]3COC(=O)[C@@H]32)"
"OCO4)cc(OC)c1O"},
{"COc1cc(cc(c1O)OC)[C@@H]2c3cc4c(cc3[C@H]([C@@H]5[C@H]2C(=O)OC5)NC(=O)CC["
"C@@H]6C[NH2][Pt]([NH2]6)Cl)OCO4",
"COc1cc([C@@H]2c3cc4c(cc3[C@@H](NC(=O)CC[C@@H](N)CN)[C@H]3COC(=O)[C@H]"
"32)OCO4)cc(OC)c1O"},
{"COc1cc(cc(c1O)OC)[C@@H]2c3cc4c(cc3[C@H]([C@@H]5[C@H]2C(=O)OC5)NC(=O)CC["
"C@H]6C[NH2][Pt]([NH2]6)Cl)OCO4",
"COc1cc([C@@H]2c3cc4c(cc3[C@@H](NC(=O)CC[C@H](N)CN)[C@H]3COC(=O)[C@H]32)"
"OCO4)cc(OC)c1O"},
{"C(=O)[Fe](C=O)(C#N)O(=O)[Ni]", "C=O"},
{"[C](=O)[Re]12(O3[Re]4(O1[Re]5(O2[Re]3(O45)([C]=O)([C]=O)[C]=O)([C]=O)(["
"C]=O)[C]=O)([C]=O)([C]=O)[C]=O)([C]=O)[C]=O",
"[C]=O"},
{"[H]/N=C(\\c1ccc2c(c1)NC3=[N]2[Zn+2][N]4=C(C3)Nc5c4ccc(c5)C(=N)N)/N",
"[H]/N=C(/N)c1ccc2nc(Cc3nc4ccc(C(=N)N)cc4[nH]3)[nH]c2c1"},
{"[NH3][Co+3]([NH3])([NH3])[NH3]", "N"},
{"[NH3][Co+3]([NH3])([NH3])([NH3])([NH3])[NH3]", "N"},
{"[NH3][Ir+3]([NH3])([NH3])([NH3])([NH3])[NH3]", "N"},
{"[NH3][Pt+2]([NH3])[NH3]", "N"},
{"[NH3][Pt]([NH3])(Cl)Cl", "N"},
{"[NH3][Rh+3]([NH3])([NH3])([NH3])([NH3])[NH3]", "N"},
{"[NH3][Ru+3]([NH3])([NH3])([NH3])([NH3])[NH3]", "N"},
{"[OH2][Ca+2]", "O"},
{"[OH2][Ca+2][OH2]", "O"},
{"[OH2][Ca+2]([OH2])[OH2]", "O"},
{"[OH2][Ca+2]([OH2])([OH2])[OH2]", "O"},
{"[OH2][Ca+2]([OH2])([OH2])([OH2])[OH2]", "O"},
{"[OH2][Ca+2]([OH2])([OH2])([OH2])([OH2])[OH2]", "O"},
{"[OH2][Ca+2]([OH2])([OH2])([OH2])([OH2])([OH2])[OH2]", "O"},
{"[OH2][Ca+2]([OH2])([OH2])([OH2])([OH2])([OH2])([OH2])[OH2]", "O"},
{"[OH2][K]([OH2])([OH2])[OH2]", "O"},
{"[OH2][Mg+2]", "O"},
{"[OH2][Mg+2][OH2]", "O"},
{"[OH2][Mg+2]([OH2])[OH2]", "O"},
{"[OH2][Mg+2]([OH2])([OH2])[OH2]", "O"},
{"[OH2][Mg+2]([OH2])([OH2])([OH2])[OH2]", "O"},
{"[OH2][Mg+2]([OH2])([OH2])([OH2])([OH2])[OH2]", "O"},
{"[OH2-][Na+]", "O"},
{"[OH2-][Na+][OH2-]", "O"},
{"[OH2-][Na+]([OH2-])[OH2-]", "O"},
{"[OH2-][Na+]([OH2-])([OH2-])([OH2-])[OH2-]", "O"},
{"[OH2-][Na+]([OH2-])([OH2-])([OH2-])([OH2-])[OH2-]", "O"},
};
std::string normalizationSmarts = R"DATA(// Name SMIRKS
// Opposite of #2.1 in InChI technical manual? Covered by RDKit Sanitization.
Nitro to N+(O-)=O [N,P,As,Sb;X3:1](=[O,S,Se,Te:2])=[O,S,Se,Te:3]>>[*+1:1]([*-1:2])=[*:3]
Sulfone to S(=O)(=O) [S+2:1]([O-:2])([O-:3])>>[S+0:1](=[O-0:2])(=[O-0:3])
Pyridine oxide to n+O- [n:1]=[O:2]>>[n+:1][O-:2]
Azide to N=N+=N- [N:2]=[N:3]#[N:4]>>[N:2]=[N+:3]=[N-:4]
Broken azide to N=N+=N- [N:2]=[N:3]=[N:4]>>[NH0:2]=[NH0+:3]=[NH0-:4]
Diazo/azo to =N+=N- [*:1]=[N:2]#[N:3]>>[*:1]=[N+:2]=[N-:3]
Sulfoxide to -S+(O-)- [!O:1][S+0;X3:2](=[O:3])[!O:4]>>[*:1][S+1:2]([O-:3])[*:4]
// Equivalent to #1.5 in InChI technical manual
Phosphate to P(O-)=O [O,S,Se,Te;-1:1][P+;D4:2][O,S,Se,Te;-1:3]>>[*+0:1]=[P+0;D5:2][*-1:3]
// Equivalent to #1.8 in InChI technical manual
C/S+N to C/S=N+ [C,S;X3+1:1]([NX3:2])[NX3!H0:3]>>[*+0:1]([N:2])=[N+:3]
// Equivalent to #1.8 in InChI technical manual
P+N to P=N+ [P;X4+1:1]([NX3:2])[NX3!H0:3]>>[*+0:1]([N:2])=[N+:3]
Normalize hydrazine-diazonium [CX4:1][NX3H:2]-[NX3H:3][CX4:4][NX2+:5]#[NX1:6]>>[CX4:1][NH0:2]=[NH+:3][C:4][N+0:5]=[NH:6]
// Equivalent to #1.3 in InChI technical manual
Recombine 1,3-separated charges [N,P,As,Sb,O,S,Se,Te;-1:1]-[A+0:2]=[N,P,As,Sb,O,S,Se,Te;+1:3]>>[*-0:1]=[*:2]-[*+0:3]
Recombine 1,3-separated charges [n,o,p,s;-1:1]:[a:2]=[N,O,P,S;+1:3]>>[*-0:1]:[*:2]-[*+0:3]
Recombine 1,3-separated charges [N,O,P,S;-1:1]-[a:2]:[n,o,p,s;+1:3]>>[*-0:1]=[*:2]:[*+0:3]
Recombine 1,5-separated charges [N,P,As,Sb,O,S,Se,Te;-1:1]-[A+0:2]=[A:3]-[A:4]=[N,P,As,Sb,O,S,Se,Te;+1:5]>>[*-0:1]=[*:2]-[*:3]=[*:4]-[*+0:5]
Recombine 1,5-separated charges [n,o,p,s;-1:1]:[a:2]:[a:3]:[c:4]=[N,O,P,S;+1:5]>>[*-0:1]:[*:2]:[*:3]:[c:4]-[*+0:5]
Recombine 1,5-separated charges [N,O,P,S;-1:1]-[c:2]:[a:3]:[a:4]:[n,o,p,s;+1:5]>>[*-0:1]=[c:2]:[*:3]:[*:4]:[*+0:5]
// Conjugated cation rules taken from Francis Atkinson's standardiser. Those that can reduce aromaticity aren't included
Normalize 1,3 conjugated cation [N,O;+0!H0:1]-[A:2]=[N!$(*[O-]),O;+1H0:3]>>[*+1:1]=[*:2]-[*+0:3]
Normalize 1,3 conjugated cation [n;+0!H0:1]:[c:2]=[N!$(*[O-]),O;+1H0:3]>>[*+1:1]:[*:2]-[*+0:3]
//Normalization('Normalize 1,3 conjugated cation', '[N,O;+0!H0:1]-[c:2]:[n!$(*[O-]),o;+1H0:3]>>[*+1:1]=[*:2]:[*+0:3]'),
Normalize 1,5 conjugated cation [N,O;+0!H0:1]-[A:2]=[A:3]-[A:4]=[N!$(*[O-]),O;+1H0:5]>>[*+1:1]=[*:2]-[*:3]=[*:4]-[*+0:5]
Normalize 1,5 conjugated cation [n;+0!H0:1]:[a:2]:[a:3]:[c:4]=[N!$(*[O-]),O;+1H0:5]>>[n+1:1]:[*:2]:[*:3]:[*:4]-[*+0:5]
// Normalization('Normalize 1,5 conjugated cation', '[N,O;+0!H0:1]-[c:2]:[a:3]:[a:4]:[n!$(*[O-]),o;+1H0:5]>>[*+1:1]=[c:2]:[*:3]:[*:4]:[*+0:5]'),
// Normalization('Normalize 1,5 conjugated cation', '[n;+0!H0:1]1:[a:2]:[a:3]:[a:4]:[n!$(*[O-]);+1H0:5]1>>[n+1:1]1:[*:2]:[*:3]:[*:4]:[n+0:5]1'),
// Normalization('Normalize 1,5 conjugated cation', '[n;+0!H0:1]:[a:2]:[a:3]:[a:4]:[n!$(*[O-]);+1H0:5]>>[n+1:1]:[*:2]:[*:3]:[*:4]:[n+0:5]'),
// Equivalent to #1.6 in InChI technical manual. RDKit Sanitization handles this for perchlorate.
Charge normalization [F,Cl,Br,I,At;-1:1]=[O:2]>>[*-0:1][O-:2]
Charge recombination [N,P,As,Sb;-1:1]=[C+;v3:2]>>[*+0:1]#[C+0:2]
Tetravalent [N] to [N+] [N+0;v4:1]>>[N+1:1]
Tetravalent [N-] to [N] [N-1;v4:1]>>[N+0:1]
[OH-] to [O-] [N,P,As,Sb,O,S,Se,Te:1][OH-:2]>>[N,P,As,Sb,O,S,Se,Te:1][OH0;1-:2]
Duplicate C=O [C:1](=[O:2])=O>>[C:1]=[O:2]
CH-C=[O,S] to C=C-[O,S] in aromatic ring [#6;H1:1][#6:2]=[#8,#16;+0:3][*:4]>>[CH0:1]=[C:2][*:3][*:4]
CH2-C=[O,S] to CH=C-[O,S] in aromatic ring [#6;H2:1][#6:2]=[#8,#16;+0:3][*:4]>>[CH1:1]=[C:2][*:3][*:4]
Negatively charged divalent O,S [O,S;v2;-1:1]>>[*;H0;-0:1]
Neutral trivalent O,S [O,S;v3;+0:1]>>[*;+1:1]
Broken 1,3-dioxol [#8,#16;v3,v4:1]=[#6:2][#8,#16:3]>>[*;+0;H0:1][C:2][*;+0;H0:3]
Positively charged tetravalent B [B;v4;+1:1]>>[*;-1:1])DATA";
std::stringstream normalizationSmartsStream(normalizationSmarts);
MolStandardize::CleanupParameters params;
MolStandardize::Normalizer normalizer(normalizationSmartsStream,
params.maxRestarts);
MolStandardize::MetalDisconnector metalDisconnector;
MolStandardize::Reionizer reionizer;
MolStandardize::LargestFragmentChooser largestFragmentChooser;
MolStandardize::Uncharger uncharger;
unsigned int failedOp;
for (const auto &pair : ligandExpoSmiles) {
RWMOL_SPTR rwmol(SmilesToMol(pair.first, 0, false));
MolOps::sanitizeMol(
*rwmol, failedOp,
MolOps::SANITIZE_CLEANUP | MolOps::SANITIZE_FINDRADICALS);
metalDisconnector.disconnect(*rwmol);
ROMOL_SPTR mol(normalizer.normalize(static_cast<const ROMol &>(*rwmol)));
rwmol.reset(new RWMol(*mol));
MolOps::sanitizeMol(*rwmol);
mol.reset(reionizer.reionize(static_cast<const ROMol &>(*rwmol)));
MolOps::assignStereochemistry(*mol);
mol.reset(largestFragmentChooser.choose(*mol));
mol.reset(uncharger.uncharge(*mol));
rwmol.reset(new RWMol(*mol));
MolOps::sanitizeMol(*rwmol);
std::unique_ptr<ROMol> refmol(SmilesToMol(pair.second));
auto refsmi = MolToSmiles(*refmol);
auto prodsmi = MolToSmiles(static_cast<const ROMol &>(*rwmol));
TEST_ASSERT(prodsmi == refsmi);
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
int main() {
testCleanup();
testStandardizeSm();
testMetalDisconnector();
testNormalize();
testNormalizeMultiFrags();
testCharge();
testMetalDisconnectorLigandExpo();
// testEnumerateTautomerSmiles();
return 0;
}
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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/Legacy/Bundle/InsertFieldsIntoBundle.h>
#include <Core/Datatypes/Legacy/Bundle/Bundle.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Modules::Bundles;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
MODULE_INFO_DEF(InsertFieldsIntoBundle, Bundle, SCIRun)
const AlgorithmParameterName InsertFieldsIntoBundle::NumFields("NumFields");
const AlgorithmParameterName InsertFieldsIntoBundle::FieldNames("FieldNames");
const AlgorithmParameterName InsertFieldsIntoBundle::FieldReplace("FieldReplace");
InsertFieldsIntoBundle::InsertFieldsIntoBundle() : Module(staticInfo_)
{
INITIALIZE_PORT(InputBundle);
INITIALIZE_PORT(OutputBundle);
INITIALIZE_PORT(InputFields);
}
void InsertFieldsIntoBundle::setStateDefaults()
{
get_state()->setValue(FieldReplace, VariableList());
}
void InsertFieldsIntoBundle::execute()
{
auto bundleOption = getOptionalInput(InputBundle);
auto fields = getRequiredDynamicInputs(InputFields);
//if (inputs_changed_ || guifield1name_.changed() ||
// guifield2name_.changed() || guifield3name_.changed() ||
// guifield4name_.changed() || guifield5name_.changed() ||
// guifield6name_.changed() ||
// guireplace1_.changed() || guireplace2_.changed() ||
// guireplace3_.changed() || guireplace4_.changed() ||
// guireplace5_.changed() || guireplace6_.changed() ||
// guibundlename_.changed() || !oport_cached("bundle"))
if (needToExecute())
{
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
std::string bundlename = guibundlename_.get();
#endif
BundleHandle bundle;
if (bundleOption && *bundleOption)
{
bundle.reset((*bundleOption)->clone());
}
else
{
bundle.reset(new Bundle());
if (!bundle)
{
THROW_ALGORITHM_PROCESSING_ERROR("Could not allocate new bundle");
}
}
//TODO: instead grab a vector of tuple<string,bool>. need to modify Variable::Value again
//auto fieldNames = get_state()->getValue(FieldNames).toVector();
auto iPorts = inputPorts();
if (fields.size() != iPorts.size() - 2)
warning("Problem in state of dynamic ports");
auto fieldPortNameIterator = iPorts.begin() + 1; // bundle port is first
auto state = get_state();
auto replace = state->getValue(FieldReplace).toVector();
for (int i = 0; i < fields.size(); ++i)
{
auto field = fields[i];
auto stateName = state->getValue(Name((*fieldPortNameIterator++)->id().toString())).toString();
if (field)
{
auto name = !stateName.empty() ? stateName : ("field" + boost::lexical_cast<std::string>(i));
auto replaceField = i < replace.size() ? replace[i].toBool() : true;
if (replaceField || !bundle->isField(name))
{
bundle->set(name, field);
}
}
}
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
if (bundlename != "")
{
handle->set_property("name",bundlename,false);
}
#endif
sendOutput(OutputBundle, bundle);
}
}
#if SCIRUN4_CODE_TO_BE_ENABLED_LATER
private:
GuiString guifield6name_;
GuiInt guireplace6_;
GuiString guibundlename_;
};
InsertFieldsIntoBundle::InsertFieldsIntoBundle(GuiContext* ctx)
: Module("InsertFieldsIntoBundle", ctx, Filter, "Bundle", "SCIRun"),
guifield1name_(get_ctx()->subVar("field1-name"), "field1"),
guifield2name_(get_ctx()->subVar("field2-name"), "field2"),
guifield3name_(get_ctx()->subVar("field3-name"), "field3"),
guifield4name_(get_ctx()->subVar("field4-name"), "field4"),
guifield5name_(get_ctx()->subVar("field5-name"), "field5"),
guifield6name_(get_ctx()->subVar("field6-name"), "field6"),
guireplace1_(get_ctx()->subVar("replace1"),1),
guireplace2_(get_ctx()->subVar("replace2"),1),
guireplace3_(get_ctx()->subVar("replace3"),1),
guireplace4_(get_ctx()->subVar("replace4"),1),
guireplace5_(get_ctx()->subVar("replace5"),1),
guireplace6_(get_ctx()->subVar("replace6"),1),
guibundlename_(get_ctx()->subVar("bundlename",false), "")
{
}
#endif
|
#include "resolver/type_syntax.h"
#include "absl/strings/str_join.h"
#include "common/typecase.h"
#include "core/Names.h"
#include "core/Symbols.h"
#include "core/core.h"
#include "core/errors/resolver.h"
using namespace std;
namespace sorbet::resolver {
// Forward declarations for the local versions of getResultType, getResultTypeAndBind, and parseSig that skolemize type
// members.
namespace {
core::TypePtr getResultTypeWithSelfTypeParams(core::Context ctx, const ast::TreePtr &expr,
const ParsedSig &sigBeingParsed, TypeSyntaxArgs args);
TypeSyntax::ResultType getResultTypeAndBindWithSelfTypeParams(core::Context ctx, const ast::TreePtr &expr,
const ParsedSig &sigBeingParsed, TypeSyntaxArgs args);
ParsedSig parseSigWithSelfTypeParams(core::Context ctx, const ast::Send &sigSend, const ParsedSig *parent,
TypeSyntaxArgs args);
} // namespace
ParsedSig TypeSyntax::parseSig(core::Context ctx, const ast::Send &sigSend, const ParsedSig *parent,
TypeSyntaxArgs args) {
auto result = parseSigWithSelfTypeParams(ctx, sigSend, parent, args);
for (auto &arg : result.argTypes) {
arg.type = core::Types::unwrapSelfTypeParam(ctx, arg.type);
}
if (result.returns != nullptr) {
result.returns = core::Types::unwrapSelfTypeParam(ctx, result.returns);
}
return result;
}
core::TypePtr TypeSyntax::getResultType(core::Context ctx, ast::TreePtr &expr, const ParsedSig &sigBeingParsed,
TypeSyntaxArgs args) {
return core::Types::unwrapSelfTypeParam(
ctx, getResultTypeWithSelfTypeParams(ctx, expr, sigBeingParsed, args.withoutRebind()));
}
TypeSyntax::ResultType TypeSyntax::getResultTypeAndBind(core::Context ctx, ast::TreePtr &expr,
const ParsedSig &sigBeingParsed, TypeSyntaxArgs args) {
auto result = getResultTypeAndBindWithSelfTypeParams(ctx, expr, sigBeingParsed, args);
result.type = core::Types::unwrapSelfTypeParam(ctx, result.type);
return result;
}
core::TypePtr getResultLiteral(core::Context ctx, const ast::TreePtr &expr) {
core::TypePtr result;
typecase(
expr, [&](const ast::Literal &lit) { result = lit.value; },
[&](const ast::TreePtr &e) {
if (auto e = ctx.beginError(expr.loc(), core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Unsupported type literal");
}
result = core::Types::untypedUntracked();
});
ENFORCE(result != nullptr);
result.sanityCheck(ctx);
return result;
}
bool isTProc(core::Context ctx, const ast::Send *send) {
while (send != nullptr) {
if (send->fun == core::Names::proc()) {
if (auto *rcv = ast::cast_tree<ast::ConstantLit>(send->recv)) {
return rcv->symbol == core::Symbols::T();
}
}
send = ast::cast_tree<ast::Send>(send->recv);
}
return false;
}
bool TypeSyntax::isSig(core::Context ctx, const ast::Send &send) {
if (send.fun != core::Names::sig()) {
return false;
}
if (send.block.get() == nullptr) {
return false;
}
auto nargs = send.args.size();
if (!(nargs == 1 || nargs == 2)) {
return false;
}
auto recv = ast::cast_tree<ast::ConstantLit>(send.recv);
if (recv && recv->symbol == core::Symbols::Sorbet_Private_Static()) {
return true;
}
return false;
}
namespace {
ParsedSig parseSigWithSelfTypeParams(core::Context ctx, const ast::Send &sigSend, const ParsedSig *parent,
TypeSyntaxArgs args) {
ParsedSig sig;
vector<const ast::Send *> sends;
if (isTProc(ctx, &sigSend)) {
sends.emplace_back(&sigSend);
} else {
sig.seen.sig = true;
ENFORCE(sigSend.fun == core::Names::sig());
auto block = ast::cast_tree<ast::Block>(sigSend.block);
ENFORCE(block);
auto send = ast::cast_tree<ast::Send>(block->body);
if (send) {
sends.emplace_back(send);
} else {
auto insseq = ast::cast_tree<ast::InsSeq>(block->body);
if (insseq) {
for (auto &stat : insseq->stats) {
send = ast::cast_tree<ast::Send>(stat);
if (!send) {
return sig;
}
sends.emplace_back(send);
}
send = ast::cast_tree<ast::Send>(insseq->expr);
if (!send) {
return sig;
}
sends.emplace_back(send);
} else {
return sig;
}
}
}
ENFORCE(!sends.empty());
if (sigSend.args.size() == 2) {
auto lit = ast::cast_tree<ast::Literal>(sigSend.args[1]);
if (lit != nullptr && lit->isSymbol(ctx) && lit->asSymbol(ctx) == core::Names::final_()) {
sig.seen.final = true;
}
}
for (auto &send : sends) {
const ast::Send *tsend = send;
// extract type parameters early
while (tsend != nullptr) {
if (tsend->fun == core::Names::typeParameters()) {
if (parent != nullptr) {
if (auto e = ctx.beginError(tsend->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Malformed signature; Type parameters can only be specified in outer sig");
}
break;
}
for (auto &arg : tsend->args) {
if (auto c = ast::cast_tree<ast::Literal>(arg)) {
if (c->isSymbol(ctx)) {
auto name = c->asSymbol(ctx);
auto &typeArgSpec = sig.enterTypeArgByName(name);
if (typeArgSpec.type) {
if (auto e =
ctx.beginError(arg.loc(), core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Malformed signature; Type argument `{}` was specified twice",
name.show(ctx));
}
}
typeArgSpec.type = core::make_type<core::TypeVar>(core::Symbols::todo());
typeArgSpec.loc = core::Loc(ctx.file, arg.loc());
} else {
if (auto e = ctx.beginError(arg.loc(), core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Malformed signature; Type parameters are specified with symbols");
}
}
} else {
if (auto e = ctx.beginError(arg.loc(), core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Malformed signature; Type parameters are specified with symbols");
}
}
}
}
tsend = ast::cast_tree<ast::Send>(tsend->recv);
}
}
if (parent == nullptr) {
parent = &sig;
}
for (auto &send : sends) {
while (send != nullptr) {
// so we don't report multiple "method does not exist" errors arising from the same expression
bool reportedInvalidMethod = false;
switch (send->fun._id) {
case core::Names::proc()._id:
sig.seen.proc = true;
break;
case core::Names::bind()._id: {
if (sig.seen.bind) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Malformed `{}`: Multiple calls to `.bind`", send->fun.show(ctx));
}
sig.bind = core::SymbolRef();
}
sig.seen.bind = true;
if (send->args.size() != 1) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Wrong number of args to `{}`. Expected: `{}`, got: `{}`", "bind", 1,
send->args.size());
}
break;
}
bool validBind = false;
auto bind = getResultTypeWithSelfTypeParams(ctx, send->args.front(), *parent, args);
if (core::isa_type<core::ClassType>(bind)) {
auto classType = core::cast_type_nonnull<core::ClassType>(bind);
sig.bind = classType.symbol;
validBind = true;
} else if (auto appType = core::cast_type<core::AppliedType>(bind)) {
// When `T.proc.bind` is used with `T.class_of`, pass it
// through as long as it only has the AttachedClass type
// member.
if (appType->klass.data(ctx)->isSingletonClass(ctx) &&
appType->klass.data(ctx)->typeMembers().size() == 1) {
sig.bind = appType->klass;
validBind = true;
}
}
if (!validBind) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Malformed `{}`: Can only bind to simple class names", send->fun.show(ctx));
}
}
break;
}
case core::Names::params()._id: {
if (sig.seen.params) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Malformed `{}`: Multiple calls to `.params`", send->fun.show(ctx));
}
sig.argTypes.clear();
}
sig.seen.params = true;
if (send->args.empty()) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
auto paramsStr = send->fun.show(ctx);
e.setHeader("`{}` must be given arguments", paramsStr);
core::Loc loc{ctx.file, send->loc};
auto orig = loc.source(ctx);
auto dot = orig.rfind(".");
if (orig.rfind(".") == string::npos) {
e.replaceWith("Remove this use of `params`", loc, "");
} else {
e.replaceWith("Remove this use of `params`", loc, "{}", orig.substr(0, dot));
}
}
break;
}
// `params` only accepts keyword args
if (send->numPosArgs != 0) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
auto paramsStr = send->fun.show(ctx);
e.setHeader("`{}` expects keyword arguments", paramsStr);
e.addErrorNote("All parameters must be given names in `{}` even if they are positional",
paramsStr);
// when the first argument is a hash, emit an autocorrect to remove the braces
if (send->numPosArgs == 1) {
if (auto *hash = ast::cast_tree<ast::Hash>(send->args.front())) {
auto loc = core::Loc(ctx.file, hash->loc.beginPos(), hash->loc.endPos());
auto source = loc.source(ctx);
e.replaceWith("Remove braces from keyword args", loc, "{}",
source.substr(1, source.size() - 2));
}
}
}
break;
}
if (send->hasKwSplat()) {
// TODO(trevor) add an error for this
}
auto [start, end] = send->kwArgsRange();
for (auto i = start; i < end; i += 2) {
auto &key = send->args[i];
auto &value = send->args[i + 1];
auto *lit = ast::cast_tree<ast::Literal>(key);
if (lit && lit->isSymbol(ctx)) {
core::NameRef name = lit->asSymbol(ctx);
auto resultAndBind =
getResultTypeAndBindWithSelfTypeParams(ctx, value, *parent, args.withRebind());
sig.argTypes.emplace_back(ParsedSig::ArgSpec{core::Loc(ctx.file, key.loc()), name,
resultAndBind.type, resultAndBind.rebind});
}
}
break;
}
case core::Names::typeParameters()._id:
// was handled above
break;
case core::Names::abstract()._id:
if (sig.seen.final) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Method that is both `{}` and `{}` cannot be implemented", "final", "abstract");
}
}
sig.seen.abstract = true;
break;
case core::Names::override_()._id: {
sig.seen.override_ = true;
if (send->numPosArgs > 0) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("`{}` expects keyword arguments", send->fun.show(ctx));
}
break;
}
if (!send->args.empty()) {
auto [posEnd, kwEnd] = send->kwArgsRange();
for (auto i = posEnd; i < kwEnd; i += 2) {
auto &key = send->args[i];
auto &value = send->args[i + 1];
auto lit = ast::cast_tree<ast::Literal>(key);
if (lit && lit->isSymbol(ctx)) {
if (lit->asSymbol(ctx) == core::Names::allowIncompatible()) {
auto val = ast::cast_tree<ast::Literal>(value);
if (val && val->isTrue(ctx)) {
sig.seen.incompatibleOverride = true;
}
}
}
}
}
break;
}
case core::Names::implementation()._id:
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::ImplementationDeprecated)) {
e.setHeader("Use of `{}` has been replaced by `{}`", "implementation", "override");
if (send->recv.isSelfReference()) {
e.replaceWith("Replace with `override`", core::Loc(ctx.file, send->loc), "override");
} else {
e.replaceWith("Replace with `override`", core::Loc(ctx.file, send->loc), "{}.override",
core::Loc(ctx.file, send->recv.loc()).source(ctx));
}
}
break;
case core::Names::overridable()._id:
if (sig.seen.final) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Method that is both `{}` and `{}` cannot be implemented", "final",
"overridable");
}
}
sig.seen.overridable = true;
break;
case core::Names::returns()._id: {
sig.seen.returns = true;
if (send->numPosArgs != send->args.size()) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("`{}` does not accept keyword arguments", send->fun.show(ctx));
if (!send->hasKwSplat()) {
auto start = send->args[send->numPosArgs].loc();
auto end = send->args.back().loc();
core::Loc argsLoc(ctx.file, start.beginPos(), end.endPos());
e.replaceWith("Wrap in braces to make a shape type", argsLoc, "{{{}}}",
argsLoc.source(ctx));
}
}
break;
}
if (send->numPosArgs != 1) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Wrong number of args to `{}`. Expected: `{}`, got: `{}`", "returns", 1,
send->numPosArgs);
}
break;
}
sig.returns = getResultTypeWithSelfTypeParams(ctx, send->args.front(), *parent, args);
break;
}
case core::Names::void_()._id:
sig.seen.void_ = true;
sig.returns = core::Types::void_();
break;
case core::Names::checked()._id:
sig.seen.checked = true;
break;
case core::Names::onFailure()._id:
break;
case core::Names::final_()._id:
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
reportedInvalidMethod = true;
e.setHeader("The syntax for declaring a method final is `sig(:final) {{...}}`, not `sig "
"{{final. ...}}`");
}
break;
default:
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
reportedInvalidMethod = true;
e.setHeader("Malformed signature: `{}` is invalid in this context", send->fun.show(ctx));
e.addErrorLine(core::Loc(ctx.file, send->loc),
"Consult https://sorbet.org/docs/sigs for signature syntax");
}
}
auto recv = ast::cast_tree<ast::Send>(send->recv);
// we only report this error if we haven't reported another unknown method error
if (!recv && !reportedInvalidMethod) {
if (!send->recv.isSelfReference()) {
if (!sig.seen.proc) {
if (auto e = ctx.beginError(send->loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Malformed signature: `{}` being invoked on an invalid receiver",
send->fun.show(ctx));
}
}
}
break;
}
send = recv;
}
}
ENFORCE(sig.seen.sig || sig.seen.proc);
return sig;
}
core::TypePtr interpretTCombinator(core::Context ctx, const ast::Send &send, const ParsedSig &sig,
TypeSyntaxArgs args) {
switch (send.fun._id) {
case core::Names::nilable()._id:
if (send.numPosArgs != 1 || send.hasKwArgs()) {
return core::Types::untypedUntracked(); // error will be reported in infer.
}
return core::Types::any(ctx, getResultTypeWithSelfTypeParams(ctx, send.args[0], sig, args),
core::Types::nilClass());
case core::Names::all()._id: {
if (send.args.empty()) {
// Error will be reported in infer
return core::Types::untypedUntracked();
}
auto result = getResultTypeWithSelfTypeParams(ctx, send.args[0], sig, args);
int i = 1;
while (i < send.args.size()) {
result = core::Types::all(ctx, result, getResultTypeWithSelfTypeParams(ctx, send.args[i], sig, args));
i++;
}
return result;
}
case core::Names::any()._id: {
if (send.args.empty()) {
// Error will be reported in infer
return core::Types::untypedUntracked();
}
auto result = getResultTypeWithSelfTypeParams(ctx, send.args[0], sig, args);
int i = 1;
while (i < send.args.size()) {
result = core::Types::any(ctx, result, getResultTypeWithSelfTypeParams(ctx, send.args[i], sig, args));
i++;
}
return result;
}
case core::Names::typeParameter()._id: {
if (send.args.size() != 1) {
// Error will be reported in infer
return core::Types::untypedUntracked();
}
auto arr = ast::cast_tree<ast::Literal>(send.args[0]);
if (!arr || !arr->isSymbol(ctx)) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("type_parameter requires a symbol");
}
return core::Types::untypedUntracked();
}
auto fnd = sig.findTypeArgByName(arr->asSymbol(ctx));
if (!fnd.type) {
if (auto e = ctx.beginError(arr->loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Unspecified type parameter");
}
return core::Types::untypedUntracked();
}
return fnd.type;
}
case core::Names::enum_()._id: {
if (send.args.size() != 1) {
// Error will be reported in infer
return core::Types::untypedUntracked();
}
auto arr = ast::cast_tree<ast::Array>(send.args[0]);
if (arr == nullptr) {
// TODO(pay-server) unsilence this error and support enums from pay-server
{ return core::Types::Object(); }
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("enum must be passed a literal array. e.g. enum([1,\"foo\",MyClass])");
}
return core::Types::untypedUntracked();
}
if (arr->elems.empty()) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("enum([]) is invalid");
}
return core::Types::untypedUntracked();
}
auto result = getResultLiteral(ctx, arr->elems[0]);
int i = 1;
while (i < arr->elems.size()) {
result = core::Types::any(ctx, result, getResultLiteral(ctx, arr->elems[i]));
i++;
}
return result;
}
case core::Names::classOf()._id: {
if (send.args.size() != 1) {
// Error will be reported in infer
return core::Types::untypedUntracked();
}
auto *obj = ast::cast_tree<ast::ConstantLit>(send.args[0]);
if (!obj) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("T.class_of needs a Class as its argument");
}
return core::Types::untypedUntracked();
}
auto maybeAliased = obj->symbol;
if (maybeAliased.data(ctx)->isTypeAlias()) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("T.class_of can't be used with a T.type_alias");
}
return core::Types::untypedUntracked();
}
if (maybeAliased.data(ctx)->isTypeMember()) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("T.class_of can't be used with a T.type_member");
}
return core::Types::untypedUntracked();
}
auto sym = maybeAliased.data(ctx)->dealias(ctx);
if (sym.data(ctx)->isStaticField()) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("T.class_of can't be used with a constant field");
}
return core::Types::untypedUntracked();
}
auto singleton = sym.data(ctx)->lookupSingletonClass(ctx);
if (!singleton.exists()) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Unknown class");
}
return core::Types::untypedUntracked();
}
return singleton.data(ctx)->externalType();
}
case core::Names::untyped()._id:
return core::Types::untyped(ctx, args.untypedBlame);
case core::Names::selfType()._id:
if (args.allowSelfType) {
return core::make_type<core::SelfType>();
}
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Only top-level T.self_type is supported");
}
return core::Types::untypedUntracked();
case core::Names::experimentalAttachedClass()._id:
case core::Names::attachedClass()._id:
if (send.fun == core::Names::experimentalAttachedClass()) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::ExperimentalAttachedClass)) {
e.setHeader("`{}` has been stabilized and is no longer experimental",
"T.experimental_attached_class");
e.replaceWith("Replace with `T.attached_class`", core::Loc(ctx.file, send.loc), "T.attached_class");
}
}
if (!ctx.owner.data(ctx)->isSingletonClass(ctx)) {
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("`{}` may only be used in a singleton class method context",
"T." + core::Names::attachedClass().show(ctx));
}
return core::Types::untypedUntracked();
} else {
// All singletons have an AttachedClass type member, created by
// `singletonClass`
auto attachedClass = ctx.owner.data(ctx)->findMember(ctx, core::Names::Constants::AttachedClass());
return attachedClass.data(ctx)->resultType;
}
case core::Names::noreturn()._id:
return core::Types::bottom();
default:
if (auto e = ctx.beginError(send.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Unsupported method `{}`", "T." + send.fun.show(ctx));
}
return core::Types::untypedUntracked();
}
}
core::TypePtr getResultTypeWithSelfTypeParams(core::Context ctx, const ast::TreePtr &expr,
const ParsedSig &sigBeingParsed, TypeSyntaxArgs args) {
return getResultTypeAndBindWithSelfTypeParams(ctx, expr, sigBeingParsed, args.withoutRebind()).type;
}
TypeSyntax::ResultType getResultTypeAndBindWithSelfTypeParams(core::Context ctx, const ast::TreePtr &expr,
const ParsedSig &sigBeingParsed, TypeSyntaxArgs args) {
// Ensure that we only check types from a class context
auto ctxOwnerData = ctx.owner.data(ctx);
ENFORCE(ctxOwnerData->isClassOrModule(), "getResultTypeAndBind wasn't called with a class owner");
TypeSyntax::ResultType result;
typecase(
expr,
[&](const ast::Array &arr) {
vector<core::TypePtr> elems;
for (auto &el : arr.elems) {
elems.emplace_back(getResultTypeWithSelfTypeParams(ctx, el, sigBeingParsed, args.withoutSelfType()));
}
result.type = core::TupleType::build(ctx, move(elems));
},
[&](const ast::Hash &hash) {
vector<core::TypePtr> keys;
vector<core::TypePtr> values;
for (auto &ktree : hash.keys) {
auto &vtree = hash.values[&ktree - &hash.keys.front()];
auto val = getResultTypeWithSelfTypeParams(ctx, vtree, sigBeingParsed, args.withoutSelfType());
auto lit = ast::cast_tree<ast::Literal>(ktree);
if (lit && (lit->isSymbol(ctx) || lit->isString(ctx))) {
ENFORCE(core::isa_type<core::LiteralType>(lit->value));
keys.emplace_back(lit->value);
values.emplace_back(val);
} else {
if (auto e = ctx.beginError(ktree.loc(), core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Malformed type declaration. Shape keys must be literals");
}
}
}
result.type = core::make_type<core::ShapeType>(core::Types::hashOfUntyped(), move(keys), move(values));
},
[&](const ast::ConstantLit &i) {
auto maybeAliased = i.symbol;
ENFORCE(maybeAliased.exists());
if (maybeAliased.data(ctx)->isTypeAlias()) {
result.type = maybeAliased.data(ctx)->resultType;
return;
}
// Only T::Enum singletons are allowed to be in type syntax because there is only one
// non-alias constant for an instance of a particular T::Enum--it was created with
// `new` and immediately assigned into a constant. Any further ConstantLits of this enum's
// type must be either class aliases (banned in type syntax) or type aliases.
//
// This is not the case for arbitrary singletons: MySingleton.instance can be called as many
// times as wanted, and assigned into different constants each time. As much as possible, we
// want there to be one name for every type; making an alias for a type should always be
// syntactically declared with T.type_alias.
if (core::isa_type<core::ClassType>(maybeAliased.data(ctx)->resultType)) {
auto resultType = core::cast_type_nonnull<core::ClassType>(maybeAliased.data(ctx)->resultType);
if (resultType.symbol.data(ctx)->derivesFrom(ctx, core::Symbols::T_Enum())) {
result.type = maybeAliased.data(ctx)->resultType;
return;
}
}
auto sym = maybeAliased.data(ctx)->dealias(ctx);
if (sym.data(ctx)->isClassOrModule()) {
// the T::Type generics internally have a typeArity of 0, so this allows us to check against them in the
// same way that we check against types like `Array`
bool isBuiltinGeneric = sym == core::Symbols::T_Hash() || sym == core::Symbols::T_Array() ||
sym == core::Symbols::T_Set() || sym == core::Symbols::T_Range() ||
sym == core::Symbols::T_Enumerable() || sym == core::Symbols::T_Enumerator();
if (isBuiltinGeneric || sym.data(ctx)->typeArity(ctx) > 0) {
// This set **should not** grow over time.
bool isStdlibWhitelisted = sym == core::Symbols::Hash() || sym == core::Symbols::Array() ||
sym == core::Symbols::Set() || sym == core::Symbols::Range() ||
sym == core::Symbols::Enumerable() || sym == core::Symbols::Enumerator();
auto level = isStdlibWhitelisted ? core::errors::Resolver::GenericClassWithoutTypeArgsStdlib
: core::errors::Resolver::GenericClassWithoutTypeArgs;
if (auto e = ctx.beginError(i.loc, level)) {
e.setHeader("Malformed type declaration. Generic class without type arguments `{}`",
sym.show(ctx));
// if we're looking at `Array`, we want the autocorrect to include `T::`, but we don't need to
// if we're already looking at `T::Array` instead.
auto typePrefix = isBuiltinGeneric ? "" : "T::";
if (sym == core::Symbols::Hash() || sym == core::Symbols::T_Hash()) {
// Hash is special because it has arity 3 but you're only supposed to write the first 2
e.replaceWith("Add type arguments", core::Loc(ctx.file, i.loc),
"{}{}[T.untyped, T.untyped]", typePrefix,
core::Loc(ctx.file, i.loc).source(ctx));
} else if (isStdlibWhitelisted || isBuiltinGeneric) {
// the default provided here for builtin generic types is 1, and that might need to change
// if we add other builtin generics (but ideally we should never need to do so!)
auto numTypeArgs = isBuiltinGeneric ? 1 : sym.data(ctx)->typeArity(ctx);
vector<string> untypeds;
for (int i = 0; i < numTypeArgs; i++) {
untypeds.emplace_back("T.untyped");
}
e.replaceWith("Add type arguments", core::Loc(ctx.file, i.loc), "{}{}[{}]", typePrefix,
core::Loc(ctx.file, i.loc).source(ctx), absl::StrJoin(untypeds, ", "));
}
}
}
if (sym == core::Symbols::StubModule()) {
// Though for normal types _and_ stub types `infer` should use `externalType`,
// using `externalType` for stub types here will lead to incorrect handling of global state hashing,
// where we won't see difference between two different unresolved stubs(or a mistyped stub). thus,
// while normally we would treat stubs as untyped, in `sig`s we treat them as proper types, so that
// we can correctly hash them.
auto unresolvedPath = i.fullUnresolvedPath(ctx);
ENFORCE(unresolvedPath.has_value());
result.type =
core::make_type<core::UnresolvedClassType>(unresolvedPath->first, move(unresolvedPath->second));
} else {
result.type = sym.data(ctx)->externalType();
}
} else if (sym.data(ctx)->isTypeMember()) {
auto symData = sym.data(ctx);
auto symOwner = symData->owner.data(ctx);
bool isTypeTemplate = symOwner->isSingletonClass(ctx);
if (args.allowTypeMember) {
bool ctxIsSingleton = ctxOwnerData->isSingletonClass(ctx);
// Check if we're processing a type within the class that
// defines this type member by comparing the singleton class of
// the context, and the singleton class of the type member's
// owner.
core::SymbolRef symOwnerSingleton =
isTypeTemplate ? symData->owner : symOwner->lookupSingletonClass(ctx);
core::SymbolRef ctxSingleton = ctxIsSingleton ? ctx.owner : ctxOwnerData->lookupSingletonClass(ctx);
bool usedOnSourceClass = symOwnerSingleton == ctxSingleton;
// For this to be a valid use of a member or template type, this
// must:
//
// 1. be used in the context of the class that defines it
// 2. if it's a type_template type, be used in a singleton
// method
// 3. if it's a type_member type, be used in an instance method
if (usedOnSourceClass &&
((isTypeTemplate && ctxIsSingleton) || !(isTypeTemplate || ctxIsSingleton))) {
// At this point, we maake a skolemized variable that will be unwrapped at the end of type
// parsing using Types::unwrapSkolemVariables. The justification for this is that type
// constructors like `Types::any` do not expect to see bound variables, and will panic.
result.type = core::make_type<core::SelfTypeParam>(sym);
} else {
if (auto e = ctx.beginError(i.loc, core::errors::Resolver::InvalidTypeDeclarationTyped)) {
string typeSource = isTypeTemplate ? "type_template" : "type_member";
string typeStr = sym.show(ctx);
if (usedOnSourceClass) {
if (ctxIsSingleton) {
e.setHeader("`{}` type `{}` used in a singleton method definition", typeSource,
typeStr);
} else {
e.setHeader("`{}` type `{}` used in an instance method definition", typeSource,
typeStr);
}
} else {
e.setHeader("`{}` type `{}` used outside of the class definition", typeSource, typeStr);
}
}
result.type = core::Types::untypedUntracked();
}
} else {
// a type member has occurred in a context that doesn't allow them
if (auto e = ctx.beginError(i.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
auto flavor = isTypeTemplate ? "type_template"sv : "type_member"sv;
e.setHeader("`{}` `{}` is not allowed in this context", flavor, sym.show(ctx));
}
result.type = core::Types::untypedUntracked();
}
} else if (sym.data(ctx)->isStaticField()) {
if (auto e = ctx.beginError(i.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Constant `{}` is not a class or type alias", maybeAliased.show(ctx));
e.addErrorLine(sym.data(ctx)->loc(),
"If you are trying to define a type alias, you should use `{}` here",
"T.type_alias");
}
result.type = core::Types::untypedUntracked();
} else {
if (auto e = ctx.beginError(i.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Malformed type declaration. Not a class type `{}`", maybeAliased.show(ctx));
}
result.type = core::Types::untypedUntracked();
}
},
[&](const ast::Send &s) {
if (isTProc(ctx, &s)) {
auto sig = parseSigWithSelfTypeParams(ctx, s, &sigBeingParsed, args.withoutSelfType());
if (sig.bind.exists()) {
if (!args.allowRebind) {
if (auto e = ctx.beginError(s.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Using `{}` is not permitted here", "bind");
}
} else {
result.rebind = sig.bind;
}
}
vector<core::TypePtr> targs;
if (sig.returns == nullptr) {
if (auto e = ctx.beginError(s.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Malformed T.proc: You must specify a return type");
}
targs.emplace_back(core::Types::untypedUntracked());
} else {
targs.emplace_back(sig.returns);
}
for (auto &arg : sig.argTypes) {
targs.emplace_back(arg.type);
}
auto arity = targs.size() - 1;
if (arity > core::Symbols::MAX_PROC_ARITY) {
if (auto e = ctx.beginError(s.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Malformed T.proc: Too many arguments (max `{}`)", core::Symbols::MAX_PROC_ARITY);
}
result.type = core::Types::untypedUntracked();
return;
}
auto sym = core::Symbols::Proc(arity);
result.type = core::make_type<core::AppliedType>(sym, move(targs));
return;
}
auto *recvi = ast::cast_tree<ast::ConstantLit>(s.recv);
if (recvi == nullptr) {
if (auto e = ctx.beginError(s.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Malformed type declaration. Unknown type syntax. Expected a ClassName or T.<func>");
}
result.type = core::Types::untypedUntracked();
return;
}
if (recvi->symbol == core::Symbols::T()) {
result.type = interpretTCombinator(ctx, s, sigBeingParsed, args);
return;
}
if (recvi->symbol == core::Symbols::Magic() && s.fun == core::Names::callWithSplat()) {
// TODO(pay-server) remove this block
if (auto e = ctx.beginError(recvi->loc, core::errors::Resolver::InvalidTypeDeclarationTyped)) {
e.setHeader("Malformed type declaration: splats cannot be used in types");
}
result.type = core::Types::untypedUntracked();
return;
}
if (s.fun != core::Names::squareBrackets()) {
if (auto e = ctx.beginError(s.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Malformed type declaration. Unknown type syntax. Expected a ClassName or T.<func>");
}
result.type = core::Types::untypedUntracked();
return;
}
InlinedVector<unique_ptr<core::TypeAndOrigins>, 2> holders;
InlinedVector<const core::TypeAndOrigins *, 2> targs;
InlinedVector<core::LocOffsets, 2> argLocs;
targs.reserve(s.args.size());
argLocs.reserve(s.args.size());
holders.reserve(s.args.size());
auto i = -1;
for (auto &arg : s.args) {
i++;
core::TypeAndOrigins ty;
ty.origins.emplace_back(core::Loc(ctx.file, arg.loc()));
if (i < s.numPosArgs) {
ty.type = core::make_type<core::MetaType>(
getResultTypeWithSelfTypeParams(ctx, arg, sigBeingParsed, args.withoutSelfType()));
} else {
// Fill this in with a dummy type. We don't want to parse this as type syntax
// because we already know it's garbage.
// But we still want to record some sort of arg (for the loc specifically) so
// that the calls.cc intrinsic can craft an autocorrect.
ty.type = core::Types::untypedUntracked();
}
holders.emplace_back(make_unique<core::TypeAndOrigins>(move(ty)));
targs.emplace_back(holders.back().get());
argLocs.emplace_back(arg.loc());
}
core::SymbolRef corrected;
if (recvi->symbol == core::Symbols::Array()) {
corrected = core::Symbols::T_Array();
} else if (recvi->symbol == core::Symbols::Hash()) {
corrected = core::Symbols::T_Hash();
} else if (recvi->symbol == core::Symbols::Enumerable()) {
corrected = core::Symbols::T_Enumerable();
} else if (recvi->symbol == core::Symbols::Enumerator()) {
corrected = core::Symbols::T_Enumerator();
} else if (recvi->symbol == core::Symbols::Range()) {
corrected = core::Symbols::T_Range();
} else if (recvi->symbol == core::Symbols::Set()) {
corrected = core::Symbols::T_Set();
}
if (corrected.exists()) {
if (auto e = ctx.beginError(s.loc, core::errors::Resolver::BadStdlibGeneric)) {
e.setHeader("Use `{}`, not `{}` to declare a typed `{}`", corrected.data(ctx)->show(ctx) + "[...]",
recvi->symbol.data(ctx)->show(ctx) + "[...]", recvi->symbol.data(ctx)->show(ctx));
e.addErrorNote(
"`{}` will raise at runtime because this generic was defined in the standard library",
recvi->symbol.data(ctx)->show(ctx) + "[...]");
e.replaceWith(fmt::format("Change `{}` to `{}`", recvi->symbol.data(ctx)->show(ctx),
corrected.data(ctx)->show(ctx)),
core::Loc(ctx.file, recvi->loc), "{}", corrected.data(ctx)->show(ctx));
}
result.type = core::Types::untypedUntracked();
return;
} else {
corrected = recvi->symbol;
}
corrected = corrected.data(ctx)->dealias(ctx);
if (!corrected.data(ctx)->isClassOrModule()) {
if (auto e = ctx.beginError(s.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Expected a class or module");
}
result.type = core::Types::untypedUntracked();
return;
}
auto correctedSingleton = corrected.data(ctx)->lookupSingletonClass(ctx);
ENFORCE_NO_TIMER(correctedSingleton.exists());
auto ctype = core::make_type<core::ClassType>(correctedSingleton);
// In `dispatchArgs` this is ordinarily used to specify the origin tag for
// uninitialized variables. Inside of a signature we shouldn't need this:
auto originForUninitialized = core::Loc::none();
core::CallLocs locs{
ctx.file,
s.loc,
recvi->loc,
argLocs,
};
core::DispatchArgs dispatchArgs{
core::Names::squareBrackets(), locs, s.numPosArgs, targs, ctype, ctype, ctype, nullptr,
originForUninitialized};
auto out = core::Types::dispatchCallWithoutBlock(ctx, ctype, dispatchArgs);
if (out.isUntyped()) {
// Using a generic untyped type here will lead to incorrect handling of global state hashing,
// where we won't see difference between types with generic arguments.
// Thus, while normally we would treat these as untyped, in `sig`s we treat them as proper types, so
// that we can correctly hash them.
vector<core::TypePtr> targPtrs;
targPtrs.reserve(targs.size());
for (auto &targ : targs) {
targPtrs.push_back(targ->type);
}
result.type = core::make_type<core::UnresolvedAppliedType>(correctedSingleton, move(targPtrs));
return;
}
if (auto *mt = core::cast_type<core::MetaType>(out)) {
result.type = mt->wrapped;
return;
}
if (auto e = ctx.beginError(s.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Malformed type declaration. Unknown type syntax. Expected a ClassName or T.<func>");
}
result.type = core::Types::untypedUntracked();
},
[&](const ast::Local &slf) {
if (expr.isSelfReference()) {
result.type = ctxOwnerData->selfType(ctx);
} else {
if (auto e = ctx.beginError(slf.loc, core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Unsupported type syntax");
}
result.type = core::Types::untypedUntracked();
}
},
[&](const ast::Literal &lit) {
auto underlying = core::isa_type<core::LiteralType>(lit.value) ? lit.value.underlying() : lit.value;
if (auto e = ctx.beginError(lit.loc, core::errors::Resolver::InvalidMethodSignature)) {
e.setHeader("Unsupported literal in type syntax", lit.value.show(ctx));
e.replaceWith("Replace with underlying type", core::Loc(ctx.file, lit.loc), "{}", underlying.show(ctx));
}
result.type = underlying;
},
[&](const ast::TreePtr &e) {
if (auto e = ctx.beginError(expr.loc(), core::errors::Resolver::InvalidTypeDeclaration)) {
e.setHeader("Unsupported type syntax");
}
result.type = core::Types::untypedUntracked();
});
ENFORCE(result.type != nullptr);
result.type.sanityCheck(ctx);
return result;
}
} // namespace
ParsedSig::TypeArgSpec &ParsedSig::enterTypeArgByName(core::NameRef name) {
for (auto ¤t : typeArgs) {
if (current.name == name) {
return current;
}
}
auto &inserted = typeArgs.emplace_back();
inserted.name = name;
return inserted;
}
const ParsedSig::TypeArgSpec emptyTypeArgSpec;
const ParsedSig::TypeArgSpec &ParsedSig::findTypeArgByName(core::NameRef name) const {
for (auto ¤t : typeArgs) {
if (current.name == name) {
return current;
}
}
return emptyTypeArgSpec;
}
} // namespace sorbet::resolver
|
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <GL/glew.h>
#include "shader.hpp"
#include "../guiconsole/console.hpp"
using namespace std;
namespace Syn {
GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path,
ConsoleManager *out){
bool error_happened = false;
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
const unsigned char* version = (const unsigned char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
std::stringstream ss;
ss << "running GLSL Version " << version;
out->printToConsole(ss.str());
ss.clear();
ss.str(std::string());
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_file_path, std::ios::in);
if(VertexShaderStream.is_open()){
std::string Line = "";
while(getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}else{
ss << "Impossible to open " << vertex_file_path << ". Are you in the right directory?";
out->printToConsole(ss.str());
ss.clear();
ss.str(std::string());
return 0;
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
if(FragmentShaderStream.is_open()){
std::string Line = "";
while(getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
GLint Result = GL_FALSE;
int InfoLogLength;
// Compile Vertex Shader
ss << "Compiling shader : " << vertex_file_path;
out->printToConsole(ss.str());
ss.clear();
ss.str(std::string());
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
// Check Vertex Shader
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> VertexShaderErrorMessage(InfoLogLength+1);
glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
ss << &VertexShaderErrorMessage[0];
if(ss.rdbuf()->in_avail() > 0) {
error_happened = true;
out->printToConsole(ss.str());
ss.clear();
ss.str(std::string());
}
}
// Compile Fragment Shader
ss << "Compiling shader : " << fragment_file_path;
out->printToConsole(ss.str());
ss.clear();
ss.str(std::string());
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
glCompileShader(FragmentShaderID);
// Check Fragment Shader
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> FragmentShaderErrorMessage(InfoLogLength+1);
glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
ss << &FragmentShaderErrorMessage[0];
if(ss.rdbuf()->in_avail() > 0) {
error_happened = true;
out->printToConsole(ss.str());
ss.clear();
ss.str(std::string());
}
}
// Link the program
printf("Linking program\n");
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
// Check the program
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> ProgramErrorMessage(InfoLogLength+1);
glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
ss << &ProgramErrorMessage[0];
if(ss.rdbuf()->in_avail() > 0) {
out->printToConsole(ss.str());
ss.clear();
ss.str(std::string());
}
}
//move text to top of console
if(error_happened)
out->printToConsole("%%%%");
else
out->printToConsole("%%%%%%%%");
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
}
|
/* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/collective/send_v2_op.h"
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
#include "paddle/fluid/platform/collective_helper.h"
#include "paddle/fluid/platform/device/gpu/nccl_helper.h"
#endif
namespace paddle {
namespace operators {
template <typename T>
class SendOpV2CUDAKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
#if (defined(PADDLE_WITH_RCCL) || defined(PADDLE_WITH_NCCL)) && \
NCCL_VERSION_CODE >= 2703
int rid = ctx.Attr<int>("ring_id");
PADDLE_ENFORCE_GE(
rid, 0,
platform::errors::InvalidArgument(
"The ring_id (%d) for send_v2 op must be non-negative.", rid));
int peer = ctx.Attr<int>("peer");
PADDLE_ENFORCE_GE(
peer, 0,
platform::errors::InvalidArgument(
"The peer (%d) for send_v2 op must be non-negative.", peer));
gpuStream_t stream = nullptr;
auto place = ctx.GetPlace();
auto comm = platform::NCCLCommContext::Instance().Get(rid, place);
if (ctx.Attr<bool>("use_calc_stream")) {
auto dev_ctx = platform::DeviceContextPool::Instance().Get(place);
stream = static_cast<platform::CUDADeviceContext*>(dev_ctx)->stream();
} else {
stream = comm->stream();
}
PADDLE_ENFORCE_LT(
peer, comm->nranks(),
platform::errors::InvalidArgument("The value of peer (%d) you set must "
"be less than comm->nranks (%d).",
peer, comm->nranks()));
auto* x_var = ctx.InputVar("X");
if (x_var->IsType<framework::LoDTensorArray>()) {
auto& x_array = x_var->Get<framework::LoDTensorArray>();
for (size_t idx = 0; idx < x_array.size(); idx++) {
VLOG(3) << "LodTensorArray: idx(" << idx << ")";
auto& x = x_array.at(idx);
int numel = x.numel();
ncclDataType_t dtype =
platform::ToNCCLDataType(framework::TransToProtoVarType(x.dtype()));
PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclSend(
x.data<T>(), numel, dtype, peer, comm->comm(), stream));
VLOG(3) << "rank " << comm->rank() << " send "
<< pten::product(x.dims()) << " to " << peer;
}
return;
}
auto x = ctx.Input<framework::LoDTensor>("X");
int numel = x->numel();
ncclDataType_t dtype =
platform::ToNCCLDataType(framework::TransToProtoVarType(x->dtype()));
PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclSend(
x->data<T>(), numel, dtype, peer, comm->comm(), stream));
VLOG(3) << "rank " << comm->rank() << " send " << pten::product(x->dims())
<< " to " << peer;
#else
PADDLE_THROW(platform::errors::Unavailable(
"PaddlePaddle should be compiled with NCCL "
"and NCCL version >= 2.7.3 is needed."));
#endif
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
namespace plat = paddle::platform;
REGISTER_OP_CUDA_KERNEL(send_v2, ops::SendOpV2CUDAKernel<float>,
ops::SendOpV2CUDAKernel<double>,
ops::SendOpV2CUDAKernel<int>,
ops::SendOpV2CUDAKernel<int64_t>,
ops::SendOpV2CUDAKernel<plat::float16>);
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Common.hpp"
# include "PointVector.hpp"
# include "2DShapes.hpp"
# include "Mat3x2.hpp"
# include "Transformer2D.hpp"
# include "Graphics2D.hpp"
namespace s3d
{
/// @brief 2D カメラの基本クラス
class BasicCamera2D
{
public:
/// @brief デフォルトコンストラクタ
SIV3D_NODISCARD_CXX20
BasicCamera2D() = default;
/// @brief 指定した設定で 2D カメラを作成します。
/// @param center カメラが見ている中心座標の初期設定
/// @param scale カメラのズーム倍率の初期設定
SIV3D_NODISCARD_CXX20
explicit constexpr BasicCamera2D(Vec2 center, double scale = 1.0) noexcept;
/// @brief カメラが見る中心座標を設定します。
/// @param center カメラが見る中心座標
constexpr void setCenter(Vec2 center) noexcept;
/// @brief カメラが見ている中心座標を返します。
/// @return カメラが見ている中心座標
[[nodiscard]]
constexpr const Vec2& getCenter() const noexcept;
/// @brief カメラのズームアップ倍率を設定します。
/// @param scale カメラのズーム倍率
constexpr void setScale(double scale) noexcept;
/// @brief カメラのズームアップ倍率を返します。
/// @return カメラのズーム倍率
[[nodiscard]]
constexpr double getScale() const noexcept;
/// @brief カメラに映っている領域を返します。
/// @param renderTargetSize 現在のレンダーターゲットのサイズ(ピクセル)
/// @return カメラに映っている領域
[[nodiscard]]
constexpr RectF getRegion(Size renderTargetSize = Graphics2D::GetRenderTargetSize()) const noexcept;
/// @brief 現在のカメラの設定から座標変換行列を作成します。
/// @param renderTargetSize 現在のレンダーターゲットのサイズ(ピクセル)
/// @return 現在のカメラの設定から作成された座標変換行列
[[nodiscard]]
constexpr Mat3x2 getMat3x2(Size renderTargetSize = Graphics2D::GetRenderTargetSize()) const noexcept;
/// @brief 現在のカメラの設定から Transformer2D を作成します。
/// @return 現在のカメラの設定から作成された Transformer2D
[[nodiscard]]
Transformer2D createTransformer() const;
protected:
/// @brief カメラが見ている中心座標
Vec2 m_center = Vec2{ 0, 0 };
/// @brief カメラのズーム倍率
double m_scale = 1.0;
};
}
# include "detail/BasicCamera2D.ipp"
|
// Copyright 2021 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "fuzzers/fuzzer_init.h"
#include "fuzzers/tint_common_fuzzer.h"
#include "fuzzers/transform_builder.h"
namespace tint {
namespace fuzzers {
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
TransformBuilder tb(data, size);
tb.AddTransform<transform::VertexPulling>();
tint::fuzzers::CommonFuzzer fuzzer(InputFormat::kWGSL, OutputFormat::kWGSL);
fuzzer.SetTransformManager(tb.manager(), tb.data_map());
fuzzer.SetDumpInput(GetCliParams().dump_input);
return fuzzer.Run(data, size);
}
} // namespace fuzzers
} // namespace tint
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "Syncer.h"
#include "Basics/ConditionLocker.h"
#include "Basics/Exceptions.h"
#include "Basics/MutexLocker.h"
#include "Basics/RocksDBUtils.h"
#include "Basics/StaticStrings.h"
#include "Basics/VelocyPackHelper.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "Rest/HttpRequest.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/ServerIdFeature.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
#include "SimpleHttpClient/GeneralClientConnection.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "StorageEngine/PhysicalCollection.h"
#include "StorageEngine/StorageEngine.h"
#include "StorageEngine/TransactionState.h"
#include "Transaction/Helpers.h"
#include "Transaction/StandaloneContext.h"
#include "Utils/CollectionGuard.h"
#include "Utils/CollectionNameResolver.h"
#include "Utils/OperationOptions.h"
#include "Utils/OperationResult.h"
#include "Utils/SingleCollectionTransaction.h"
#include "VocBase/Identifiers/LocalDocumentId.h"
#include "VocBase/LogicalCollection.h"
#include "VocBase/LogicalView.h"
#include "VocBase/ManagedDocumentResult.h"
#include "VocBase/Methods/Indexes.h"
#include "VocBase/voc-types.h"
#include "VocBase/vocbase.h"
#include <velocypack/Builder.h>
#include <velocypack/Collection.h>
#include <velocypack/Slice.h>
#include <velocypack/StringRef.h>
#include <velocypack/velocypack-aliases.h>
namespace {
arangodb::velocypack::StringRef const cuidRef("cuid");
arangodb::velocypack::StringRef const dbRef("db");
arangodb::velocypack::StringRef const databaseRef("database");
arangodb::velocypack::StringRef const globallyUniqueIdRef("globallyUniqueId");
/// @brief extract the collection id from VelocyPack
arangodb::DataSourceId getCid(arangodb::velocypack::Slice const& slice) {
return arangodb::DataSourceId{arangodb::basics::VelocyPackHelper::extractIdValue(slice)};
}
/// @brief extract the collection name from VelocyPack
std::string getCName(arangodb::velocypack::Slice const& slice) {
return arangodb::basics::VelocyPackHelper::getStringValue(slice, "cname", "");
}
/// @brief extract the collection by either id or name, may return nullptr!
std::shared_ptr<arangodb::LogicalCollection> getCollectionByIdOrName(
TRI_vocbase_t& vocbase, arangodb::DataSourceId cid, std::string const& name) {
auto idCol = vocbase.lookupCollection(cid);
std::shared_ptr<arangodb::LogicalCollection> nameCol;
if (!name.empty()) {
// try looking up the collection by name then
nameCol = vocbase.lookupCollection(name);
}
if (idCol != nullptr && nameCol != nullptr) {
if (idCol->id() == nameCol->id()) {
// found collection by id and name, and both are identical!
return idCol;
}
// found different collections by id and name
TRI_ASSERT(!name.empty());
if (name[0] == '_') {
// system collection. always return collection by name when in doubt
return nameCol;
}
// no system collection. still prefer local collection
return nameCol;
}
if (nameCol != nullptr) {
TRI_ASSERT(idCol == nullptr);
return nameCol;
}
// may be nullptr
return idCol;
}
/// @brief apply the data from a collection dump or the continuous log
arangodb::Result applyCollectionDumpMarkerInternal(
arangodb::Syncer::SyncerState const& state,
arangodb::transaction::Methods& trx, arangodb::LogicalCollection* coll,
arangodb::TRI_replication_operation_e type, VPackSlice const& slice) {
using arangodb::OperationOptions;
using arangodb::OperationResult;
using arangodb::Result;
// key must not be empty
VPackSlice keySlice = slice.get(arangodb::StaticStrings::KeyString);
if (!keySlice.isString() || keySlice.getStringLength() == 0) {
return TRI_ERROR_REPLICATION_INVALID_RESPONSE;
}
if (type == arangodb::TRI_replication_operation_e::REPLICATION_MARKER_DOCUMENT) {
// {"type":2300,"key":"230274209405676","data":{"_key":"230274209405676","_rev":"230274209405676","foo":"bar"}}
OperationOptions options;
options.silent = true;
options.ignoreRevs = true;
options.isRestore = true;
if (!state.leaderId.empty()) {
options.isSynchronousReplicationFrom = state.leaderId;
}
// we want the conflicting other key returned in case of unique constraint
// violation
options.indexOperationMode = arangodb::IndexOperationMode::internal;
try {
OperationResult opRes(Result(), options);
bool useReplace = false;
// if we are about to process a single document marker we first check if the target
// document exists. if yes, we don't try an insert (which would fail anyway) but carry
// on with a replace.
std::pair<arangodb::LocalDocumentId, arangodb::RevisionId> lookupResult;
if (coll->getPhysical()->lookupKey(&trx, keySlice.stringRef(), lookupResult).ok()) {
// determine if we already have this revision or need to replace the
// one we have
arangodb::RevisionId rid = arangodb::RevisionId::fromSlice(slice);
if (rid.isSet() && rid == lookupResult.second) {
// we already have exactly this document, don't replace, just
// consider it already applied and bail
return {};
}
// need to replace the one we have
useReplace = true;
opRes.result.reset(TRI_ERROR_NO_ERROR, keySlice.copyString());
}
if (!useReplace) {
// try insert first
opRes = trx.insert(coll->name(), slice, options);
if (opRes.is(TRI_ERROR_ARANGO_UNIQUE_CONSTRAINT_VIOLATED)) {
useReplace = true;
}
}
if (useReplace) {
// conflicting key is contained in opRes.errorMessage() now.
// let's check if the key we have got is the same as the one
// that we would like to insert
if (keySlice.stringRef() != opRes.errorMessage()) {
// different key
if (trx.isSingleOperationTransaction()) {
// return a special error code from here, with the key of
// the conflicting document as the error message :-|
return Result(TRI_ERROR_ARANGO_TRY_AGAIN, opRes.errorMessage());
}
VPackBuilder tmp;
tmp.add(VPackValue(opRes.errorMessage()));
opRes = trx.remove(coll->name(), tmp.slice(), options);
if (opRes.ok() || !opRes.is(TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND)) {
useReplace = false;
}
}
int tries = 0;
while (tries++ < 2) {
if (useReplace) {
// perform a replace
opRes = trx.replace(coll->name(), slice, options);
} else {
// perform a re-insert
opRes = trx.insert(coll->name(), slice, options);
}
if (opRes.ok() ||
!opRes.is(TRI_ERROR_ARANGO_UNIQUE_CONSTRAINT_VIOLATED) ||
trx.isSingleOperationTransaction()) {
break;
}
// in case we get a unique constraint violation in a multi-document transaction,
// we can remove the conflicting document and try again
options.indexOperationMode = arangodb::IndexOperationMode::normal;
VPackBuilder tmp;
tmp.add(VPackValue(opRes.errorMessage()));
trx.remove(coll->name(), tmp.slice(), options);
}
}
return Result(opRes.result);
} catch (arangodb::basics::Exception const& ex) {
return Result(ex.code(),
std::string("document insert/replace operation failed: ") + ex.what());
} catch (std::exception const& ex) {
return Result(TRI_ERROR_INTERNAL,
std::string("document insert/replace operation failed: ") + ex.what());
} catch (...) {
return Result(
TRI_ERROR_INTERNAL,
std::string(
"document insert/replace operation failed: unknown exception"));
}
} else if (type == arangodb::TRI_replication_operation_e::REPLICATION_MARKER_REMOVE) {
// {"type":2302,"key":"592063"}
try {
OperationOptions options;
options.silent = true;
options.ignoreRevs = true;
if (!state.leaderId.empty()) {
options.isSynchronousReplicationFrom = state.leaderId;
}
OperationResult opRes = trx.remove(coll->name(), slice, options);
if (opRes.ok() || opRes.is(TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND)) {
// ignore document not found errors
return Result();
}
return Result(opRes.result);
} catch (arangodb::basics::Exception const& ex) {
return Result(ex.code(),
std::string("document remove operation failed: ") + ex.what());
} catch (std::exception const& ex) {
return Result(TRI_ERROR_INTERNAL,
std::string("document remove operation failed: ") + ex.what());
} catch (...) {
return Result(TRI_ERROR_INTERNAL,
std::string(
"document remove operation failed: unknown exception"));
}
}
return Result(TRI_ERROR_REPLICATION_UNEXPECTED_MARKER,
std::string("unexpected marker type ") +
arangodb::basics::StringUtils::itoa(type));
}
} // namespace
namespace arangodb {
Syncer::JobSynchronizer::JobSynchronizer(std::shared_ptr<Syncer const> const& syncer)
: _syncer(syncer), _gotResponse(false), _time(0.0), _jobsInFlight(0) {}
Syncer::JobSynchronizer::~JobSynchronizer() {
// signal that we have got something
try {
gotResponse(Result(TRI_ERROR_REPLICATION_APPLIER_STOPPED));
} catch (...) {
// must not throw from here
}
// wait until all posted jobs have been completed/canceled
while (hasJobInFlight()) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
std::this_thread::yield();
}
}
bool Syncer::JobSynchronizer::gotResponse() const noexcept {
CONDITION_LOCKER(guard, _condition);
return _gotResponse;
}
/// @brief will be called whenever a response for the job comes in
void Syncer::JobSynchronizer::gotResponse(
std::unique_ptr<arangodb::httpclient::SimpleHttpResult> response, double time) noexcept {
CONDITION_LOCKER(guard, _condition);
_res.reset(); // no error!
_response = std::move(response);
_gotResponse = true;
_time = time;
guard.signal();
}
/// @brief will be called whenever an error occurred
/// expects "res" to be an error!
void Syncer::JobSynchronizer::gotResponse(arangodb::Result&& res, double time) noexcept {
TRI_ASSERT(res.fail());
CONDITION_LOCKER(guard, _condition);
_res = std::move(res);
_response.reset();
_gotResponse = true;
_time = time;
guard.signal();
}
/// @brief the calling Syncer will call and block inside this function until
/// there is a response or the syncer/server is shut down
Result Syncer::JobSynchronizer::waitForResponse(
std::unique_ptr<arangodb::httpclient::SimpleHttpResult>& response) {
while (true) {
{
CONDITION_LOCKER(guard, _condition);
if (!_gotResponse) {
guard.wait(1 * 1000 * 1000);
}
// check again, _gotResponse may have changed
if (_gotResponse) {
_gotResponse = false;
response = std::move(_response);
return _res;
}
}
if (_syncer->isAborted()) {
// clear result response
response.reset();
CONDITION_LOCKER(guard, _condition);
_gotResponse = false;
_response.reset();
_res.reset();
// will result in returning TRI_ERROR_REPLICATION_APPLIER_STOPPED
break;
}
}
return Result(TRI_ERROR_REPLICATION_APPLIER_STOPPED);
}
void Syncer::JobSynchronizer::request(std::function<void()> const& cb) {
// by indicating that we have posted an async job, the caller
// will block on exit until all posted jobs have finished
if (!jobPosted()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_REPLICATION_APPLIER_STOPPED);
}
try {
bool queued = SchedulerFeature::SCHEDULER->queue(RequestLane::INTERNAL_LOW, [self = shared_from_this(), cb]() {
// whatever happens next, when we leave this here, we need to indicate
// that there is no more posted job.
// otherwise the calling thread may block forever waiting on the
// posted jobs to finish
auto guard = scopeGuard([self]() { self->jobDone(); });
cb();
});
if (!queued) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_QUEUE_FULL);
}
} catch (...) {
// will get here only if Scheduler::post threw
jobDone();
throw;
}
}
/// @brief notifies that a job was posted
/// returns false if job counter could not be increased (e.g. because
/// the syncer was stopped/aborted already)
bool Syncer::JobSynchronizer::jobPosted() {
while (true) {
CONDITION_LOCKER(guard, _condition);
// _jobsInFlight should be 0 in almost all cases, however, there
// is a small window in which the request has been processed already
// (i.e. after waitForResponse() has returned and before jobDone()
// has been called and has decreased _jobsInFlight). For this
// particular case, we simply wait for _jobsInFlight to become 0 again
if (_jobsInFlight == 0) {
++_jobsInFlight;
return true;
}
if (_syncer->isAborted()) {
// syncer already stopped... no need to carry on here
return false;
}
guard.wait(10 * 1000);
}
}
/// @brief notifies that a job was done
void Syncer::JobSynchronizer::jobDone() {
CONDITION_LOCKER(guard, _condition);
TRI_ASSERT(_jobsInFlight == 1);
--_jobsInFlight;
_condition.signal();
}
/// @brief checks if there are jobs in flight (can be 0 or 1 job only)
bool Syncer::JobSynchronizer::hasJobInFlight() const noexcept {
CONDITION_LOCKER(guard, _condition);
TRI_ASSERT(_jobsInFlight <= 1);
return _jobsInFlight > 0;
}
/**
* @brief Generate a new syncer ID, used for the catchup in synchronous replication.
*
* If we're running in a cluster, we're a DBServer that's using asynchronous
* replication to catch up until we can switch to synchronous replication.
*
* As in this case multiple syncers can run on the same client, syncing from the
* same server, the server ID used to identify the client with usual asynchronous
* replication on the server is not sufficiently unique. For that case, we use
* the syncer ID with a server specific tick.
*
* Otherwise, we're doing some other kind of asynchronous replication (e.g.
* active failover or dc2dc). In that case, the server specific tick would not
* be unique among clients, and the server ID will be used instead.
*
* The server distinguishes between syncer and server IDs, which is why we don't
* just return ServerIdFeature::getId() here, so e.g. SyncerId{4} and server ID 4
* will be handled as distinct values.
*/
SyncerId newSyncerId() {
if (ServerState::instance()->isRunningInCluster()) {
TRI_ASSERT(ServerState::instance()->getShortId() != 0);
return SyncerId{TRI_NewServerSpecificTick()};
}
return SyncerId{0};
}
Syncer::SyncerState::SyncerState(Syncer* syncer, ReplicationApplierConfiguration const& configuration)
: syncerId{newSyncerId()}, applier{configuration}, connection{syncer, configuration}, leader{configuration} {}
Syncer::Syncer(ReplicationApplierConfiguration const& configuration)
: _state{this, configuration} {
if (!ServerState::instance()->isSingleServer() && !ServerState::instance()->isDBServer()) {
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_NOT_IMPLEMENTED,
"the replication functionality is supposed to be invoked only on a "
"single server or DB server");
}
if (!_state.applier._database.empty()) {
// use name from configuration
_state.databaseName = _state.applier._database;
}
if (_state.applier._chunkSize == 0) {
_state.applier._chunkSize = 2 * 1024 * 1024; // default: 2 MB
} else if (_state.applier._chunkSize < 16 * 1024) {
_state.applier._chunkSize = 16 * 1024;
}
// get our own server-id
_state.localServerId = ServerIdFeature::getId();
_state.localServerIdString = basics::StringUtils::itoa(_state.localServerId.id());
_state.leader.endpoint = _state.applier._endpoint;
}
Syncer::~Syncer() = default;
/// @brief request location rewriter (injects database name)
std::string Syncer::rewriteLocation(void* data, std::string const& location) {
Syncer* s = static_cast<Syncer*>(data);
TRI_ASSERT(s != nullptr);
if (location.compare(0, 5, "/_db/", 5) == 0) {
// location already contains /_db/
return location;
}
TRI_ASSERT(!s->_state.databaseName.empty());
if (location[0] == '/') {
return "/_db/" + s->_state.databaseName + location;
}
return "/_db/" + s->_state.databaseName + "/" + location;
}
void Syncer::setAborted(bool value) { _state.connection.setAborted(value); }
bool Syncer::isAborted() const { return _state.connection.isAborted(); }
TRI_vocbase_t* Syncer::resolveVocbase(VPackSlice const& slice) {
std::string name;
if (slice.isObject()) {
VPackSlice tmp;
if ((tmp = slice.get(::dbRef)).isString()) { // wal access protocol
name = tmp.copyString();
} else if ((tmp = slice.get(::databaseRef)).isString()) { // pre 3.3
name = tmp.copyString();
}
} else if (slice.isString()) {
name = slice.copyString();
}
if (name.empty()) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"could not resolve vocbase id / name");
}
// will work with either names or id's
auto const& it = _state.vocbases.find(name);
if (it == _state.vocbases.end()) {
// automatically checks for id in string
TRI_vocbase_t* vocbase = DatabaseFeature::DATABASE->lookupDatabase(name);
if (vocbase != nullptr) {
_state.vocbases.try_emplace(name, *vocbase); //we can not be lazy because of the guard requires a valid ref
} else {
LOG_TOPIC("9bb38", DEBUG, Logger::REPLICATION) << "could not find database '" << name << "'";
}
return vocbase;
} else {
return &(it->second.database());
}
}
std::shared_ptr<LogicalCollection> Syncer::resolveCollection(
TRI_vocbase_t& vocbase, arangodb::velocypack::Slice const& slice) {
// extract "cid"
DataSourceId cid = ::getCid(slice);
if (!_state.leader.simulate32Client() || cid.empty()) {
VPackSlice uuid;
if ((uuid = slice.get(::cuidRef)).isString()) {
return vocbase.lookupCollectionByUuid(uuid.copyString());
} else if ((uuid = slice.get(::globallyUniqueIdRef)).isString()) {
return vocbase.lookupCollectionByUuid(uuid.copyString());
}
}
if (cid.empty()) {
LOG_TOPIC("fbf1a", ERR, Logger::REPLICATION)
<< "Invalid replication response: Was unable to resolve"
<< " collection from marker: " << slice.toJson();
return nullptr;
}
// extract optional "cname"
std::string cname = ::getCName(slice);
if (cname.empty()) {
cname =
arangodb::basics::VelocyPackHelper::getStringValue(slice, "name", "");
}
return ::getCollectionByIdOrName(vocbase, cid, cname);
}
Result Syncer::applyCollectionDumpMarker(transaction::Methods& trx, LogicalCollection* coll,
TRI_replication_operation_e type,
VPackSlice const& slice) {
if (_state.applier._lockTimeoutRetries > 0) {
decltype(_state.applier._lockTimeoutRetries) tries = 0;
while (true) {
Result res = ::applyCollectionDumpMarkerInternal(_state, trx, coll, type, slice);
if (res.errorNumber() != TRI_ERROR_LOCK_TIMEOUT) {
return res;
}
// lock timeout
if (++tries > _state.applier._lockTimeoutRetries) {
// timed out
return res;
}
LOG_TOPIC("569c6", DEBUG, Logger::REPLICATION)
<< "got lock timeout while waiting for lock on collection '"
<< coll->name() << "', retrying...";
std::this_thread::sleep_for(std::chrono::milliseconds(50));
// retry
}
} else {
return ::applyCollectionDumpMarkerInternal(_state, trx, coll, type, slice);
}
}
/// @brief creates a collection, based on the VelocyPack provided
Result Syncer::createCollection(TRI_vocbase_t& vocbase,
arangodb::velocypack::Slice const& slice,
LogicalCollection** dst) {
if (dst != nullptr) {
*dst = nullptr;
}
if (!slice.isObject()) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"collection slice is no object");
}
std::string const name =
basics::VelocyPackHelper::getStringValue(slice, "name", "");
if (name.empty()) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"no name specified for collection");
}
TRI_col_type_e const type = static_cast<TRI_col_type_e>(
basics::VelocyPackHelper::getNumericValue<int>(slice, "type", TRI_COL_TYPE_DOCUMENT));
// resolve collection by uuid, name, cid (in that order of preference)
auto col = resolveCollection(vocbase, slice);
if (col != nullptr && col->type() == type &&
(!_state.leader.simulate32Client() || col->name() == name)) {
// collection already exists. TODO: compare attributes
return Result();
}
bool forceRemoveCid = false;
if (col != nullptr && _state.leader.simulate32Client()) {
forceRemoveCid = true;
LOG_TOPIC("01f9f", INFO, Logger::REPLICATION)
<< "would have got a wrong collection!";
// go on now and truncate or drop/re-create the collection
}
// conflicting collections need to be dropped from 3.3 onwards
col = vocbase.lookupCollection(name);
if (col != nullptr) {
if (col->system()) {
TRI_ASSERT(!_state.leader.simulate32Client() || col->guid() == col->name());
SingleCollectionTransaction trx(transaction::StandaloneContext::Create(vocbase),
*col, AccessMode::Type::WRITE);
trx.addHint(transaction::Hints::Hint::INTERMEDIATE_COMMITS);
trx.addHint(transaction::Hints::Hint::ALLOW_RANGE_DELETE);
Result res = trx.begin();
if (!res.ok()) {
return res;
}
OperationOptions opts;
OperationResult opRes = trx.truncate(col->name(), opts);
if (opRes.fail()) {
return opRes.result;
}
return trx.finish(opRes.result);
} else {
vocbase.dropCollection(col->id(), false, -1.0);
}
}
VPackSlice uuid = slice.get(StaticStrings::DataSourceGuid);
// merge in "isSystem" attribute, doesn't matter if name does not start with
// '_'
VPackBuilder s;
s.openObject();
s.add(StaticStrings::DataSourceSystem, VPackValue(true));
if ((uuid.isString() && !_state.leader.simulate32Client()) || forceRemoveCid) { // need to use cid for 3.2 leader
// if we received a globallyUniqueId from the remote, then we will always
// use this id so we can discard the "cid" and "id" values for the
// collection
s.add(StaticStrings::DataSourceId, VPackSlice::nullSlice());
s.add("cid", VPackSlice::nullSlice());
}
s.close();
VPackBuilder merged = VPackCollection::merge(slice, s.slice(), /*mergeValues*/ true,
/*nullMeansRemove*/ true);
// we need to remove every occurence of objectId as a key
auto stripped = rocksutils::stripObjectIds(merged.slice());
try {
col = vocbase.createCollection(stripped.first);
} catch (basics::Exception const& ex) {
return Result(ex.code(), ex.what());
} catch (std::exception const& ex) {
return Result(TRI_ERROR_INTERNAL, ex.what());
} catch (...) {
return Result(TRI_ERROR_INTERNAL);
}
TRI_ASSERT(col != nullptr);
TRI_ASSERT(!uuid.isString() || uuid.compareString(col->guid()) == 0);
if (dst != nullptr) {
*dst = col.get();
}
return Result();
}
/// @brief drops a collection, based on the VelocyPack provided
Result Syncer::dropCollection(VPackSlice const& slice, bool reportError) {
TRI_vocbase_t* vocbase = resolveVocbase(slice);
if (vocbase == nullptr) {
return Result(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
auto* col = resolveCollection(*vocbase, slice).get();
if (col == nullptr) {
if (reportError) {
return Result(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND);
}
return Result();
}
return vocbase->dropCollection(col->id(), true, -1.0);
}
/// @brief creates an index, based on the VelocyPack provided
Result Syncer::createIndex(VPackSlice const& slice) {
VPackSlice indexSlice = slice.get("index");
if (!indexSlice.isObject()) {
indexSlice = slice.get("data");
}
if (!indexSlice.isObject()) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"index slice is not an object");
}
TRI_vocbase_t* vocbase = resolveVocbase(slice);
if (vocbase == nullptr) {
return Result(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
auto col = resolveCollection(*vocbase, slice);
if (col == nullptr) {
return Result(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND,
"did not find collection for index");
}
VPackBuilder s;
s.openObject();
s.add("objectId", VPackSlice::nullSlice());
s.close();
VPackBuilder merged =
VPackCollection::merge(indexSlice, s.slice(),
/*mergeValues*/ true, /*nullMeansRemove*/ true);
try {
VPackSlice idxDef = merged.slice();
createIndexInternal(idxDef, *col);
} catch (arangodb::basics::Exception const& ex) {
return Result(ex.code(),
std::string("caught exception while creating index: ") + ex.what());
} catch (std::exception const& ex) {
return Result(TRI_ERROR_INTERNAL,
std::string("caught exception while creating index: ") + ex.what());
} catch (...) {
return Result(TRI_ERROR_INTERNAL,
"caught unknown exception while creating index");
}
return Result();
}
void Syncer::createIndexInternal(VPackSlice const& idxDef, LogicalCollection& col) {
std::shared_ptr<arangodb::Index> idx;
auto physical = col.getPhysical();
TRI_ASSERT(physical != nullptr);
// check any identifier conflicts first
{
// check ID first
IndexId iid = IndexId::none();
std::string name; // placeholder for now
CollectionNameResolver resolver(col.vocbase());
Result res = methods::Indexes::extractHandle(&col, &resolver, idxDef, iid, name);
if (res.ok() && iid.isSet()) {
// lookup by id
auto byId = physical->lookupIndex(iid);
auto byDef = physical->lookupIndex(idxDef);
if (byId != nullptr) {
if (byDef == nullptr || byId != byDef) {
// drop existing byId
physical->dropIndex(byId->id());
} else {
idx = byId;
}
}
}
// now check name;
name = basics::VelocyPackHelper::getStringValue(idxDef, StaticStrings::IndexName,
"");
if (!name.empty()) {
// lookup by name
auto byName = physical->lookupIndex(name);
auto byDef = physical->lookupIndex(idxDef);
if (byName != nullptr) {
if (byDef == nullptr || byName != byDef) {
// drop existing byName
physical->dropIndex(byName->id());
} else if (idx != nullptr && byName != idx) {
// drop existing byName and byId
physical->dropIndex(byName->id());
physical->dropIndex(idx->id());
idx = nullptr;
} else {
idx = byName;
}
}
}
}
if (idx == nullptr) {
bool created = false;
idx = physical->createIndex(idxDef, /*restore*/ true, created);
}
TRI_ASSERT(idx != nullptr);
}
Result Syncer::dropIndex(arangodb::velocypack::Slice const& slice) {
auto cb = [&](VPackSlice const& slice) {
std::string id;
if (slice.hasKey("data")) {
id = basics::VelocyPackHelper::getStringValue(slice.get("data"), "id", "");
} else {
id = basics::VelocyPackHelper::getStringValue(slice, "id", "");
}
if (id.empty()) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"id not found in index drop slice");
}
IndexId const iid{basics::StringUtils::uint64(id)};
TRI_vocbase_t* vocbase = resolveVocbase(slice);
if (vocbase == nullptr) {
return Result(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
auto col = resolveCollection(*vocbase, slice);
if (!col) {
return Result(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND);
}
try {
CollectionGuard guard(vocbase, col->id());
bool result = guard.collection()->dropIndex(iid);
if (!result) {
return Result(); // TODO: why do we ignore failures here?
}
return Result();
} catch (arangodb::basics::Exception const& ex) {
return Result(ex.code(), ex.what());
} catch (std::exception const& ex) {
return Result(TRI_ERROR_INTERNAL, ex.what());
} catch (...) {
return Result(TRI_ERROR_INTERNAL);
}
};
Result r = cb(slice);
if (r.fail() && (r.is(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND) ||
r.is(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND))) {
// if dropping an index for a non-existing database or collection fails,
// this is not a real problem
return Result();
}
return r;
}
/// @brief creates a view, based on the VelocyPack provided
Result Syncer::createView(TRI_vocbase_t& vocbase, arangodb::velocypack::Slice const& slice) {
if (!slice.isObject()) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"collection slice is no object");
}
VPackSlice nameSlice = slice.get(StaticStrings::DataSourceName);
if (!nameSlice.isString() || nameSlice.getStringLength() == 0) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"no name specified for view");
}
VPackSlice guidSlice = slice.get(StaticStrings::DataSourceGuid);
if (!guidSlice.isString() || guidSlice.getStringLength() == 0) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"no guid specified for view");
}
VPackSlice typeSlice = slice.get(StaticStrings::DataSourceType);
if (!typeSlice.isString() || typeSlice.getStringLength() == 0) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"no type specified for view");
}
auto view = vocbase.lookupView(guidSlice.copyString());
if (view) { // identical view already exists
if (!nameSlice.isEqualString(view->name())) {
auto res = view->rename(nameSlice.copyString());
if (!res.ok()) {
return res;
}
}
return view->properties(slice, false); // always a full-update
}
// check for name conflicts
view = vocbase.lookupView(nameSlice.copyString());
if (view) { // resolve name conflict by deleting existing
Result res = view->drop();
if (res.fail()) {
return res;
}
}
VPackBuilder s;
s.openObject();
s.add("id", VPackSlice::nullSlice());
s.close();
VPackBuilder merged = VPackCollection::merge(slice, s.slice(), /*mergeValues*/ true,
/*nullMeansRemove*/ true);
try {
LogicalView::ptr empty; // ignore result
return LogicalView::create(empty, vocbase, merged.slice());
} catch (basics::Exception const& ex) {
return Result(ex.code(), ex.what());
} catch (std::exception const& ex) {
return Result(TRI_ERROR_INTERNAL, ex.what());
} catch (...) {
return Result(TRI_ERROR_INTERNAL);
}
}
/// @brief drops a view, based on the VelocyPack provided
Result Syncer::dropView(arangodb::velocypack::Slice const& slice, bool reportError) {
TRI_vocbase_t* vocbase = resolveVocbase(slice);
if (vocbase == nullptr) {
return Result(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
VPackSlice guidSlice = slice.get(::globallyUniqueIdRef);
if (guidSlice.isNone()) {
guidSlice = slice.get(::cuidRef);
}
if (!guidSlice.isString() || guidSlice.getStringLength() == 0) {
return Result(TRI_ERROR_REPLICATION_INVALID_RESPONSE,
"no guid specified for view");
}
try {
TRI_ASSERT(!ServerState::instance()->isCoordinator());
auto view = vocbase->lookupView(guidSlice.copyString());
if (view) { // prevent dropping of system views ?
return view->drop();
}
} catch (basics::Exception const& ex) {
return Result(ex.code(), ex.what());
} catch (std::exception const& ex) {
return Result(TRI_ERROR_INTERNAL, ex.what());
} catch (...) {
return Result(TRI_ERROR_INTERNAL);
}
return Result();
}
void Syncer::reloadUsers() {
AuthenticationFeature* af = AuthenticationFeature::instance();
auth::UserManager* um = af->userManager();
if (um != nullptr) {
um->triggerLocalReload();
}
}
SyncerId Syncer::syncerId() const noexcept { return _state.syncerId; }
} // namespace arangodb
|
#include <stdafx.h>
#include "art_helpers.h"
#include <events/event_dispatcher.h>
#include <events/event_js_callback.h>
#include <utils/gdi_helpers.h>
#include <utils/image_helpers.h>
#include <utils/thread_pool_instance.h>
#include <Shlwapi.h>
#include <qwr/abort_callback.h>
#include <qwr/string_helpers.h>
#include <algorithm>
using namespace smp;
namespace
{
class AlbumArtFetchTask
{
public:
AlbumArtFetchTask( HWND hNotifyWnd, metadb_handle_ptr handle, const art::LoadingOptions& options );
AlbumArtFetchTask( const AlbumArtFetchTask& ) = delete;
AlbumArtFetchTask& operator=( const AlbumArtFetchTask& ) = delete;
void operator()();
private:
void run();
private:
HWND hNotifyWnd_;
metadb_handle_ptr handle_;
const art::LoadingOptions options_;
};
} // namespace
namespace
{
const std::array<const GUID*, 5> gKnownArtGuids = {
&album_art_ids::cover_front,
&album_art_ids::cover_back,
&album_art_ids::disc,
&album_art_ids::icon,
&album_art_ids::artist
};
}
namespace
{
AlbumArtFetchTask::AlbumArtFetchTask( HWND hNotifyWnd, metadb_handle_ptr handle, const art::LoadingOptions& options )
: hNotifyWnd_( hNotifyWnd )
, handle_( handle )
, options_( options )
{
}
void AlbumArtFetchTask::operator()()
{
return run();
}
void AlbumArtFetchTask::run()
{
qwr::u8string imagePath;
auto bitmap = art::GetBitmapFromMetadbOrEmbed( handle_, options_, &imagePath );
EventDispatcher::Get().PutEvent( hNotifyWnd_,
GenerateEvent_JsCallback(
EventId::kInternalGetAlbumArtDone,
handle_,
options_.artId,
std::move( bitmap ),
imagePath ) );
}
std::unique_ptr<Gdiplus::Bitmap> GetBitmapFromAlbumArtData( const album_art_data_ptr& data )
{
if ( !data.is_valid() )
{
return nullptr;
}
IStreamPtr pStream;
{
auto pMemStream = SHCreateMemStream( nullptr, 0 );
if ( !pMemStream )
{
return nullptr;
}
// copy and assignment operators increase Stream ref count,
// while SHCreateMemStream returns object with ref count 1,
// so we need to take ownership without increasing ref count
// (or decrease ref count manually)
pStream.Attach( pMemStream );
}
ULONG bytes_written = 0;
HRESULT hr = pStream->Write( data->get_ptr(), data->get_size(), &bytes_written );
if ( FAILED( hr ) || bytes_written != data->get_size() )
{
return nullptr;
}
auto pImg = std::make_unique<Gdiplus::Bitmap>( static_cast<IStream*>( pStream ), TRUE );
if ( !gdi::IsGdiPlusObjectValid( pImg ) )
{
return smp::image::LoadImageWithWIC( pStream );
}
return pImg;
}
/// @details Throws pfc::exception, if art is not found or if aborted
std::unique_ptr<Gdiplus::Bitmap> ExtractBitmap( album_art_extractor_instance_v2::ptr extractor, const GUID& artTypeGuid, bool onlyGetPath, qwr::u8string* pImagePath, abort_callback& abort )
{
album_art_data_ptr data = extractor->query( artTypeGuid, abort );
std::unique_ptr<Gdiplus::Bitmap> bitmap;
if ( !onlyGetPath )
{
bitmap = GetBitmapFromAlbumArtData( data );
}
if ( pImagePath && ( onlyGetPath || bitmap ) )
{
auto pathlist = extractor->query_paths( artTypeGuid, abort );
if ( pathlist->get_count() )
{
*pImagePath = file_path_display( pathlist->get_path( 0 ) );
}
}
return bitmap;
}
} // namespace
namespace smp::art
{
EmbedThread::EmbedThread( EmbedAction action,
album_art_data_ptr data,
const metadb_handle_list& handles,
GUID what )
: action_( action )
, data_( data )
, handles_( handles )
, what_( what )
{
}
void EmbedThread::run( threaded_process_status& p_status,
abort_callback& p_abort )
{
auto api = file_lock_manager::get();
const auto stlHandleList = qwr::pfc_x::Make_Stl_Ref( handles_ );
for ( const auto& [i, handle]: ranges::views::enumerate( stlHandleList ) )
{
const qwr::u8string path = handle->get_path();
p_status.set_progress( i, stlHandleList.size() );
p_status.set_item_path( path.c_str() );
album_art_editor::ptr ptr;
if ( !album_art_editor::g_get_interface( ptr, path.c_str() ) )
{
continue;
}
try
{
auto scopedLock = api->acquire_write( path.c_str(), p_abort );
auto aaep = ptr->open( nullptr, path.c_str(), p_abort );
switch ( action_ )
{
case EmbedAction::embed:
{
aaep->set( what_, data_, p_abort );
break;
}
case EmbedAction::remove:
{
aaep->remove( what_ );
break;
}
case EmbedAction::removeAll:
{
album_art_editor_instance_v2::ptr v2;
if ( aaep->cast( v2 ) )
{ // not all file formats support this
v2->remove_all();
}
else
{ // m4a is one example that needs this fallback
for ( const auto pGuid: gKnownArtGuids )
{
aaep->remove( *pGuid );
}
}
break;
}
default:
assert( 0 );
break;
}
aaep->commit( p_abort );
}
catch ( const pfc::exception& )
{ // operation failed (e.g. file does not support art embedding)
}
}
}
const GUID& GetGuidForArtId( uint32_t art_id )
{
qwr::QwrException::ExpectTrue( art_id < gKnownArtGuids.size(), "Unknown art_id: {}", art_id );
return *gKnownArtGuids[art_id];
}
std::unique_ptr<Gdiplus::Bitmap> GetBitmapFromEmbeddedData( const qwr::u8string& rawpath, uint32_t art_id )
{
const pfc::string_extension extension( rawpath.c_str() );
const GUID& artTypeGuid = GetGuidForArtId( art_id );
qwr::TimedAbortCallback abort;
for ( service_enum_t<album_art_extractor> e; !e.finished(); ++e )
{
auto extractor = e.get();
if ( !extractor->is_our_path( rawpath.c_str(), extension ) )
{
continue;
}
try
{
auto aaep = extractor->open( nullptr, rawpath.c_str(), abort );
auto data = aaep->query( artTypeGuid, abort );
return GetBitmapFromAlbumArtData( data );
}
catch ( const pfc::exception& )
{ // not found or aborted
}
}
return nullptr;
}
std::unique_ptr<Gdiplus::Bitmap> GetBitmapFromMetadb( const metadb_handle_ptr& handle, const LoadingOptions& options, qwr::u8string* pImagePath )
{
assert( handle.is_valid() );
const GUID& artTypeGuid = GetGuidForArtId( options.artId );
qwr::TimedAbortCallback abort;
auto aamv2 = album_art_manager_v2::get();
try
{
auto aaeiv2 = aamv2->open( pfc::list_single_ref_t<metadb_handle_ptr>( handle ), pfc::list_single_ref_t<GUID>( artTypeGuid ), abort );
return ExtractBitmap( aaeiv2, artTypeGuid, options.onlyGetPath, pImagePath, abort );
}
catch ( const pfc::exception& )
{ // not found or aborted
if ( options.fallbackToStubImage )
{
try
{
auto aaeiv2 = aamv2->open_stub( abort );
return ExtractBitmap( aaeiv2, artTypeGuid, options.onlyGetPath, pImagePath, abort );
}
catch ( const pfc::exception& )
{ // not found or aborted
}
}
}
return nullptr;
}
std::unique_ptr<Gdiplus::Bitmap> GetBitmapFromMetadbOrEmbed( const metadb_handle_ptr& handle, const LoadingOptions& options, qwr::u8string* pImagePath )
{
assert( handle.is_valid() );
qwr::u8string imagePath;
std::unique_ptr<Gdiplus::Bitmap> bitmap;
try
{
if ( options.loadOnlyEmbedded )
{
bitmap = GetBitmapFromEmbeddedData( handle->get_path(), options.artId );
if ( bitmap )
{
imagePath = handle->get_path();
}
}
else
{
bitmap = GetBitmapFromMetadb( handle, options, &imagePath );
}
}
catch ( const qwr::QwrException& )
{ // The only possible exception is invalid art id, which should be checked beforehand
assert( 0 );
}
if ( pImagePath )
{
*pImagePath = ( imagePath.empty() ? "" : file_path_display( imagePath.c_str() ).get_ptr() );
}
return bitmap;
}
void GetAlbumArtAsync( HWND hWnd, const metadb_handle_ptr& handle, const LoadingOptions& options )
{
assert( handle.is_valid() );
// Art id is validated in LoadingOptions constructor, so we don't need to worry about it here
smp::GetThreadPoolInstance().AddTask( [task = std::make_shared<AlbumArtFetchTask>( hWnd, handle, options )] {
std::invoke( *task );
} );
}
} // namespace smp::art
|
//
// This file is part of Easylogging++ samples
// TIMED_BLOCK sample
//
// Revision 1.1
// @author mkhan3189
//
#include "easylogging++.h"
INITIALIZE_EASYLOGGINGPP
int main(int argc, char** argv) {
START_EASYLOGGINGPP(argc, argv);
TIMED_BLOCK(t, "my-block") {
for (long i = 0; i <= 300; ++i) {
LOG(INFO) << "This is for-block 1";
}
t.timer->checkpoint("checkpoint-1"); // Note t.timer to access el::base::Trackable
for (int i = 0; i <= 200; ++i) {
LOG(INFO) << "This is for-block 2";
}
}
LOG(INFO) << "You should get performance result of above scope";
return 0;
}
|
#include "xtcdata/xtc/NamesIter.hh"
using namespace XtcData;
int NamesIter::process(Xtc* xtc)
{
switch (xtc->contains.id()) {
case (TypeId::Parent): {
iterate(xtc); // look inside anything that is a Parent
break;
}
case (TypeId::Names): {
Names& names = *(Names*)xtc;
NamesId& namesId = names.namesId();
_namesLookup[namesId] = NameIndex(names);
break;
}
default:
break;
}
return Continue;
}
|
// Copyright John Maddock 2006.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Basic sanity check that header <boost/math/distributions/cauchy.hpp>
// #includes all the files that it needs to.
//
#define BOOST_MATH_ASSERT_UNDEFINED_POLICY false
#include <boost/math/distributions/cauchy.hpp>
//
// Note this header includes no other headers, this is
// important if this test is to be meaningful:
//
#include "test_compile_result.hpp"
void check()
{
TEST_DIST_FUNC(cauchy)
}
template class boost::math::cauchy_distribution<float, boost::math::policies::policy<> >;
template class boost::math::cauchy_distribution<double, boost::math::policies::policy<> >;
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
template class boost::math::cauchy_distribution<long double, boost::math::policies::policy<> >;
#endif
|
/*--------------------------------------------------------------------------------
Copyright (c) Microsoft Corporation. All rights reserved.
*/
/**
\file
\brief Test class the statistical disk pal for physical disks.
\date 2008-06-18 11:08:56
*/
/*----------------------------------------------------------------------------*/
#include <scxcorelib/scxcmn.h>
#include <scxsystemlib/statisticalphysicaldiskenumeration.h>
#include <cppunit/extensions/HelperMacros.h>
#include <testutils/scxunit.h>
#include <scxcorelib/scxexception.h>
#include <scxcorelib/scxfile.h>
#include <scxcorelib/stringaid.h>
#include <testutils/scxtestutils.h>
using namespace SCXSystemLib;
#include "diskdepend_mock.h"
class SCXStatisticalPhysicalDiskTest : public CPPUNIT_NS::TestFixture
{
CPPUNIT_TEST_SUITE( SCXStatisticalPhysicalDiskTest );
CPPUNIT_TEST( callDumpStringForCoverage );
#if defined(sun)
CPPUNIT_TEST( Test_Huge_Mount_Table_bug507232 );
CPPUNIT_TEST( TestBug15583_DoNotDiscoverCdromForSolaris );
#endif
#if defined(hpux)
CPPUNIT_TEST( TestBug6755_PartialHPUXDiscovery );
#endif
CPPUNIT_TEST_SUITE_END();
private:
SCXCoreLib::SCXHandle<SCXSystemLib::StatisticalPhysicalDiskEnumeration> m_diskEnum;
std::wstring fauxMntTab;
public:
SCXStatisticalPhysicalDiskTest()
{
fauxMntTab = L"test_mnttab";
}
void setUp(void)
{
m_diskEnum = 0;
}
void tearDown(void)
{
unlink(SCXCoreLib::StrToUTF8(fauxMntTab).c_str());
if (m_diskEnum != 0)
{
m_diskEnum->CleanUp();
m_diskEnum = 0;
}
}
void callDumpStringForCoverage()
{
SCXCoreLib::SCXHandle<DiskDependTest> deps( new DiskDependTest() );
StatisticalPhysicalDiskInstance inst(deps);
CPPUNIT_ASSERT(inst.DumpString().find(L"StatisticalDiskInstance") != std::wstring::npos);
}
#if defined(sun)
/*----------------------------------------------------------------------------*/
/**
Created for bug #507232 (RFC: File Descriptor leak in OM2007 R2 Xplat agent
on Solaris 8 and 10)
This problem occurs on systems with a mount table with more than ~500 to ~1000
entries that are not ignored file systems. There is a kstat handle that is opened
for each StatisticalDiskInstance for performance reasons. This customer's system
had tens of thousands of 'mvfs' mount points, each of which would have a
StatisticalDiskInstance, and thus a kstat handle. This led to the failure of
'kstat_open' once too many kstat handles were open. This problem was resolved by
including 'mvfs' in the ignored file systems array.
\date 2013-02-14
*/
void Test_Huge_Mount_Table_bug507232()
{
SCXCoreLib::SCXHandle<DiskDependTest> deps( new DiskDependTest() );
deps->SetMountTabPath(L"./testfiles/bug507232_mnttab");
CPPUNIT_ASSERT_NO_THROW(m_diskEnum = new SCXSystemLib::MockSolarisStatisticalPhysicalDiskEnumeration(deps));
CPPUNIT_ASSERT_NO_THROW(m_diskEnum->Init());
CPPUNIT_ASSERT_NO_THROW(m_diskEnum->Update(true));
}
#endif
/*----------------------------------------------------------------------------*/
/**
Created for Bug #15583 (QFE: CSS: Customer get 'disk full' alerts when
mounting CD-roms). The problem occurs in the Statistical Logical Disk
Enumeration (which reads /etc/mnttab). From the Solaris documentation,
we know that "the file /etc/mnttab is really a file system that provides
read-only access to the table of mounted file systems for the current host."
Thus for Solaris it is not sufficient to decide on the file system format, the
device path must also be examined.
\date 12/02/2009
*/
void TestBug15583_DoNotDiscoverCdromForSolaris()
{
SCXCoreLib::SCXHandle<DiskDependTest> deps( new DiskDependTest() );
deps->SetOpenErrno("/dev/dsk/c0t0d0", 0);
deps->SetOpenErrno("/dev/dsk/c0t0d0s0",0); // Set to zero to fake file and ioctl operations.
deps->SetOpenErrno("/dev/dsk/c0t0d0s1",0);
deps->SetOpenErrno("/dev/dsk/c0t0d0s2",0);
deps->SetOpenErrno("/dev/dsk/c0t0d0s4",0);
deps->SetOpenErrno("/dev/dsk/c0t0d0s5",0);
deps->SetOpenErrno("/dev/dsk/c0t0d0s6",0);
deps->SetOpenErrno("/dev/dsk/c0t0d0s7",0);
deps->SetOpenErrno("/dev/dsk/c9t0d0", 0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s0",0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s1",0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s2",0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s3",0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s4",0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s5",0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s6",0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s7",0);
deps->SetOpenErrno("/dev/dsk/c9t1d0s0",0);
deps->SetOpenErrno("/dev/dsk/c9t1d0s1",0);
deps->SetOpenErrno("/dev/dsk/c9t1d0s2",0);
deps->SetOpenErrno("/dev/dsk/c9t1d0s3",0);
deps->SetOpenErrno("/dev/dsk/c9t1d0s4",0);
deps->SetOpenErrno("/dev/dsk/c9t1d0s5",0);
deps->SetOpenErrno("/dev/dsk/c9t1d0s6",0);
deps->SetOpenErrno("/dev/dsk/c9t1d0s7",0);
struct stat statData;
memset(&statData, 0, sizeof(statData));
deps->SetStat("/dev/dsk/c0t0d0", statData);
deps->SetStat("/dev/dsk/c0t0d0s0", statData);
deps->SetStat("/dev/dsk/c0t0d0s0",statData);
deps->SetStat("/dev/dsk/c0t0d0s1",statData);
deps->SetStat("/dev/dsk/c0t0d0s2",statData);
deps->SetStat("/dev/dsk/c0t0d0s4",statData);
deps->SetStat("/dev/dsk/c0t0d0s5",statData);
deps->SetStat("/dev/dsk/c0t0d0s6",statData);
deps->SetStat("/dev/dsk/c0t0d0s7",statData);
deps->SetStat("/dev/dsk/c9t0d0", statData);
deps->SetStat("/dev/dsk/c9t0d0s0",statData);
deps->SetStat("/dev/dsk/c9t0d0s1",statData);
deps->SetStat("/dev/dsk/c9t0d0s2",statData);
deps->SetStat("/dev/dsk/c9t0d0s3",statData);
deps->SetStat("/dev/dsk/c9t0d0s4",statData);
deps->SetStat("/dev/dsk/c9t0d0s5",statData);
deps->SetStat("/dev/dsk/c9t0d0s6",statData);
deps->SetStat("/dev/dsk/c9t0d0s7",statData);
deps->SetStat("/dev/dsk/c9t1d0s0",statData);
deps->SetStat("/dev/dsk/c9t1d0s1",statData);
deps->SetStat("/dev/dsk/c9t1d0s2",statData);
deps->SetStat("/dev/dsk/c9t1d0s3",statData);
deps->SetStat("/dev/dsk/c9t1d0s4",statData);
deps->SetStat("/dev/dsk/c9t1d0s5",statData);
deps->SetStat("/dev/dsk/c9t1d0s6",statData);
deps->SetStat("/dev/dsk/c9t1d0s7",statData);
SCXCoreLib::SelfDeletingFilePath mntTab(fauxMntTab);
FILE* fp = fopen(SCXCoreLib::StrToUTF8(fauxMntTab).c_str(), "wb");
CPPUNIT_ASSERT(0 != fp);
// Note: sample data comes from a Solaris 9 development box with a UFS CD
// in the drive. The SPARC (not the x86) installation media is an example
// of a CD-ROM with a UFS file system.
fprintf(fp,
"/dev/dsk/c9t0d0s0 / ufs rw,intr,largefiles,logging,xattr,onerror=panic,suid,dev=800010 1258671407\n"
"/proc /proc proc dev=4600000 1258671406\n"
"mnttab /etc/mnttab mntfs dev=46c0000 1258671406\n"
"fd /dev/fd fd rw,suid,dev=4700000 1258671407\n"
"swap /var/run tmpfs xattr,dev=1 1258671408\n"
"swap /tmp tmpfs xattr,dev=2 1258671409\n"
"/dev/dsk/c9t0d0s7 /export/home ufs rw,intr,largefiles,logging,xattr,onerror=panic,suid,dev=800017 1258671409\n"
"-hosts /net autofs indirect,nosuid,ignore,nobrowse,dev=4880001 1258671410\n"
"auto_home /home autofs indirect,ignore,nobrowse,dev=4880002 1258671410\n"
"-xfn /xfn autofs indirect,ignore,dev=4880003 1258671410\n"
"scxsun14:vold(pid345) /vol nfs ignore,noquota,dev=4840001 1258671413\n"
"/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s6 /cdrom/sol_10_606_sparc/s6 ufs ro,intr,largefiles,xattr,onerror=panic,nosuid,dev=16c0007 1259791871\n"
"/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s5 /cdrom/sol_10_606_sparc/s5 ufs ro,intr,largefiles,xattr,onerror=panic,nosuid,dev=16c0006 1259791871\n"
"/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s4 /cdrom/sol_10_606_sparc/s4 ufs ro,intr,largefiles,xattr,onerror=panic,nosuid,dev=16c0005 1259791872\n"
"/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s3 /cdrom/sol_10_606_sparc/s3 ufs ro,intr,largefiles,xattr,onerror=panic,nosuid,dev=16c0004 1259791872\n"
"/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s2 /cdrom/sol_10_606_sparc/s2 ufs ro,intr,largefiles,xattr,onerror=panic,nosuid,dev=16c0003 1259791872\n"
"/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s1 /cdrom/sol_10_606_sparc/s1 ufs ro,intr,largefiles,xattr,onerror=panic,nosuid,dev=16c0002 1259791872\n"
"/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s0 /cdrom/sol_10_606_sparc/s0 hsfs maplcase,noglobal,nosuid,ro,rr,traildot,dev=16c0001 1259791873\n");
fclose(fp);
deps->SetMountTabPath(fauxMntTab);
deps->SetOpenErrno("/dev/dsk/c9t0d0", 0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s0", 0);
deps->SetOpenErrno("/dev/dsk/c9t0d0s7", 0);
deps->SetOpenErrno("/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s6", 0);
deps->SetOpenErrno("/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s5", 0);
deps->SetOpenErrno("/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s4", 0);
deps->SetOpenErrno("/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s3", 0);
deps->SetOpenErrno("/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s2", 0);
deps->SetOpenErrno("/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s1", 0);
deps->SetOpenErrno("/vol/dev/dsk/c0t0d0/sol_10_606_sparc/s0", 0);
CPPUNIT_ASSERT_NO_THROW(m_diskEnum = new SCXSystemLib::MockSolarisStatisticalPhysicalDiskEnumeration(deps));
CPPUNIT_ASSERT_NO_THROW(m_diskEnum->Init());
CPPUNIT_ASSERT_NO_THROW(m_diskEnum->Update(true));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Found the wrong number of disks from (a fake) MNT TAB file",
static_cast<size_t>(1), m_diskEnum->Size());
SCXCoreLib::SCXHandle<SCXSystemLib::StatisticalPhysicalDiskInstance> di = *(m_diskEnum->Begin());
std::wstring expected(L"c9t0d0");
std::wstring actual;
CPPUNIT_ASSERT(di->GetDiskDeviceID(actual));
// Verify that the name of the only device returned
CPPUNIT_ASSERT_EQUAL_MESSAGE("Received wrong name of for the discovered device.", 0, expected.compare(actual));
}
#if defined(hpux)
void TestBug6755_PartialHPUXDiscovery()
{
SCXCoreLib::SCXHandle<DiskDependTest> deps( new DiskDependTest() );
deps->SetOpenErrno("/dev/rdisk/disk3",0); // Set to zero to fake file and ioctl operations.
deps->SetOpenErrno("/dev/rdisk/disk5",ENXIO);
deps->SetOpenErrno("/dev/rdisk/disk7",ENXIO);
SCXCoreLib::SelfDeletingFilePath mntTab(fauxMntTab);
FILE* fp = fopen(SCXCoreLib::StrToUTF8(fauxMntTab).c_str(), "wb");
CPPUNIT_ASSERT(0 != fp);
fprintf(fp,
"/dev/vg00/lvol3 / vxfs ioerror=nodisable,log,dev=40000003 0 1 1213709666\n"
"DevFS /dev/deviceFileSystem DevFS defaults,dev=4000000 0 0 1213709709\n"
"-hosts /net autofs ignore,indirect,nosuid,soft,nobrowse,dev=4000003 0 0 1213709740\n");
fclose(fp);
deps->SetMountTabPath(fauxMntTab);
SCXCoreLib::SCXHandle<LvmTabTest> lvmtab( new LvmTabTest() );
lvmtab->AddVG(L"/dev/vg00", L"/dev/disk/disk3", L"/dev/disk/disk5");
lvmtab->AddVG(L"/dev/vg01", L"/dev/disk/disk7");
deps->SetLvmTab(lvmtab);
memset(&m_diskInfo, 0, sizeof(m_diskInfo));
m_diskInfo.psd_dev.psd_minor = 3;
deps->SetPstDiskInfo(&m_diskInfo, 1);
struct stat statData;
memset(&statData, 0, sizeof(statData));
deps->SetStat("/dev/disk/disk5", statData);
deps->SetStat("/dev/disk/disk7", statData);
statData.st_rdev = 3;
deps->SetStat("/dev/disk/disk3", statData);
CPPUNIT_ASSERT_NO_THROW(m_diskEnum = new SCXSystemLib::StatisticalPhysicalDiskEnumeration(deps));
CPPUNIT_ASSERT_NO_THROW(m_diskEnum->Init());
CPPUNIT_ASSERT_NO_THROW(m_diskEnum->Update(true));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), m_diskEnum->Size());
SCXCoreLib::SCXHandle<SCXSystemLib::StatisticalPhysicalDiskInstance> di = *m_diskEnum->Begin();
std::wstring id;
CPPUNIT_ASSERT(di->GetDiskName(id));
CPPUNIT_ASSERT(L"disk3" == id);
/*
for (SCXSystemLib::EntityEnumeration<SCXSystemLib::StatisticalPhysicalDiskInstance>::EntityIterator iter = m_diskEnum->Begin(); iter != m_diskEnum->End(); iter++)
{
SCXSystemLib::StatisticalPhysicalDiskInstance* di = *iter;
std::wcout << std::endl << di->DumpString();
}
*/
}
private:
// data for test case TestBug6755_PartialHPUXDiscovery - must live longer than funciotn live-time
struct pst_diskinfo m_diskInfo;
#endif
};
CPPUNIT_TEST_SUITE_REGISTRATION( SCXStatisticalPhysicalDiskTest );
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: IMultiplayerRichPresenceData
#include "GlobalNamespace/IMultiplayerRichPresenceData.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: String
class String;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: InMultiplayerRichPresenceData
// [TokenAttribute] Offset: FFFFFFFF
class InMultiplayerRichPresenceData : public ::Il2CppObject/*, public GlobalNamespace::IMultiplayerRichPresenceData*/ {
public:
// private System.String <apiName>k__BackingField
// Size: 0x8
// Offset: 0x10
::Il2CppString* apiName;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String <localizedDescription>k__BackingField
// Size: 0x8
// Offset: 0x18
::Il2CppString* localizedDescription;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String <multiplayerLobbyCode>k__BackingField
// Size: 0x8
// Offset: 0x20
::Il2CppString* multiplayerLobbyCode;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// Creating value type constructor for type: InMultiplayerRichPresenceData
InMultiplayerRichPresenceData(::Il2CppString* apiName_ = {}, ::Il2CppString* localizedDescription_ = {}, ::Il2CppString* multiplayerLobbyCode_ = {}) noexcept : apiName{apiName_}, localizedDescription{localizedDescription_}, multiplayerLobbyCode{multiplayerLobbyCode_} {}
// Creating interface conversion operator: operator GlobalNamespace::IMultiplayerRichPresenceData
operator GlobalNamespace::IMultiplayerRichPresenceData() noexcept {
return *reinterpret_cast<GlobalNamespace::IMultiplayerRichPresenceData*>(this);
}
// [LocalizationKeyAttribute] Offset: 0xEAFAE8
// static field const value: static private System.String kInMultiplayerLobbyRichPresenceLocalizationKey
static constexpr const char* kInMultiplayerLobbyRichPresenceLocalizationKey = "IN_MULTIPLAYER_LOBBY_PRESENCE";
// Get static field: static private System.String kInMultiplayerLobbyRichPresenceLocalizationKey
static ::Il2CppString* _get_kInMultiplayerLobbyRichPresenceLocalizationKey();
// Set static field: static private System.String kInMultiplayerLobbyRichPresenceLocalizationKey
static void _set_kInMultiplayerLobbyRichPresenceLocalizationKey(::Il2CppString* value);
// Get instance field: private System.String <apiName>k__BackingField
::Il2CppString* _get_$apiName$k__BackingField();
// Set instance field: private System.String <apiName>k__BackingField
void _set_$apiName$k__BackingField(::Il2CppString* value);
// Get instance field: private System.String <localizedDescription>k__BackingField
::Il2CppString* _get_$localizedDescription$k__BackingField();
// Set instance field: private System.String <localizedDescription>k__BackingField
void _set_$localizedDescription$k__BackingField(::Il2CppString* value);
// Get instance field: private System.String <multiplayerLobbyCode>k__BackingField
::Il2CppString* _get_$multiplayerLobbyCode$k__BackingField();
// Set instance field: private System.String <multiplayerLobbyCode>k__BackingField
void _set_$multiplayerLobbyCode$k__BackingField(::Il2CppString* value);
// public System.String get_apiName()
// Offset: 0x1F3EBBC
::Il2CppString* get_apiName();
// protected System.Void set_apiName(System.String value)
// Offset: 0x1F3EBC4
void set_apiName(::Il2CppString* value);
// public System.String get_localizedDescription()
// Offset: 0x1F3EBCC
::Il2CppString* get_localizedDescription();
// protected System.Void set_localizedDescription(System.String value)
// Offset: 0x1F3EBD4
void set_localizedDescription(::Il2CppString* value);
// public System.String get_multiplayerLobbyCode()
// Offset: 0x1F3EBDC
::Il2CppString* get_multiplayerLobbyCode();
// public System.Void set_multiplayerLobbyCode(System.String value)
// Offset: 0x1F3EBE4
void set_multiplayerLobbyCode(::Il2CppString* value);
// public System.Boolean get_isJoinable()
// Offset: 0x1F3EBEC
bool get_isJoinable();
// public System.Void .ctor(System.String multiplayerLobbyCode)
// Offset: 0x1F3EBFC
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static InMultiplayerRichPresenceData* New_ctor(::Il2CppString* multiplayerLobbyCode) {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::InMultiplayerRichPresenceData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<InMultiplayerRichPresenceData*, creationType>(multiplayerLobbyCode)));
}
}; // InMultiplayerRichPresenceData
#pragma pack(pop)
static check_size<sizeof(InMultiplayerRichPresenceData), 32 + sizeof(::Il2CppString*)> __GlobalNamespace_InMultiplayerRichPresenceDataSizeCheck;
static_assert(sizeof(InMultiplayerRichPresenceData) == 0x28);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::InMultiplayerRichPresenceData*, "", "InMultiplayerRichPresenceData");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::InMultiplayerRichPresenceData::get_apiName
// Il2CppName: get_apiName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::InMultiplayerRichPresenceData::*)()>(&GlobalNamespace::InMultiplayerRichPresenceData::get_apiName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::InMultiplayerRichPresenceData*), "get_apiName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::InMultiplayerRichPresenceData::set_apiName
// Il2CppName: set_apiName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::InMultiplayerRichPresenceData::*)(::Il2CppString*)>(&GlobalNamespace::InMultiplayerRichPresenceData::set_apiName)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::InMultiplayerRichPresenceData*), "set_apiName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::InMultiplayerRichPresenceData::get_localizedDescription
// Il2CppName: get_localizedDescription
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::InMultiplayerRichPresenceData::*)()>(&GlobalNamespace::InMultiplayerRichPresenceData::get_localizedDescription)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::InMultiplayerRichPresenceData*), "get_localizedDescription", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::InMultiplayerRichPresenceData::set_localizedDescription
// Il2CppName: set_localizedDescription
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::InMultiplayerRichPresenceData::*)(::Il2CppString*)>(&GlobalNamespace::InMultiplayerRichPresenceData::set_localizedDescription)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::InMultiplayerRichPresenceData*), "set_localizedDescription", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::InMultiplayerRichPresenceData::get_multiplayerLobbyCode
// Il2CppName: get_multiplayerLobbyCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::InMultiplayerRichPresenceData::*)()>(&GlobalNamespace::InMultiplayerRichPresenceData::get_multiplayerLobbyCode)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::InMultiplayerRichPresenceData*), "get_multiplayerLobbyCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::InMultiplayerRichPresenceData::set_multiplayerLobbyCode
// Il2CppName: set_multiplayerLobbyCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::InMultiplayerRichPresenceData::*)(::Il2CppString*)>(&GlobalNamespace::InMultiplayerRichPresenceData::set_multiplayerLobbyCode)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::InMultiplayerRichPresenceData*), "set_multiplayerLobbyCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::InMultiplayerRichPresenceData::get_isJoinable
// Il2CppName: get_isJoinable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::InMultiplayerRichPresenceData::*)()>(&GlobalNamespace::InMultiplayerRichPresenceData::get_isJoinable)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::InMultiplayerRichPresenceData*), "get_isJoinable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::InMultiplayerRichPresenceData::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
#ifndef SRC_MYLABEL
#define SRC_WYLABEL
#pragma execution_character_set("utf-8")
#include <QMouseEvent>
#include <QDebug>
#include <QPixmap>
#include <QString>
#include <QMessageBox>
#include <QResizeEvent>
#include <cmath>
#include <deque>
#include <algorithm>
#include <thread>
#include <chrono>
#include "mylabel.h"
static const double r_city = 10; //半径
MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
{
this->setScaledContents(true);
// this->setScaledContents(false);
// this->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
}
void MyLabel::setOriginPixmap()
{
if (!hasOriginPixmap())
origin_pixmap = *pixmap();
}
bool MyLabel::hasOriginPixmap()
{
return !origin_pixmap.isNull();
}
void MyLabel::mouseMoveEvent(QMouseEvent *ev)
{
mouse_x_ = ev->pos().x();
mouse_y_ = ev->pos().y();
int i = judge_mouse_pos();
if (i != -1)
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
setToolTip(QString::fromStdString(idmap->getCityStr(i)));
}
else
{
setToolTip(nullptr);
}
}
void MyLabel::mousePressEvent(QMouseEvent *ev)
{
//qDebug() << ev->x() << ev->y();
if (ev->button() == Qt::LeftButton)
{
//qDebug() << mark_origin->height() << mark_origin->width();
//qDebug() << ev->x() << ev->y();
mouse_x_ = ev->x();
mouse_y_ = ev->y() + mark_origin->height() / 4;
int i = judge_mouse_pos();
if (i != -1 && has_mark_transfer[i])
{
has_mark_transfer[i] = false;
mark_transfer[i]->hide();
delete_transfer_city(i);
QString temp = "途经城市:";
for(auto city : transfer_city)
{
temp += QString::fromStdString(idmap->getCityStr(city)) + " ";
}
transfercityBrowser_->setText(temp);
}
}
else if (ev->button() == Qt::RightButton)
{
mouse_x_ = ev->x();
mouse_y_ = ev->y();
//QString temp;
int i = judge_mouse_pos();
//qDebug() << i;
//if(i!=-1)
//temp = QString::fromStdString(idmap->getCityStr(i));
//qDebug() << temp;
if (i != -1 && where_mark_destination != i && where_mark_origin != i && !has_mark_transfer[i])
{
current_set_city = i;
rightbutton_menu->popup(ev->globalPos());
}
}
}
void MyLabel::origin_action_triggered()
{
double x = mouse_x_, y = mouse_y_;
double city_x = city_pos_[current_set_city].first, city_y = city_pos_[current_set_city].second;
double w_ratio = static_cast<double>(current_qsize_.width()) / static_cast<double>(origin_qsize_.width());
double h_ratio = static_cast<double>(current_qsize_.height()) / static_cast<double>(origin_qsize_.height());
city_x *= w_ratio;
city_y *= h_ratio;
mark_origin->move(city_x - 33, city_y - 55);
rect_mark_origin = mark_origin->geometry();
rect_mark_origin.moveTo(rect_mark_origin.x() + 33, rect_mark_origin.y() + 55);
mark_origin->show();
where_mark_origin = current_set_city;
citylabel1_->setText(QString::fromStdString(idmap->getCityStr(current_set_city)));
}
void MyLabel::destination_action_triggered()
{
double x = mouse_x_, y = mouse_y_;
double city_x = city_pos_[current_set_city].first, city_y = city_pos_[current_set_city].second;
double w_ratio = static_cast<double>(current_qsize_.width()) / static_cast<double>(origin_qsize_.width());
double h_ratio = static_cast<double>(current_qsize_.height()) / static_cast<double>(origin_qsize_.height());
city_x *= w_ratio;
city_y *= h_ratio;
mark_destination->move(city_x - 33, city_y - 55);
rect_mark_destination = mark_destination->geometry();
rect_mark_destination.moveTo(rect_mark_destination.x() + 33, rect_mark_destination.y() + 55);
mark_destination->show();
where_mark_destination = current_set_city;
citylabel2_->setText(QString::fromStdString(idmap->getCityStr(current_set_city)));
}
void MyLabel::transfer_action_triggered()
{
double x = mouse_x_, y = mouse_y_;
double city_x = city_pos_[current_set_city].first, city_y = city_pos_[current_set_city].second;
double w_ratio = static_cast<double>(current_qsize_.width()) / static_cast<double>(origin_qsize_.width());
double h_ratio = static_cast<double>(current_qsize_.height()) / static_cast<double>(origin_qsize_.height());
city_x *= w_ratio;
city_y *= h_ratio;
mark_transfer[current_set_city]->move(city_x - 33, city_y - 55);
rect_mark_transfer[current_set_city] = mark_transfer[current_set_city]->geometry();
rect_mark_transfer[current_set_city].moveTo(rect_mark_transfer[current_set_city].x() + 33, rect_mark_transfer[current_set_city].y() + 55);
mark_transfer[current_set_city]->show();
transfer_city.push_back(current_set_city);
has_mark_transfer[current_set_city] = true;
QString temp = "途经城市:";
for(auto city : transfer_city)
{
temp += QString::fromStdString(idmap->getCityStr(city)) + " ";
}
transfercityBrowser_->setText(temp);
/*for(auto city : transfer_city)
{
qDebug() << city;
}*/
}
void MyLabel::delete_transfer_city(int i)
{
for (auto iter = transfer_city.begin(); iter != transfer_city.end(); iter++)
{
if (i == *iter)
{
transfer_city.erase(iter);
/*for(auto city : transfer_city)
{
qDebug() << city;
}*/
return;
}
}
}
std::vector<int> MyLabel::get_plan()
{
std::vector<int> temp;
temp.push_back(where_mark_origin);
for (const auto &i : transfer_city)
// while(!transfer_city.empty())
{
temp.push_back(i);
// temp.push_back(transfer_city.front());
// transfer_city.pop_front();
}
temp.push_back(where_mark_destination);
return temp;
}
void MyLabel::initializMyLabel(IDMap *a, QLabel *label1, QLabel *label2, QTextBrowser *browser)
{
idmap = a;
citylabel1_ = label1;
citylabel2_ = label2;
transfercityBrowser_ = browser;
current_qsize_ = origin_qsize_ = this->size();
rightbutton_menu = new QMenu(this);
rightbutton_menu->setStyleSheet(
"\
QMenu {\
\
background-color:rgb(240,240,240);\
border: 1px solid rgb(0,0,0);\
}\
QMenu::item {\
color: rgb(0,0,0);\
background-color:rgb(240,240,240);\
}\
QMenu::item:selected { \
background-color:rgb(200,200,200);\
}\
");
QAction *add_origin = new QAction(rightbutton_menu);
QAction *add_destination = new QAction(rightbutton_menu);
QAction *add_transfer = new QAction(rightbutton_menu);
add_origin->setText("起点");
add_destination->setText("终点");
add_transfer->setText("途径点");
rightbutton_menu->addAction(add_origin);
rightbutton_menu->addAction(add_destination);
rightbutton_menu->addAction(add_transfer);
connect(add_origin, SIGNAL(triggered()), this, SLOT(origin_action_triggered()));
connect(add_destination, SIGNAL(triggered()), this, SLOT(destination_action_triggered()));
connect(add_transfer, SIGNAL(triggered()), this, SLOT(transfer_action_triggered()));
mark_origin = new QLabel(this);
mark_origin->setPixmap(QPixmap(":/image/6.png"));
mark_origin->setScaledContents(true);
mark_origin->resize(66, 66);
mark_origin->hide();
where_mark_origin = -1;
mark_destination = new QLabel(this);
mark_destination->setPixmap(QPixmap(":/image/2.png"));
mark_destination->setScaledContents(true);
mark_destination->resize(66, 66);
mark_destination->hide();
where_mark_destination = -1;
for (int i = 0; i < 31; i++)
{
mark_transfer[i] = new QLabel(this);
mark_transfer[i]->setPixmap(QPixmap(":/image/4.png"));
mark_transfer[i]->setScaledContents(true);
mark_transfer[i]->resize(66, 66);
mark_transfer[i]->hide();
has_mark_transfer[i] = false;
}
initialize_citymap_pos();
}
void MyLabel::UpdateColAndRowMap()
{
double current_width = current_qsize_.width();
double current_height = current_qsize_.height();
double origin_width = origin_qsize_.width();
double origin_height = origin_qsize_.height();
for (int i = 0; i < sizeof(origin_col_map_) / sizeof(double); i++)
col_map_[i] = origin_col_map_[i] * current_width / origin_width;
for (int i = 0; i < sizeof(origin_row_map_) / sizeof(double); i++)
row_map_[i] = origin_row_map_[i] * current_height / origin_height;
}
int MyLabel::judge_mouse_pos()
{
UpdateColAndRowMap();
if (mouse_x_ > col_map_[0])
{
if (mouse_x_ < col_map_[1])
{
if (mouse_y_ < row_map_[0])
{
if (in_city_range(6))
return 6;
}
else if (mouse_y_ > row_map_[2] && mouse_y_ < row_map_[3])
{
if (in_city_range(30))
return 30;
}
}
else if (mouse_x_ > col_map_[2] && mouse_x_ < col_map_[3])
{
if (mouse_y_ > row_map_[1] && mouse_y_ < row_map_[2])
{
if (in_city_range(25))
return 25;
if (in_city_range(7))
return 7;
}
else if (mouse_y_ > row_map_[2] && mouse_y_ < row_map_[3])
{
if (in_city_range(23))
return 23;
}
else if (mouse_y_ > row_map_[3] && mouse_y_ < row_map_[4])
{
if (in_city_range(24))
return 24;
}
}
else if (mouse_x_ > col_map_[3] && mouse_x_ < col_map_[4])
{
if (mouse_y_ > row_map_[0] && mouse_y_ < row_map_[1])
{
if (in_city_range(8))
return 8;
}
else if (mouse_y_ > row_map_[1] && mouse_y_ < row_map_[2])
{
if (in_city_range(10))
return 10;
}
else if (mouse_y_ > row_map_[2] && mouse_y_ < row_map_[3])
{
if (in_city_range(28))
return 28;
}
else if (mouse_y_ > row_map_[3] && mouse_y_ < row_map_[4])
{
if (in_city_range(20))
return 20;
}
else if (mouse_y_ > row_map_[4])
{
if (in_city_range(19))
return 19;
}
}
else if (mouse_x_ > col_map_[4] && mouse_x_ < col_map_[5])
{
if (mouse_y_ > row_map_[0] && mouse_y_ < row_map_[1])
{
if (in_city_range(5))
return 5;
if (in_city_range(9))
return 9;
if (in_city_range(1))
return 1;
if (in_city_range(29))
return 29;
if (in_city_range(26))
return 26;
}
else if (mouse_y_ > row_map_[1] && mouse_y_ < row_map_[2])
{
if (in_city_range(0))
return 0;
if (in_city_range(11))
return 11;
}
else if (mouse_y_ > row_map_[2] && mouse_y_ < row_map_[3])
{
if (in_city_range(12))
return 12;
if (in_city_range(22))
return 22;
if (in_city_range(21))
return 21;
if (in_city_range(17))
return 17;
}
else if (mouse_y_ > row_map_[4])
{
if (in_city_range(16))
return 16;
if (in_city_range(18))
return 18;
}
}
else if (mouse_x_ > col_map_[5] && mouse_x_ < col_map_[6])
{
if (mouse_y_ < row_map_[0])
{
if (in_city_range(3))
return 3;
if (in_city_range(4))
return 4;
if (in_city_range(2))
return 2;
}
else if (mouse_y_ > row_map_[2] && mouse_y_ < row_map_[3])
{
if (in_city_range(13))
return 13;
if (in_city_range(27))
return 27;
if (in_city_range(14))
return 14;
}
else if (mouse_y_ > row_map_[3] && mouse_y_ < row_map_[4])
{
if (in_city_range(15))
return 15;
}
}
}
// for (int i = 0; i < 31; i++)
// if (in_city_range(i))
// return i;
return -1;
}
void MyLabel::initialize_citymap_pos()
{
// 900 650图片下
city_pos_[0] = std::make_pair(674, 323); //济南
city_pos_[1] = std::make_pair(631, 291); //石家庄
city_pos_[2] = std::make_pair(768, 172); //长春
city_pos_[3] = std::make_pair(778, 135); //哈尔滨
city_pos_[4] = std::make_pair(749, 212); //沈阳
city_pos_[5] = std::make_pair(580, 249); //呼和浩特
city_pos_[6] = std::make_pair(234, 179); //乌鲁木齐
city_pos_[7] = std::make_pair(465, 340); //兰州
city_pos_[8] = std::make_pair(500, 294); //银川
city_pos_[9] = std::make_pair(597, 301); //太原
city_pos_[10] = std::make_pair(545, 368); //西安
city_pos_[11] = std::make_pair(625, 356); //郑州
city_pos_[12] = std::make_pair(686, 400); //合肥
city_pos_[13] = std::make_pair(718, 399); //南京
city_pos_[14] = std::make_pair(736, 423); //杭州
city_pos_[15] = std::make_pair(734, 499); //福州
city_pos_[16] = std::make_pair(632, 563); //广州
city_pos_[17] = std::make_pair(668, 459); //南昌
city_pos_[18] = std::make_pair(578, 624); //海口
city_pos_[19] = std::make_pair(541, 571); //南宁
city_pos_[20] = std::make_pair(510, 506); //贵阳
city_pos_[21] = std::make_pair(620, 471); //长沙
city_pos_[22] = std::make_pair(641, 430); //武汉
city_pos_[23] = std::make_pair(465, 433); //成都
city_pos_[24] = std::make_pair(440, 533); //昆明
city_pos_[25] = std::make_pair(430, 326); //西宁
city_pos_[26] = std::make_pair(672, 273); //天津
city_pos_[27] = std::make_pair(759, 407); //上海
city_pos_[28] = std::make_pair(505, 451); //重庆
city_pos_[29] = std::make_pair(657, 254); //北京
city_pos_[30] = std::make_pair(246, 435); //拉萨
// city_pos_[0][0] = 674;city_pos_[0][1] = 323; //济南
// city_pos_[1][0] = 631;city_pos_[1][1] = 291; //石家庄
// city_pos_[2][0] = 768;city_pos_[2][1] = 172; //长春
// city_pos_[3][0] = 778;city_pos_[3][1] = 135; //哈尔滨
// city_pos_[4][0] = 749;city_pos_[4][1] = 212; //沈阳
// city_pos_[5][0] = 580;city_pos_[5][1] = 249; //呼和浩特
// city_pos_[6][0] = 234;city_pos_[6][1] = 179; //乌鲁木齐
// city_pos_[7][0] = 465;city_pos_[7][1] = 340; //兰州
// city_pos_[8][0] = 500;city_pos_[8][1] = 294; //银川
// city_pos_[9][0] = 597;city_pos_[9][1] = 301; //太原
// city_pos_[10][0] = 545;city_pos_[10][1] = 368;//西安
// city_pos_[11][0] = 625;city_pos_[11][1] = 356;//郑州
// city_pos_[12][0] = 686;city_pos_[12][1] = 400;//合肥
// city_pos_[13][0] = 718;city_pos_[13][1] = 399;//南京
// city_pos_[14][0] = 736;city_pos_[14][1] = 423;//杭州
// city_pos_[15][0] = 734;city_pos_[15][1] = 499;//福州
// city_pos_[16][0] = 632;city_pos_[16][1] = 563;//广州
// city_pos_[17][0] = 668;city_pos_[17][1] = 459;//南昌
// city_pos_[18][0] = 578;city_pos_[18][1] = 624;//海口
// city_pos_[19][0] = 541;city_pos_[19][1] = 571;//南宁
// city_pos_[20][0] = 510;city_pos_[20][1] = 506;//贵阳
// city_pos_[21][0] = 620;city_pos_[21][1] = 471;//长沙
// city_pos_[22][0] = 641;city_pos_[22][1] = 430;//武汉
// city_pos_[23][0] = 465;city_pos_[23][1] = 433;//成都
// city_pos_[24][0] = 440;city_pos_[24][1] = 533;//昆明
// city_pos_[25][0] = 430;city_pos_[25][1] = 326;//西宁
// city_pos_[26][0] = 672;city_pos_[26][1] = 273;//天津
// city_pos_[27][0] = 759;city_pos_[27][1] = 407;//上海
// city_pos_[28][0] = 505;city_pos_[28][1] = 451;//重庆
// city_pos_[29][0] = 657;city_pos_[29][1] = 254;//北京
// city_pos_[30][0] = 246;city_pos_[30][1] = 435;//拉萨
origin_col_map_[0] = 218;
origin_col_map_[1] = 267;
origin_col_map_[2] = 414;
origin_col_map_[3] = 487;
origin_col_map_[4] = 559;
origin_col_map_[5] = 702;
origin_col_map_[6] = 799;
origin_row_map_[0] = 230;
origin_row_map_[1] = 310;
origin_row_map_[2] = 382;
origin_row_map_[3] = 485;
origin_row_map_[4] = 550;
}
bool MyLabel::in_city_range(int i)
{
// qDebug() << std::pow(mouse_x_ - city_pos_[i].first, 2) + std::pow(mouse_y_ - city_pos_[i].second, 2) - r_city * r_city << endl;
double x = mouse_x_, y = mouse_y_;
double city_x = city_pos_[i].first, city_y = city_pos_[i].second;
double w_ratio = static_cast<double>(current_qsize_.width()) / static_cast<double>(origin_qsize_.width());
double h_ratio = static_cast<double>(current_qsize_.height()) / static_cast<double>(origin_qsize_.height());
double r = r_city * std::min(w_ratio, h_ratio);
city_x *= w_ratio;
city_y *= h_ratio;
return std::pow(x - city_x, 2.0) + std::pow(y - city_y, 2.0) <= r * r;
// int x = ev->x();
// int y = ev->y();
// qDebug() << this->size() << endl
// << this->origin_pixmap.size() << endl;
}
void MyLabel::MoveWhenResize(int type, int index, QLabel *target, const QSize &before_size, const QSize &after_size)
{
struct Point
{
double x;
double y;
};
static Point s_diff{}, e_diff{}, t_diff[31]{};
Point *temp;
if (type == 0) // start
temp = &s_diff;
else if (type == 1) // end
temp = &e_diff;
else // transfer
temp = &t_diff[index];
QRectF icon_rect = target->geometry();
icon_rect.moveTo(icon_rect.x() + 33, icon_rect.y() + 55);
double x_ratio = static_cast<double>(icon_rect.x()) / static_cast<double>(before_size.width());
double y_ratio = static_cast<double>(icon_rect.y()) / static_cast<double>(before_size.height());
double after_x = (after_size.width() * x_ratio); // 消除浮点转化为整数时的累积误差(尚有偏差)
double after_y = (after_size.height() * y_ratio);
int diff_x = after_x;
int diff_y = after_y;
temp->x += after_x - diff_x;
temp->y += after_y - diff_y;
int adjust_x = static_cast<int>(temp->x);
int adjust_y = static_cast<int>(temp->y);
if (adjust_x)
temp->x -= adjust_x;
if (adjust_y)
temp->y -= adjust_y;
// qDebug() << temp->x << " " << temp->y << endl;
icon_rect.moveTo((after_size.width() * x_ratio) + adjust_x, (after_size.height() * y_ratio) + adjust_y);
icon_rect.moveTo(icon_rect.x() - 33, icon_rect.y() - 55);
target->setGeometry(icon_rect.x(), icon_rect.y(), icon_rect.width(), icon_rect.height());
}
void MyLabel::resizeEvent(QResizeEvent *ev)
{
current_qsize_ = ev->size();
// qDebug() << current_qsize_ << endl;
// qDebug() << mark_origin->geometry() << endl;
MoveWhenResize(0, 0, mark_origin, ev->oldSize(), ev->size());
MoveWhenResize(1, 0, mark_destination, ev->oldSize(), ev->size());
for (int i = 0; i < 31; i++)
{
if (has_mark_transfer[i])
MoveWhenResize(2, i, mark_transfer[i], ev->oldSize(), ev->size());
}
this->setPixmap(origin_pixmap.scaled(ev->size().width(),
ev->size().height(),
Qt::KeepAspectRatio,
Qt::FastTransformation));
}
#endif // SRC_MYLABEL
|
// Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "ResourceManager.h"
#include <Corrade/Containers/ArrayViewStl.h>
#include <Corrade/Containers/PointerStl.h>
#include <Corrade/PluginManager/Manager.h>
#include <Corrade/PluginManager/PluginMetadata.h>
#include <Corrade/Utility/Assert.h>
#include <Corrade/Utility/ConfigurationGroup.h>
#include <Corrade/Utility/Debug.h>
#include <Corrade/Utility/DebugStl.h>
#include <Corrade/Utility/Directory.h>
#include <Corrade/Utility/FormatStl.h>
#include <Corrade/Utility/String.h>
#include <Magnum/EigenIntegration/GeometryIntegration.h>
#include <Magnum/EigenIntegration/Integration.h>
#include <Magnum/GL/Context.h>
#include <Magnum/GL/Extensions.h>
#include <Magnum/ImageView.h>
#include <Magnum/Math/FunctionsBatch.h>
#include <Magnum/Math/Range.h>
#include <Magnum/Math/Tags.h>
#include <Magnum/MeshTools/Compile.h>
#include <Magnum/MeshTools/Interleave.h>
#include <Magnum/MeshTools/Reference.h>
#include <Magnum/PixelFormat.h>
#include <Magnum/SceneGraph/Object.h>
#include <Magnum/Trade/AbstractImporter.h>
#include <Magnum/Trade/ImageData.h>
#include <Magnum/Trade/MeshObjectData3D.h>
#include <Magnum/Trade/PbrMetallicRoughnessMaterialData.h>
#include <Magnum/Trade/PhongMaterialData.h>
#include <Magnum/Trade/SceneData.h>
#include <Magnum/Trade/TextureData.h>
#include <Magnum/VertexFormat.h>
#include <memory>
#include "esp/geo/geo.h"
#include "esp/gfx/GenericDrawable.h"
#include "esp/gfx/MaterialUtil.h"
#include "esp/gfx/PbrDrawable.h"
#include "esp/gfx/replay/Recorder.h"
#include "esp/io/URDFParser.h"
#include "esp/io/io.h"
#include "esp/io/json.h"
#include "esp/physics/PhysicsManager.h"
#include "esp/scene/SceneGraph.h"
#include "esp/nav/PathFinder.h"
#ifdef ESP_BUILD_WITH_BULLET
#include "esp/physics/bullet/BulletPhysicsManager.h"
#endif
#include "CollisionMeshData.h"
#include "GenericInstanceMeshData.h"
#include "GenericMeshData.h"
#include "MeshData.h"
#ifdef ESP_BUILD_PTEX_SUPPORT
#include "PTexMeshData.h"
#include "esp/gfx/PTexMeshDrawable.h"
#include "esp/gfx/PTexMeshShader.h"
#endif
namespace Cr = Corrade;
namespace Mn = Magnum;
namespace esp {
using metadata::attributes::AbstractObjectAttributes;
using metadata::attributes::CubePrimitiveAttributes;
using metadata::attributes::ObjectAttributes;
using metadata::attributes::PhysicsManagerAttributes;
using metadata::attributes::StageAttributes;
using metadata::managers::AssetAttributesManager;
using metadata::managers::ObjectAttributesManager;
using metadata::managers::PhysicsAttributesManager;
using metadata::managers::StageAttributesManager;
namespace assets {
ResourceManager::ResourceManager(
metadata::MetadataMediator::ptr& _metadataMediator,
Flags _flags)
: flags_(_flags),
metadataMediator_(_metadataMediator)
#ifdef MAGNUM_BUILD_STATIC
,
// avoid using plugins that might depend on different library versions
importerManager_("nonexistent")
#endif
{
#ifdef ESP_BUILD_WITH_VHACD
// Destructor is protected, using Clean() and Release() to destruct interface
// (this is how it is used VHACD examples.)
interfaceVHACD = VHACD::CreateVHACD();
#endif
initDefaultLightSetups();
initDefaultMaterials();
buildImporters();
}
ResourceManager::~ResourceManager() {
#ifdef ESP_BUILD_WITH_VHACD
interfaceVHACD->Clean();
interfaceVHACD->Release();
#endif
}
void ResourceManager::buildImporters() {
// instantiate a primitive importer
CORRADE_INTERNAL_ASSERT_OUTPUT(
primitiveImporter_ =
importerManager_.loadAndInstantiate("PrimitiveImporter"));
// necessary for importer to be usable
primitiveImporter_->openData("");
// instantiate importer for file load
CORRADE_INTERNAL_ASSERT_OUTPUT(
fileImporter_ = importerManager_.loadAndInstantiate("AnySceneImporter"));
} // buildImporters
void ResourceManager::initDefaultPrimAttributes() {
// by this point, we should have a GL::Context so load the bb primitive.
// TODO: replace this completely with standard mesh (i.e. treat the bb
// wireframe cube no differently than other primivite-based rendered
// objects)
auto cubeMeshName =
getAssetAttributesManager()
->getObjectCopyByHandle<CubePrimitiveAttributes>("cubeWireframe")
->getPrimObjClassName();
auto wfCube = primitiveImporter_->mesh(cubeMeshName);
primitive_meshes_[nextPrimitiveMeshId++] =
std::make_unique<Magnum::GL::Mesh>(Magnum::MeshTools::compile(*wfCube));
} // initDefaultPrimAttributes
void ResourceManager::initPhysicsManager(
std::shared_ptr<physics::PhysicsManager>& physicsManager,
bool isEnabled,
scene::SceneNode* parent,
const metadata::attributes::PhysicsManagerAttributes::ptr&
physicsManagerAttributes) {
//! PHYSICS INIT: Use the passed attributes to initialize physics engine
bool defaultToNoneSimulator = true;
if (isEnabled) {
if (physicsManagerAttributes->getSimulator() == "bullet") {
#ifdef ESP_BUILD_WITH_BULLET
physicsManager = std::make_shared<physics::BulletPhysicsManager>(
*this, physicsManagerAttributes);
defaultToNoneSimulator = false;
#else
LOG(WARNING)
<< ":\n---\nPhysics was enabled and Bullet physics engine was "
"specified, but the project is built without Bullet support. "
"Objects added to the scene will be restricted to kinematic "
"updates "
"only. Reinstall with --bullet to enable Bullet dynamics.\n---";
#endif
}
}
// reset to base PhysicsManager to override previous as default behavior
// if the desired simulator is not supported reset to "none" in metaData
if (defaultToNoneSimulator) {
physicsManagerAttributes->setSimulator("none");
physicsManager = std::make_shared<physics::PhysicsManager>(
*this, physicsManagerAttributes);
}
// build default primitive asset templates, and default primitive object
// templates
initDefaultPrimAttributes();
// initialize the physics simulator
physicsManager->initPhysics(parent);
} // ResourceManager::initPhysicsManager
bool ResourceManager::loadStage(
StageAttributes::ptr& stageAttributes,
const std::shared_ptr<physics::PhysicsManager>& _physicsManager,
esp::scene::SceneManager* sceneManagerPtr,
std::vector<int>& activeSceneIDs,
bool createSemanticMesh,
bool forceSeparateSemanticSceneGraph) {
// create AssetInfos here for each potential mesh file for the scene, if they
// are unique.
bool buildCollisionMesh =
((_physicsManager != nullptr) &&
(_physicsManager->getInitializationAttributes()->getSimulator() !=
"none"));
const std::string renderLightSetupKey(stageAttributes->getLightSetup());
std::map<std::string, AssetInfo> assetInfoMap =
createStageAssetInfosFromAttributes(stageAttributes, buildCollisionMesh,
createSemanticMesh);
// set equal to current Simulator::activeSemanticSceneID_ value
int activeSemanticSceneID = activeSceneIDs[0];
// if semantic scene load is requested and possible
if (assetInfoMap.count("semantic") != 0u) {
// check if file names exist
AssetInfo semanticInfo = assetInfoMap.at("semantic");
auto semanticStageFilename = semanticInfo.filepath;
if (Cr::Utility::Directory::exists(semanticStageFilename)) {
LOG(INFO) << "::loadStage : Loading Semantic Stage mesh : "
<< semanticStageFilename;
activeSemanticSceneID = sceneManagerPtr->initSceneGraph();
auto& semanticSceneGraph =
sceneManagerPtr->getSceneGraph(activeSemanticSceneID);
auto& semanticRootNode = semanticSceneGraph.getRootNode();
auto& semanticDrawables = semanticSceneGraph.getDrawables();
RenderAssetInstanceCreationInfo::Flags flags;
flags |= RenderAssetInstanceCreationInfo::Flag::IsSemantic;
if (stageAttributes->getFrustumCulling()) {
// only treat as static if doing culling
flags |= RenderAssetInstanceCreationInfo::Flag::IsStatic;
}
RenderAssetInstanceCreationInfo creation(
semanticStageFilename, Cr::Containers::NullOpt, flags, NO_LIGHT_KEY);
bool semanticStageSuccess =
loadStageInternal(semanticInfo, // AssetInfo
&creation,
&semanticRootNode, // parent scene node
&semanticDrawables); // drawable group
// regardless of load failure, original code still changed
// activeSemanticSceneID_
if (!semanticStageSuccess) {
LOG(ERROR) << "::loadStage : Semantic Stage mesh "
"load failed.";
return false;
} else {
LOG(INFO) << "::loadStage : Semantic Stage mesh : "
<< semanticStageFilename << " loaded.";
}
} else { // semantic file name does not exist but house does
LOG(WARNING) << "::loadStage : Not loading semantic mesh - "
"File Name : "
<< semanticStageFilename << " does not exist.";
}
} else { // not wanting to create semantic mesh
LOG(INFO) << "::loadStage : Not loading semantic mesh";
}
if (forceSeparateSemanticSceneGraph &&
activeSemanticSceneID == activeSceneIDs[0]) {
// Create a separate semantic scene graph if it wasn't already created
// above.
activeSemanticSceneID = sceneManagerPtr->initSceneGraph();
}
// save active semantic scene ID so that simulator can consume
activeSceneIDs[1] = activeSemanticSceneID;
const bool isSeparateSemanticScene = activeSceneIDs[1] != activeSceneIDs[0];
auto& sceneGraph = sceneManagerPtr->getSceneGraph(activeSceneIDs[0]);
auto& rootNode = sceneGraph.getRootNode();
auto& drawables = sceneGraph.getDrawables();
AssetInfo renderInfo = assetInfoMap.at("render");
RenderAssetInstanceCreationInfo::Flags flags;
flags |= RenderAssetInstanceCreationInfo::Flag::IsStatic;
flags |= RenderAssetInstanceCreationInfo::Flag::IsRGBD;
if (!isSeparateSemanticScene) {
flags |= RenderAssetInstanceCreationInfo::Flag::IsSemantic;
}
RenderAssetInstanceCreationInfo renderCreation(
renderInfo.filepath, Cr::Containers::NullOpt, flags, renderLightSetupKey);
LOG(INFO) << "::loadStage : start load render asset " << renderInfo.filepath
<< ".";
bool renderMeshSuccess = loadStageInternal(renderInfo, // AssetInfo
&renderCreation,
&rootNode, // parent scene node
&drawables); // drawable group
if (!renderMeshSuccess) {
LOG(ERROR)
<< " ResourceManager::loadStage : Stage render mesh load failed, "
"Aborting scene initialization.";
return false;
}
// declare mesh group variable
std::vector<CollisionMeshData> meshGroup;
AssetInfo& infoToUse = renderInfo;
if (assetInfoMap.count("collision") != 0u) {
AssetInfo colInfo = assetInfoMap.at("collision");
if (resourceDict_.count(colInfo.filepath) == 0) {
LOG(INFO) << "::loadStage : start load collision asset "
<< colInfo.filepath << ".";
// will not reload if already present
bool collisionMeshSuccess =
loadStageInternal(colInfo, // AssetInfo
nullptr, // creation
nullptr, // parent scene node
nullptr); // drawable group
if (!collisionMeshSuccess) {
LOG(ERROR) << " ResourceManager::loadStage : Stage collision mesh "
"load failed. Aborting scene initialization.";
return false;
}
}
// if we have a collision mesh, and it does not exist already as a
// collision object, add it
if (colInfo.filepath != EMPTY_SCENE) {
infoToUse = colInfo;
} // if not colInfo.filepath.compare(EMPTY_SCENE)
} // if collision mesh desired
// build the appropriate mesh groups, either for the collision mesh, or, if
// the collision mesh is empty scene
if ((_physicsManager != nullptr) && (infoToUse.filepath != EMPTY_SCENE)) {
bool success = buildMeshGroups(infoToUse, meshGroup);
if (!success) {
return false;
}
//! Add to physics manager - will only be null for certain tests
// Either add with pre-built meshGroup if collision assets are loaded
// or empty vector for mesh group - this should only be the case if
// we are using None-type physicsManager.
bool sceneSuccess = _physicsManager->addStage(stageAttributes, meshGroup);
if (!sceneSuccess) {
LOG(ERROR) << "::loadStage : Adding Stage "
<< stageAttributes->getHandle()
<< " to PhysicsManager failed. Aborting scene initialization.";
return false;
}
}
return true;
} // ResourceManager::loadScene
bool ResourceManager::buildMeshGroups(
const AssetInfo& info,
std::vector<CollisionMeshData>& meshGroup) {
if (collisionMeshGroups_.count(info.filepath) == 0) {
//! Collect collision mesh group
bool colMeshGroupSuccess = false;
if (info.type == AssetType::INSTANCE_MESH) {
// PLY Instance mesh
colMeshGroupSuccess =
buildStageCollisionMeshGroup<GenericInstanceMeshData>(info.filepath,
meshGroup);
} else if (info.type == AssetType::MP3D_MESH ||
info.type == AssetType::UNKNOWN) {
// GLB Mesh
colMeshGroupSuccess = buildStageCollisionMeshGroup<GenericMeshData>(
info.filepath, meshGroup);
}
#ifdef ESP_BUILD_PTEX_SUPPORT
else if (info.type == AssetType::FRL_PTEX_MESH) {
colMeshGroupSuccess =
buildStageCollisionMeshGroup<PTexMeshData>(info.filepath, meshGroup);
}
#endif
// failure during build of collision mesh group
if (!colMeshGroupSuccess) {
LOG(ERROR) << "::loadStage : Stage " << info.filepath
<< " Collision mesh load failed. Aborting scene "
"initialization.";
return false;
}
//! Add scene meshgroup to collision mesh groups
collisionMeshGroups_.emplace(info.filepath, meshGroup);
} else {
// collision meshGroup already exists from prior load
meshGroup = collisionMeshGroups_.at(info.filepath);
}
return true;
} // ResourceManager::buildMeshGroups
std::map<std::string, AssetInfo>
ResourceManager::createStageAssetInfosFromAttributes(
const StageAttributes::ptr& stageAttributes,
bool createCollisionInfo,
bool createSemanticInfo) {
std::map<std::string, AssetInfo> resMap;
auto frame =
buildFrameFromAttributes(stageAttributes, stageAttributes->getOrigin());
float virtualUnitToMeters = stageAttributes->getUnitsToMeters();
// create render asset info
auto renderType =
static_cast<AssetType>(stageAttributes->getRenderAssetType());
AssetInfo renderInfo{
renderType, // type
stageAttributes->getRenderAssetHandle(), // file path
frame, // frame
virtualUnitToMeters, // virtualUnitToMeters
stageAttributes->getRequiresLighting() // requiresLighting
};
resMap["render"] = renderInfo;
if (createCollisionInfo) {
// create collision asset info if requested
auto colType =
static_cast<AssetType>(stageAttributes->getCollisionAssetType());
AssetInfo collisionInfo{
colType, // type
stageAttributes->getCollisionAssetHandle(), // file path
frame, // frame
virtualUnitToMeters, // virtualUnitToMeters
false // requiresLighting
};
resMap["collision"] = collisionInfo;
}
if (createSemanticInfo) {
// create semantic asset info if requested
auto semanticType =
static_cast<AssetType>(stageAttributes->getSemanticAssetType());
AssetInfo semanticInfo{
semanticType, // type
stageAttributes->getSemanticAssetHandle(), // file path
frame, // frame
virtualUnitToMeters, // virtualUnitToMeters
false, // requiresLighting
// only split instance mesh if doing frustum culling
stageAttributes->getFrustumCulling() // splitInstanceMesh
};
resMap["semantic"] = semanticInfo;
}
return resMap;
} // ResourceManager::createStageAssetInfosFromAttributes
esp::geo::CoordinateFrame ResourceManager::buildFrameFromAttributes(
const AbstractObjectAttributes::ptr& attribs,
const Magnum::Vector3& origin) {
const vec3f upEigen{
Mn::EigenIntegration::cast<vec3f>(attribs->getOrientUp())};
const vec3f frontEigen{
Mn::EigenIntegration::cast<vec3f>(attribs->getOrientFront())};
if (upEigen.isOrthogonal(frontEigen)) {
const vec3f originEigen{Mn::EigenIntegration::cast<vec3f>(origin)};
esp::geo::CoordinateFrame frame{upEigen, frontEigen, originEigen};
return frame;
} else {
LOG(INFO) << "::buildFrameFromAttributes : Specified frame "
"in Attributes : "
<< attribs->getHandle()
<< " is not orthogonal, so returning default frame.";
esp::geo::CoordinateFrame frame;
return frame;
}
} // ResourceManager::buildCoordFrameFromAttribVals
std::string ResourceManager::createColorMaterial(
const esp::assets::PhongMaterialColor& materialColor) {
std::ostringstream matHandleStream;
matHandleStream << "phong_amb_" << materialColor.ambientColor.toSrgbAlphaInt()
<< "_dif_" << materialColor.diffuseColor.toSrgbAlphaInt()
<< "_spec_" << materialColor.specularColor.toSrgbAlphaInt();
std::string newMaterialID = matHandleStream.str();
auto materialResource = shaderManager_.get<gfx::MaterialData>(newMaterialID);
if (materialResource.state() == Mn::ResourceState::NotLoadedFallback) {
gfx::PhongMaterialData::uptr phongMaterial =
gfx::PhongMaterialData::create_unique();
phongMaterial->ambientColor = materialColor.ambientColor;
phongMaterial->diffuseColor = materialColor.diffuseColor;
phongMaterial->specularColor = materialColor.specularColor;
std::unique_ptr<gfx::MaterialData> finalMaterial(phongMaterial.release());
shaderManager_.set(newMaterialID, finalMaterial.release());
}
return newMaterialID;
} // ResourceManager::createColorMaterial
scene::SceneNode* ResourceManager::loadAndCreateRenderAssetInstance(
const AssetInfo& assetInfo,
const RenderAssetInstanceCreationInfo& creation,
esp::scene::SceneManager* sceneManagerPtr,
const std::vector<int>& activeSceneIDs) {
// We map isStatic, isSemantic, and isRGBD to a scene graph.
int sceneID = -1;
if (!creation.isStatic()) {
// Non-static instances must always get added to the RGBD scene graph, with
// nodeType==OBJECT, and they will be drawn for both RGBD and Semantic
// sensors.
if (!(creation.isSemantic() && creation.isRGBD())) {
LOG(WARNING) << "unsupported instance creation flags for asset ["
<< assetInfo.filepath << "]";
return nullptr;
}
sceneID = activeSceneIDs[0];
} else {
if (creation.isSemantic() && creation.isRGBD()) {
if (activeSceneIDs[1] != activeSceneIDs[0]) {
// Because we have a separate semantic scene graph, we can't support a
// static instance with both isSemantic and isRGBD.
LOG(WARNING)
<< "unsupported instance creation flags for asset ["
<< assetInfo.filepath
<< "] with "
"SimulatorConfiguration::forceSeparateSemanticSceneGraph=true.";
return nullptr;
}
sceneID = activeSceneIDs[0];
} else {
if (activeSceneIDs[1] == activeSceneIDs[0]) {
// A separate semantic scene graph wasn't constructed, so we can't
// support a Semantic-only (or RGBD-only) instance.
LOG(WARNING)
<< "unsupported instance creation flags for asset ["
<< assetInfo.filepath
<< "] with "
"SimulatorConfiguration::forceSeparateSemanticSceneGraph=false.";
return nullptr;
}
sceneID = creation.isSemantic() ? activeSceneIDs[1] : activeSceneIDs[0];
}
}
auto& sceneGraph = sceneManagerPtr->getSceneGraph(sceneID);
auto& rootNode = sceneGraph.getRootNode();
auto& drawables = sceneGraph.getDrawables();
return loadAndCreateRenderAssetInstance(assetInfo, creation, &rootNode,
&drawables);
} // ResourceManager::loadAndCreateRenderAssetInstance
scene::SceneNode* ResourceManager::loadAndCreateRenderAssetInstance(
const AssetInfo& assetInfo,
const RenderAssetInstanceCreationInfo& creation,
scene::SceneNode* parent,
DrawableGroup* drawables,
std::vector<scene::SceneNode*>* visNodeCache) {
if (!loadRenderAsset(assetInfo)) {
return nullptr;
}
ASSERT(assetInfo.filepath == creation.filepath);
// copy the const creation info to modify the key if necessary
RenderAssetInstanceCreationInfo finalCreation(creation);
if (assetInfo.overridePhongMaterial != Cr::Containers::NullOpt) {
// material override is requested so get the id
finalCreation.filepath =
assetInfo.filepath + "?" +
createColorMaterial(*assetInfo.overridePhongMaterial);
}
return createRenderAssetInstance(finalCreation, parent, drawables,
visNodeCache);
}
bool ResourceManager::loadRenderAsset(const AssetInfo& info) {
bool registerMaterialOverride =
info.overridePhongMaterial != Cr::Containers::NullOpt;
bool fileAssetIsLoaded = resourceDict_.count(info.filepath) > 0;
bool meshSuccess = fileAssetIsLoaded;
// first load the file asset as-is if necessary
if (!fileAssetIsLoaded) {
// clone the AssetInfo and remove the custom material to load a default
// AssetInfo first
AssetInfo defaultInfo(info);
defaultInfo.overridePhongMaterial = Cr::Containers::NullOpt;
if (info.type == AssetType::PRIMITIVE) {
buildPrimitiveAssetData(info.filepath);
meshSuccess = true;
} else if (info.type == AssetType::FRL_PTEX_MESH) {
meshSuccess = loadRenderAssetPTex(defaultInfo);
} else if (info.type == AssetType::INSTANCE_MESH) {
meshSuccess = loadRenderAssetIMesh(defaultInfo);
} else if (isRenderAssetGeneral(info.type)) {
meshSuccess = loadRenderAssetGeneral(defaultInfo);
} else {
// loadRenderAsset doesn't yet support the requested asset type
CORRADE_INTERNAL_ASSERT_UNREACHABLE();
}
if (meshSuccess) {
// create and register the collisionMeshGroups
if (info.type != AssetType::PRIMITIVE) {
std::vector<CollisionMeshData> meshGroup;
CORRADE_ASSERT(buildMeshGroups(defaultInfo, meshGroup),
"Failed to construct collisionMeshGroups for asset "
<< info.filepath,
false);
}
if (gfxReplayRecorder_) {
gfxReplayRecorder_->onLoadRenderAsset(defaultInfo);
}
}
}
// now handle loading the material override AssetInfo if configured
if (meshSuccess && registerMaterialOverride) {
// register or get the override material id
std::string materialId = createColorMaterial(*info.overridePhongMaterial);
// construct the unique id for the material modified asset
std::string modifiedAssetName = info.filepath + "?" + materialId;
const bool matModAssetIsRegistered =
resourceDict_.count(modifiedAssetName) > 0;
if (!matModAssetIsRegistered) {
// first register the copied metaData
resourceDict_.emplace(modifiedAssetName,
LoadedAssetData(resourceDict_.at(info.filepath)));
// Replace the AssetInfo
resourceDict_.at(modifiedAssetName).assetInfo = info;
// Modify the MeshMetaData local material ids for all components
std::vector<MeshTransformNode*> nodeQueue;
nodeQueue.push_back(
&resourceDict_.at(modifiedAssetName).meshMetaData.root);
while (!nodeQueue.empty()) {
MeshTransformNode* node = nodeQueue.back();
nodeQueue.pop_back();
for (auto& child : node->children) {
nodeQueue.push_back(&child);
}
if (node->meshIDLocal != ID_UNDEFINED) {
node->materialID = materialId;
}
}
if (info.type != AssetType::PRIMITIVE) {
// clone the collision data
collisionMeshGroups_.emplace(modifiedAssetName,
collisionMeshGroups_.at(info.filepath));
}
if (gfxReplayRecorder_) {
gfxReplayRecorder_->onLoadRenderAsset(info);
}
}
}
return meshSuccess;
}
scene::SceneNode* ResourceManager::createRenderAssetInstance(
const RenderAssetInstanceCreationInfo& creation,
scene::SceneNode* parent,
DrawableGroup* drawables,
std::vector<scene::SceneNode*>* visNodeCache) {
CORRADE_ASSERT(resourceDict_.count(creation.filepath), "asset is not loaded",
nullptr);
const LoadedAssetData& loadedAssetData = resourceDict_.at(creation.filepath);
if (!isLightSetupCompatible(loadedAssetData, creation.lightSetupKey)) {
LOG(WARNING)
<< "Instantiating render asset " << creation.filepath
<< " with incompatible light setup, instance will not be correctly lit."
"For objects, please ensure 'requires lighting' is enabled in "
"object config file.";
}
const auto& info = loadedAssetData.assetInfo;
scene::SceneNode* newNode = nullptr;
if (info.type == AssetType::FRL_PTEX_MESH) {
CORRADE_ASSERT(!visNodeCache,
"createRenderAssetInstancePTex doesn't support this",
nullptr);
newNode = createRenderAssetInstancePTex(creation, parent, drawables);
} else if (info.type == AssetType::INSTANCE_MESH) {
CORRADE_ASSERT(!visNodeCache,
"createRenderAssetInstanceIMesh doesn't support this",
nullptr);
newNode = createRenderAssetInstanceIMesh(creation, parent, drawables);
} else if (isRenderAssetGeneral(info.type) ||
info.type == AssetType::PRIMITIVE) {
newNode = createRenderAssetInstanceGeneralPrimitive(
creation, parent, drawables, visNodeCache);
} else {
// createRenderAssetInstance doesn't yet support the requested asset type
CORRADE_INTERNAL_ASSERT_UNREACHABLE();
}
if (gfxReplayRecorder_ && newNode) {
gfxReplayRecorder_->onCreateRenderAssetInstance(newNode, creation);
}
return newNode;
} // ResourceManager::createRenderAssetInstance
bool ResourceManager::loadStageInternal(
const AssetInfo& info,
const RenderAssetInstanceCreationInfo* creation,
scene::SceneNode* parent,
DrawableGroup* drawables) {
// scene mesh loading
const std::string& filename = info.filepath;
LOG(INFO) << "::loadStageInternal : Attempting to load stage " << filename
<< " ";
bool meshSuccess = true;
if (info.filepath != EMPTY_SCENE) {
if (!Cr::Utility::Directory::exists(filename)) {
LOG(ERROR) << "::loadStageInternal : Cannot find scene file " << filename;
meshSuccess = false;
} else {
if (info.type == AssetType::SUNCG_SCENE) {
meshSuccess = loadSUNCGHouseFile(info, parent, drawables);
} else {
// load render asset if necessary
if (!loadRenderAsset(info)) {
return false;
} else {
if (resourceDict_[filename].assetInfo != info) {
// TODO: support color material modified assets by changing the
// "creation" filepath to the modified key
// Right now, we only allow for an asset to be loaded with one
// configuration, since generated mesh data may be invalid for a new
// configuration
LOG(ERROR)
<< "Reloading asset " << filename
<< " with different configuration not currently supported. "
<< "Asset may not be rendered correctly.";
}
}
// create render asset instance if requested
if (parent) {
CORRADE_INTERNAL_ASSERT(creation);
createRenderAssetInstance(*creation, parent, drawables);
}
return true;
}
}
} else {
LOG(INFO) << "::loadStageInternal : Loading empty scene for " << filename;
// EMPTY_SCENE (ie. "NONE") string indicates desire for an empty scene (no
// scene mesh): welcome to the void
}
return meshSuccess;
} // ResourceManager::loadStageInternal
template <class T>
bool ResourceManager::buildStageCollisionMeshGroup(
const std::string& filename,
std::vector<CollisionMeshData>& meshGroup) {
// TODO : refactor to manage any mesh groups, not just scene
//! Collect collision mesh group
const MeshMetaData& metaData = getMeshMetaData(filename);
auto indexPair = metaData.meshIndex;
int start = indexPair.first;
int end = indexPair.second;
for (int mesh_i = start; mesh_i <= end; ++mesh_i) {
T* rawMeshData = dynamic_cast<T*>(meshes_.at(mesh_i).get());
if (rawMeshData == nullptr) {
// means dynamic cast failed
Cr::Utility::Debug()
<< "::buildStageCollisionMeshGroup : "
"AssetInfo::AssetType "
"type error: unsupported mesh type, aborting. Try running "
"without \"--enable-physics\" and consider logging an issue.";
return false;
}
CollisionMeshData& colMeshData = rawMeshData->getCollisionMeshData();
meshGroup.push_back(colMeshData);
} // for each mesh
return true;
} // ResourceManager::buildStageCollisionMeshGroup
bool ResourceManager::loadObjectMeshDataFromFile(
const std::string& filename,
const metadata::attributes::ObjectAttributes::ptr& objectAttributes,
const std::string& meshType,
const bool requiresLighting) {
bool success = false;
if (!filename.empty()) {
AssetInfo meshInfo{AssetType::UNKNOWN, filename};
meshInfo.requiresLighting = requiresLighting;
meshInfo.frame = buildFrameFromAttributes(objectAttributes, {0, 0, 0});
success = loadRenderAsset(meshInfo);
if (!success) {
LOG(ERROR) << "Failed to load a physical object ("
<< objectAttributes->getHandle() << ")'s " << meshType
<< " mesh from file : " << filename;
}
}
return success;
} // loadObjectMeshDataFromFile
Magnum::Range3D ResourceManager::computeMeshBB(BaseMesh* meshDataGL) {
CollisionMeshData& meshData = meshDataGL->getCollisionMeshData();
return Mn::Math::minmax(meshData.positions);
}
#ifdef ESP_BUILD_PTEX_SUPPORT
void ResourceManager::computePTexMeshAbsoluteAABBs(
BaseMesh& baseMesh,
const std::vector<StaticDrawableInfo>& staticDrawableInfo) {
std::vector<Mn::Matrix4> absTransforms =
computeAbsoluteTransformations(staticDrawableInfo);
CORRADE_ASSERT(
absTransforms.size() == staticDrawableInfo.size(),
"::computePTexMeshAbsoluteAABBs: number of "
"transformations does not match number of drawables. Aborting.", );
// obtain the sub-meshes within the ptex mesh
PTexMeshData& ptexMeshData = dynamic_cast<PTexMeshData&>(baseMesh);
const std::vector<PTexMeshData::MeshData>& submeshes = ptexMeshData.meshes();
for (uint32_t iEntry = 0; iEntry < absTransforms.size(); ++iEntry) {
// convert std::vector<vec3f> to std::vector<Mn::Vector3>
const PTexMeshData::MeshData& submesh =
submeshes[staticDrawableInfo[iEntry].meshID];
std::vector<Mn::Vector3> pos{submesh.vbo.begin(), submesh.vbo.end()};
// transform the vertex positions to the world space
Mn::MeshTools::transformPointsInPlace(absTransforms[iEntry], pos);
scene::SceneNode& node = staticDrawableInfo[iEntry].node;
node.setAbsoluteAABB(Mn::Math::minmax(pos));
}
} // ResourceManager::computePTexMeshAbsoluteAABBs
#endif
void ResourceManager::computeGeneralMeshAbsoluteAABBs(
const std::vector<StaticDrawableInfo>& staticDrawableInfo) {
std::vector<Mn::Matrix4> absTransforms =
computeAbsoluteTransformations(staticDrawableInfo);
CORRADE_ASSERT(absTransforms.size() == staticDrawableInfo.size(),
"::computeGeneralMeshAbsoluteAABBs: number of "
"transforms does not match number of drawables.", );
for (uint32_t iEntry = 0; iEntry < absTransforms.size(); ++iEntry) {
const int meshID = staticDrawableInfo[iEntry].meshID;
Cr::Containers::Optional<Magnum::Trade::MeshData>& meshData =
meshes_.at(meshID)->getMeshData();
CORRADE_ASSERT(meshData,
"::computeGeneralMeshAbsoluteAABBs: The mesh "
"data specified at ID:"
<< meshID << "is empty/undefined. Aborting", );
// a vector to store the min, max pos for the aabb of every position array
std::vector<Mn::Vector3> bbPos;
// transform the vertex positions to the world space, compute the aabb for
// each position array
for (uint32_t jArray = 0;
jArray < meshData->attributeCount(Mn::Trade::MeshAttribute::Position);
++jArray) {
Cr::Containers::Array<Mn::Vector3> pos =
meshData->positions3DAsArray(jArray);
Mn::MeshTools::transformPointsInPlace(absTransforms[iEntry], pos);
std::pair<Mn::Vector3, Mn::Vector3> bb = Mn::Math::minmax(pos);
bbPos.push_back(bb.first);
bbPos.push_back(bb.second);
}
// locate the scene node which contains the current drawable
scene::SceneNode& node = staticDrawableInfo[iEntry].node;
// set the absolute axis aligned bounding box
node.setAbsoluteAABB(Mn::Math::minmax(bbPos));
} // iEntry
} // ResourceManager::computeGeneralMeshAbsoluteAABBs
void ResourceManager::computeInstanceMeshAbsoluteAABBs(
const std::vector<StaticDrawableInfo>& staticDrawableInfo) {
std::vector<Mn::Matrix4> absTransforms =
computeAbsoluteTransformations(staticDrawableInfo);
CORRADE_ASSERT(absTransforms.size() == staticDrawableInfo.size(),
"::computeInstancelMeshAbsoluteAABBs: Number of "
"transforms does not match number of drawables. Aborting.", );
for (size_t iEntry = 0; iEntry < absTransforms.size(); ++iEntry) {
const int meshID = staticDrawableInfo[iEntry].meshID;
// convert std::vector<vec3f> to std::vector<Mn::Vector3>
const std::vector<vec3f>& vertexPositions =
dynamic_cast<GenericInstanceMeshData&>(*meshes_.at(meshID))
.getVertexBufferObjectCPU();
std::vector<Mn::Vector3> transformedPositions{vertexPositions.begin(),
vertexPositions.end()};
Mn::MeshTools::transformPointsInPlace(absTransforms[iEntry],
transformedPositions);
scene::SceneNode& node = staticDrawableInfo[iEntry].node;
node.setAbsoluteAABB(Mn::Math::minmax(transformedPositions));
} // iEntry
}
std::vector<Mn::Matrix4> ResourceManager::computeAbsoluteTransformations(
const std::vector<StaticDrawableInfo>& staticDrawableInfo) {
// sanity check
if (staticDrawableInfo.size() == 0) {
return {};
}
// basic assumption is that all the drawables are in the same scene;
// so use the 1st element in the vector to obtain this scene
auto* scene = dynamic_cast<MagnumScene*>(staticDrawableInfo[0].node.scene());
CORRADE_ASSERT(scene != nullptr,
"::computeAbsoluteTransformations: The node is "
"not attached to any scene graph. Aborting.",
{});
// collect all drawable objects
std::vector<std::reference_wrapper<MagnumObject>> objects;
objects.reserve(staticDrawableInfo.size());
std::transform(staticDrawableInfo.begin(), staticDrawableInfo.end(),
std::back_inserter(objects),
[](const StaticDrawableInfo& info) -> MagnumObject& {
return info.node;
});
// compute transformations of all objects in the group relative to the root,
// which are the absolute transformations
std::vector<Mn::Matrix4> absTransforms =
scene->transformationMatrices(objects);
return absTransforms;
}
void ResourceManager::translateMesh(BaseMesh* meshDataGL,
Magnum::Vector3 translation) {
CollisionMeshData& meshData = meshDataGL->getCollisionMeshData();
Magnum::Matrix4 transform = Magnum::Matrix4::translation(translation);
Magnum::MeshTools::transformPointsInPlace(transform, meshData.positions);
// save the mesh transformation for future query
meshDataGL->meshTransform_ = transform * meshDataGL->meshTransform_;
meshDataGL->BB = meshDataGL->BB.translated(translation);
} // ResourceManager::translateMesh
void ResourceManager::buildPrimitiveAssetData(
const std::string& primTemplateHandle) {
// retrieves -actual- template, not a copy
esp::metadata::attributes::AbstractPrimitiveAttributes::ptr primTemplate =
getAssetAttributesManager()->getObjectByHandle(primTemplateHandle);
if (primTemplate == nullptr) {
// Template does not yet exist, create it using its name - primitive
// template names encode all the pertinent template settings and cannot be
// changed by the user, so the template name can be used to recreate the
// template itself.
auto newTemplate = getAssetAttributesManager()->createTemplateFromHandle(
primTemplateHandle);
// if still null, fail.
if (newTemplate == nullptr) {
LOG(ERROR)
<< "::buildPrimitiveAssetData : Attempting to reference or build a "
"primitive template from an unknown/malformed handle : "
<< primTemplateHandle << ". Aborting";
return;
}
// we do not want a copy of the newly created template, but the actual
// template
primTemplate = getAssetAttributesManager()->getObjectByHandle(
newTemplate->getHandle());
}
// check if unique name of attributes describing primitive asset is present
// already - don't remake if so
auto primAssetHandle = primTemplate->getHandle();
if (resourceDict_.count(primAssetHandle) > 0) {
LOG(INFO) << " Primitive Asset exists already : " << primAssetHandle;
return;
}
// class of primitive object
std::string primClassName = primTemplate->getPrimObjClassName();
// make sure it is open before use
primitiveImporter_->openData("");
// configuration for PrimitiveImporter - replace appropriate group's data
// before instancing prim object
Cr::Utility::ConfigurationGroup& conf = primitiveImporter_->configuration();
Cr::Utility::ConfigurationGroup* cfgGroup = conf.group(primClassName);
if (cfgGroup != nullptr) { // ignore prims with no configuration like cubes
auto newCfgGroup = primTemplate->getConfigGroup();
// replace current conf group with passed attributes
*cfgGroup = newCfgGroup;
}
// make assetInfo
AssetInfo info{AssetType::PRIMITIVE};
info.requiresLighting = true;
// set up primitive mesh
// make primitive mesh structure
auto primMeshData = std::make_unique<GenericMeshData>(false);
// build mesh data object
primMeshData->importAndSetMeshData(*primitiveImporter_, primClassName);
// compute the mesh bounding box
primMeshData->BB = computeMeshBB(primMeshData.get());
primMeshData->uploadBuffersToGPU(false);
// make MeshMetaData
int meshStart = nextMeshID_++;
int meshEnd = meshStart;
MeshMetaData meshMetaData{meshStart, meshEnd};
meshes_.emplace(meshStart, std::move(primMeshData));
// default material for now
std::unique_ptr<gfx::MaterialData> phongMaterial =
gfx::PhongMaterialData::create_unique();
shaderManager_.set(std::to_string(nextMaterialID_), phongMaterial.release());
meshMetaData.root.meshIDLocal = 0;
meshMetaData.root.componentID = 0;
meshMetaData.root.materialID = std::to_string(nextMaterialID_++);
// store the rotation to world frame upon load - currently superfluous
const quatf transform = info.frame.rotationFrameToWorld();
Magnum::Matrix4 R = Magnum::Matrix4::from(
Magnum::Quaternion(transform).toMatrix(), Magnum::Vector3());
meshMetaData.root.transformFromLocalToParent =
R * meshMetaData.root.transformFromLocalToParent;
// make LoadedAssetData corresponding to this asset
LoadedAssetData loadedAssetData{info, meshMetaData};
auto inserted =
resourceDict_.emplace(primAssetHandle, std::move(loadedAssetData));
LOG(INFO) << " Primitive Asset Added : ID : " << primTemplate->getID()
<< " : attr lib key : " << primTemplate->getHandle()
<< " | instance class : " << primClassName
<< " | Conf has group for this obj type : "
<< conf.hasGroup(primClassName);
} // ResourceManager::buildPrimitiveAssetData
bool ResourceManager::loadRenderAssetPTex(const AssetInfo& info) {
ASSERT(info.type == AssetType::FRL_PTEX_MESH);
#ifdef ESP_BUILD_PTEX_SUPPORT
// if this is a new file, load it and add it to the dictionary
const std::string& filename = info.filepath;
ASSERT(resourceDict_.count(filename) == 0);
const auto atlasDir = Cr::Utility::Directory::join(
Cr::Utility::Directory::path(filename), "textures");
int index = nextMeshID_++;
meshes_.emplace(index, std::make_unique<PTexMeshData>());
auto* pTexMeshData = dynamic_cast<PTexMeshData*>(meshes_.at(index).get());
pTexMeshData->load(filename, atlasDir);
// update the dictionary
auto inserted =
resourceDict_.emplace(filename, LoadedAssetData{info, {index, index}});
MeshMetaData& meshMetaData = inserted.first->second.meshMetaData;
meshMetaData.root.meshIDLocal = 0;
meshMetaData.root.componentID = 0;
// store the rotation to world frame upon load
const quatf transform = info.frame.rotationFrameToWorld();
Magnum::Matrix4 R = Magnum::Matrix4::from(
Magnum::Quaternion(transform).toMatrix(), Magnum::Vector3());
meshMetaData.root.transformFromLocalToParent =
R * meshMetaData.root.transformFromLocalToParent;
CORRADE_ASSERT(meshMetaData.meshIndex.first == meshMetaData.meshIndex.second,
"::loadRenderAssetPTex: ptex mesh is not loaded "
"correctly. Aborting.",
false);
return true;
#else
LOG(ERROR) << "PTex support not enabled. Enable the BUILD_PTEX_SUPPORT CMake "
"option when building.";
return false;
#endif
} // ResourceManager::loadRenderAssetPTex
scene::SceneNode* ResourceManager::createRenderAssetInstancePTex(
const RenderAssetInstanceCreationInfo& creation,
scene::SceneNode* parent,
DrawableGroup* drawables) {
#ifdef ESP_BUILD_PTEX_SUPPORT
ASSERT(!creation.scale); // PTex doesn't support scale
ASSERT(creation.lightSetupKey == NO_LIGHT_KEY); // PTex doesn't support
// lighting
const std::string& filename = creation.filepath;
const LoadedAssetData& loadedAssetData = resourceDict_.at(creation.filepath);
const MeshMetaData& metaData = getMeshMetaData(filename);
const auto& info = loadedAssetData.assetInfo;
auto indexPair = metaData.meshIndex;
int start = indexPair.first;
int end = indexPair.second;
std::vector<StaticDrawableInfo> staticDrawableInfo;
scene::SceneNode* instanceRoot = &parent->createChild();
for (int iMesh = start; iMesh <= end; ++iMesh) {
auto* pTexMeshData = dynamic_cast<PTexMeshData*>(meshes_.at(iMesh).get());
pTexMeshData->uploadBuffersToGPU(false);
for (int jSubmesh = 0; jSubmesh < pTexMeshData->getSize(); ++jSubmesh) {
scene::SceneNode& node = instanceRoot->createChild();
const quatf transform = info.frame.rotationFrameToWorld();
node.setRotation(Magnum::Quaternion(transform));
node.addFeature<gfx::PTexMeshDrawable>(*pTexMeshData, jSubmesh,
shaderManager_, drawables);
staticDrawableInfo.emplace_back(StaticDrawableInfo{node, jSubmesh});
}
}
// we assume a ptex mesh is only used as static
ASSERT(creation.isStatic());
ASSERT(metaData.meshIndex.first == metaData.meshIndex.second);
computePTexMeshAbsoluteAABBs(*meshes_.at(metaData.meshIndex.first),
staticDrawableInfo);
return instanceRoot;
#else
LOG(ERROR) << "PTex support not enabled. Enable the BUILD_PTEX_SUPPORT CMake "
"option when building.";
return nullptr;
#endif
} // ResourceManager::createRenderAssetInstancePTex
bool ResourceManager::loadRenderAssetIMesh(const AssetInfo& info) {
ASSERT(info.type == AssetType::INSTANCE_MESH);
const std::string& filename = info.filepath;
ASSERT(resourceDict_.count(filename) == 0);
Cr::Containers::Pointer<Importer> importer;
CORRADE_INTERNAL_ASSERT_OUTPUT(
importer = importerManager_.loadAndInstantiate("StanfordImporter"));
std::vector<GenericInstanceMeshData::uptr> instanceMeshes;
if (info.splitInstanceMesh) {
instanceMeshes =
GenericInstanceMeshData::fromPlySplitByObjectId(*importer, filename);
} else {
GenericInstanceMeshData::uptr meshData =
GenericInstanceMeshData::fromPLY(*importer, filename);
if (meshData)
instanceMeshes.emplace_back(std::move(meshData));
}
if (instanceMeshes.empty()) {
LOG(ERROR) << "Error loading instance mesh data";
return false;
}
int meshStart = nextMeshID_;
int meshEnd = meshStart + instanceMeshes.size() - 1;
nextMeshID_ = meshEnd + 1;
MeshMetaData meshMetaData{meshStart, meshEnd};
meshMetaData.root.children.resize(instanceMeshes.size());
for (int meshIDLocal = 0; meshIDLocal < instanceMeshes.size();
++meshIDLocal) {
instanceMeshes[meshIDLocal]->uploadBuffersToGPU(false);
meshes_.emplace(meshStart + meshIDLocal,
std::move(instanceMeshes[meshIDLocal]));
meshMetaData.root.children[meshIDLocal].meshIDLocal = meshIDLocal;
}
// update the dictionary
resourceDict_.emplace(filename,
LoadedAssetData{info, std::move(meshMetaData)});
return true;
} // ResourceManager::loadRenderAssetIMesh
scene::SceneNode* ResourceManager::createRenderAssetInstanceIMesh(
const RenderAssetInstanceCreationInfo& creation,
scene::SceneNode* parent,
DrawableGroup* drawables) {
ASSERT(!creation.scale); // IMesh doesn't support scale
ASSERT(creation.lightSetupKey == NO_LIGHT_KEY); // IMesh doesn't support
// lighting
const bool computeAbsoluteAABBs = creation.isStatic();
std::vector<StaticDrawableInfo> staticDrawableInfo;
auto indexPair = getMeshMetaData(creation.filepath).meshIndex;
int start = indexPair.first;
int end = indexPair.second;
scene::SceneNode* instanceRoot = &parent->createChild();
for (int iMesh = start; iMesh <= end; ++iMesh) {
scene::SceneNode& node = instanceRoot->createChild();
// Instance mesh does NOT have normal texture, so do not bother to
// query if the mesh data contain tangent or bitangent.
gfx::Drawable::Flags meshAttributeFlags{
gfx::Drawable::Flag::HasVertexColor};
// WARNING:
// This is to initiate drawables for instance mesh, and the instance mesh
// data is NOT stored in the meshData_ in the BaseMesh.
// That means One CANNOT query the data like e.g.,
// meshes_.at(iMesh)->getMeshData()->hasAttribute(Mn::Trade::MeshAttribute::Tangent)
// It will SEGFAULT!
createDrawable(*(meshes_.at(iMesh)->getMagnumGLMesh()), // render mesh
meshAttributeFlags, // mesh attribute flags
node, // scene node
creation.lightSetupKey, // lightSetup key
PER_VERTEX_OBJECT_ID_MATERIAL_KEY, // material key
drawables); // drawable group
if (computeAbsoluteAABBs) {
staticDrawableInfo.emplace_back(StaticDrawableInfo{node, iMesh});
}
}
if (computeAbsoluteAABBs) {
computeInstanceMeshAbsoluteAABBs(staticDrawableInfo);
}
return instanceRoot;
} // ResourceManager::createRenderAssetInstanceIMesh
bool ResourceManager::loadRenderAssetGeneral(const AssetInfo& info) {
ASSERT(isRenderAssetGeneral(info.type));
const std::string& filename = info.filepath;
const std::string dispFileName = Cr::Utility::Directory::filename(filename);
CHECK(resourceDict_.count(filename) == 0);
// Preferred plugins, Basis target GPU format
importerManager_.setPreferredPlugins("GltfImporter", {"TinyGltfImporter"});
#ifdef ESP_BUILD_ASSIMP_SUPPORT
importerManager_.setPreferredPlugins("ObjImporter", {"AssimpImporter"});
Cr::PluginManager::PluginMetadata* const assimpmetadata =
importerManager_.metadata("AssimpImporter");
assimpmetadata->configuration().setValue("ImportColladaIgnoreUpDirection",
"true");
#endif
{
Cr::PluginManager::PluginMetadata* const metadata =
importerManager_.metadata("BasisImporter");
Mn::GL::Context& context = Mn::GL::Context::current();
#ifdef MAGNUM_TARGET_WEBGL
if (context.isExtensionSupported<
Mn::GL::Extensions::WEBGL::compressed_texture_astc>())
#else
if (context.isExtensionSupported<
Mn::GL::Extensions::KHR::texture_compression_astc_ldr>())
#endif
{
LOG(INFO) << "Importing Basis files as ASTC 4x4 for " << dispFileName;
metadata->configuration().setValue("format", "Astc4x4RGBA");
}
#ifdef MAGNUM_TARGET_GLES
else if (context.isExtensionSupported<
Mn::GL::Extensions::EXT::texture_compression_bptc>())
#else
else if (context.isExtensionSupported<
Mn::GL::Extensions::ARB::texture_compression_bptc>())
#endif
{
LOG(INFO) << "Importing Basis files as BC7 for " << dispFileName;
metadata->configuration().setValue("format", "Bc7RGBA");
}
#ifdef MAGNUM_TARGET_WEBGL
else if (context.isExtensionSupported<
Mn::GL::Extensions::WEBGL::compressed_texture_s3tc>())
#elif defined(MAGNUM_TARGET_GLES)
else if (context.isExtensionSupported<
Mn::GL::Extensions::EXT::texture_compression_s3tc>() ||
context.isExtensionSupported<
Mn::GL::Extensions::ANGLE::texture_compression_dxt5>())
#else
else if (context.isExtensionSupported<
Mn::GL::Extensions::EXT::texture_compression_s3tc>())
#endif
{
LOG(INFO) << "Importing Basis files as BC3 for " << dispFileName;
metadata->configuration().setValue("format", "Bc3RGBA");
}
#ifndef MAGNUM_TARGET_GLES2
else
#ifndef MAGNUM_TARGET_GLES
if (context.isExtensionSupported<
Mn::GL::Extensions::ARB::ES3_compatibility>())
#endif
{
LOG(INFO) << "Importing Basis files as ETC2 for " << dispFileName;
metadata->configuration().setValue("format", "Etc2RGBA");
}
#else /* For ES2, fall back to PVRTC as ETC2 is not available */
else
#ifdef MAGNUM_TARGET_WEBGL
if (context.isExtensionSupported<Mn::WEBGL::compressed_texture_pvrtc>())
#else
if (context.isExtensionSupported<Mn::IMG::texture_compression_pvrtc>())
#endif
{
LOG(INFO) << "Importing Basis files as PVRTC 4bpp for " << dispFileName;
metadata->configuration().setValue("format", "PvrtcRGBA4bpp");
}
#endif
#if defined(MAGNUM_TARGET_GLES2) || !defined(MAGNUM_TARGET_GLES)
else /* ES3 has ETC2 always */
{
LOG(WARNING) << "No supported GPU compressed texture format detected, "
"Basis images will get imported as RGBA8 for "
<< dispFileName;
metadata->configuration().setValue("format", "RGBA8");
}
#endif
}
if (!fileImporter_->openFile(filename)) {
LOG(ERROR) << "Cannot open file " << filename;
return false;
}
// load file and add it to the dictionary
LoadedAssetData loadedAssetData{info};
if (requiresTextures_) {
loadTextures(*fileImporter_, loadedAssetData);
loadMaterials(*fileImporter_, loadedAssetData);
}
loadMeshes(*fileImporter_, loadedAssetData);
auto inserted = resourceDict_.emplace(filename, std::move(loadedAssetData));
MeshMetaData& meshMetaData = inserted.first->second.meshMetaData;
// Register magnum mesh
if (fileImporter_->defaultScene() != -1) {
Cr::Containers::Optional<Magnum::Trade::SceneData> sceneData =
fileImporter_->scene(fileImporter_->defaultScene());
if (!sceneData) {
LOG(ERROR) << "Cannot load scene, exiting";
return false;
}
for (unsigned int sceneDataID : sceneData->children3D()) {
loadMeshHierarchy(*fileImporter_, meshMetaData.root, sceneDataID);
}
} else if ((fileImporter_->meshCount() != 0u) &&
meshes_.at(meshMetaData.meshIndex.first)) {
// no default scene --- standalone OBJ/PLY files, for example
// take a wild guess and load the first mesh with the first material
// addMeshToDrawables(metaData, *parent, drawables, 0, 0);
loadMeshHierarchy(*fileImporter_, meshMetaData.root, 0);
} else {
LOG(ERROR) << "No default scene available and no meshes found, exiting";
return false;
}
const quatf transform = info.frame.rotationFrameToWorld();
Magnum::Matrix4 R = Magnum::Matrix4::from(
Magnum::Quaternion(transform).toMatrix(), Magnum::Vector3());
meshMetaData.root.transformFromLocalToParent =
R * meshMetaData.root.transformFromLocalToParent;
return true;
} // ResourceManager::loadRenderAssetGeneral
scene::SceneNode* ResourceManager::createRenderAssetInstanceGeneralPrimitive(
const RenderAssetInstanceCreationInfo& creation,
scene::SceneNode* parent,
DrawableGroup* drawables,
std::vector<scene::SceneNode*>* userVisNodeCache) {
ASSERT(parent);
ASSERT(drawables);
CHECK(resourceDict_.count(creation.filepath));
const LoadedAssetData& loadedAssetData = resourceDict_.at(creation.filepath);
std::vector<scene::SceneNode*> dummyVisNodeCache;
auto& visNodeCache = userVisNodeCache ? *userVisNodeCache : dummyVisNodeCache;
scene::SceneNode& newNode = parent->createChild();
if (creation.scale) {
// need a new node for scaling because motion state will override scale
// set at the physical node
// perf todo: avoid this if unit scale
newNode.setScaling(*creation.scale);
// legacy quirky behavior: only add this node to viscache if using scaling
visNodeCache.push_back(&newNode);
}
std::vector<StaticDrawableInfo> staticDrawableInfo;
auto nodeType = creation.isStatic() ? scene::SceneNodeType::EMPTY
: scene::SceneNodeType::OBJECT;
bool computeAbsoluteAABBs = creation.isStatic();
addComponent(loadedAssetData.meshMetaData, // mesh metadata
newNode, // parent scene node
creation.lightSetupKey, // lightSetup key
drawables, // drawable group
loadedAssetData.meshMetaData.root, // mesh transform node
visNodeCache, // a vector of scene nodes, the visNodeCache
computeAbsoluteAABBs, // compute absolute AABBs
staticDrawableInfo); // a vector of static drawable info
if (computeAbsoluteAABBs) {
// now compute aabbs by constructed staticDrawableInfo
computeGeneralMeshAbsoluteAABBs(staticDrawableInfo);
}
// set the node type for all cached visual nodes
if (nodeType != scene::SceneNodeType::EMPTY) {
for (auto* node : visNodeCache) {
node->setType(nodeType);
}
}
return &newNode;
} // ResourceManager::createRenderAssetInstanceGeneralPrimitive
bool ResourceManager::buildTrajectoryVisualization(
const std::string& trajVisName,
const std::vector<Mn::Vector3>& pts,
int numSegments,
float radius,
const Magnum::Color4& color,
bool smooth,
int numInterp) {
// enforce required minimum/reasonable values if illegal values specified
if (numSegments < 3) { // required by circle prim
numSegments = 3;
}
// clip to 10 points between trajectory points, if illegal value
if (smooth && (numInterp <= 0)) {
numInterp = 10;
}
// 1 millimeter radius minimum
if (radius <= 0) {
radius = .001;
}
LOG(INFO) << "::loadTrajectoryVisualization : Calling "
"trajectoryTubeSolid to build a tube named :"
<< trajVisName << " with " << pts.size()
<< " points, building a tube of radius :" << radius << " using "
<< numSegments << " circular segments and " << numInterp
<< " interpolated points between each trajectory point.";
// create mesh tube
Cr::Containers::Optional<Mn::Trade::MeshData> trajTubeMesh =
geo::buildTrajectoryTubeSolid(pts, numSegments, radius, smooth,
numInterp);
LOG(INFO) << "::loadTrajectoryVisualization : Successfully "
"returned from trajectoryTubeSolid ";
// make assetInfo
AssetInfo info{AssetType::PRIMITIVE};
info.requiresLighting = true;
// set up primitive mesh
// make primitive mesh structure
auto visMeshData = std::make_unique<GenericMeshData>(false);
visMeshData->setMeshData(*std::move(trajTubeMesh));
// compute the mesh bounding box
visMeshData->BB = computeMeshBB(visMeshData.get());
visMeshData->uploadBuffersToGPU(false);
// make MeshMetaData
int meshStart = meshes_.size();
int meshEnd = meshStart;
MeshMetaData meshMetaData{meshStart, meshEnd};
meshes_.emplace(meshStart, std::move(visMeshData));
// default material for now
auto phongMaterial = gfx::PhongMaterialData::create_unique();
phongMaterial->specularColor = {1.0, 1.0, 1.0, 1.0};
phongMaterial->ambientColor = color;
phongMaterial->diffuseColor = color;
shaderManager_.set(std::to_string(nextMaterialID_),
static_cast<gfx::MaterialData*>(phongMaterial.release()));
meshMetaData.root.meshIDLocal = 0;
meshMetaData.root.componentID = 0;
meshMetaData.root.materialID = std::to_string(nextMaterialID_++);
// store the rotation to world frame upon load - currently superfluous
const quatf transform = info.frame.rotationFrameToWorld();
Magnum::Matrix4 R = Magnum::Matrix4::from(
Magnum::Quaternion(transform).toMatrix(), Magnum::Vector3());
meshMetaData.root.transformFromLocalToParent =
R * meshMetaData.root.transformFromLocalToParent;
// make LoadedAssetData corresponding to this asset
LoadedAssetData loadedAssetData{info, meshMetaData};
// TODO : need to free render assets associated with this object if collision
// occurs, otherwise leak! (Currently unsupported).
// if (resourceDict_.count(trajVisName) != 0) {
// resourceDict_.erase(trajVisName);
// }
auto inserted =
resourceDict_.emplace(trajVisName, std::move(loadedAssetData));
return true;
} // ResourceManager::loadTrajectoryVisualization
int ResourceManager::loadNavMeshVisualization(esp::nav::PathFinder& pathFinder,
scene::SceneNode* parent,
DrawableGroup* drawables) {
int navMeshPrimitiveID = ID_UNDEFINED;
if (!pathFinder.isLoaded())
return navMeshPrimitiveID;
// create the mesh
std::vector<Magnum::UnsignedInt> indices;
std::vector<Magnum::Vector3> positions;
const MeshData::ptr navMeshData = pathFinder.getNavMeshData();
// add the vertices
positions.resize(navMeshData->vbo.size());
for (size_t vix = 0; vix < navMeshData->vbo.size(); vix++) {
positions[vix] = Magnum::Vector3{navMeshData->vbo[vix]};
}
indices.resize(navMeshData->ibo.size() * 2);
for (size_t ix = 0; ix < navMeshData->ibo.size();
ix += 3) { // for each triangle, create lines
size_t nix = ix * 2;
indices[nix] = navMeshData->ibo[ix];
indices[nix + 1] = navMeshData->ibo[ix + 1];
indices[nix + 2] = navMeshData->ibo[ix + 1];
indices[nix + 3] = navMeshData->ibo[ix + 2];
indices[nix + 4] = navMeshData->ibo[ix + 2];
indices[nix + 5] = navMeshData->ibo[ix];
}
// create a temporary mesh object referencing the above data
Mn::Trade::MeshData visualNavMesh{
Mn::MeshPrimitive::Lines,
{},
indices,
Mn::Trade::MeshIndexData{indices},
{},
positions,
{Mn::Trade::MeshAttributeData{Mn::Trade::MeshAttribute::Position,
Cr::Containers::arrayView(positions)}}};
// compile and add the new mesh to the structure
navMeshPrimitiveID = nextPrimitiveMeshId;
primitive_meshes_[nextPrimitiveMeshId++] = std::make_unique<Magnum::GL::Mesh>(
Magnum::MeshTools::compile(visualNavMesh));
if (parent != nullptr && drawables != nullptr &&
navMeshPrimitiveID != ID_UNDEFINED) {
// create the drawable
addPrimitiveToDrawables(navMeshPrimitiveID, *parent, drawables);
}
return navMeshPrimitiveID;
} // ResourceManager::loadNavMeshVisualization
void ResourceManager::loadMaterials(Importer& importer,
LoadedAssetData& loadedAssetData) {
for (int iMaterial = 0; iMaterial < importer.materialCount(); ++iMaterial) {
int currentMaterialID = nextMaterialID_++;
// TODO:
// it seems we have a way to just load the material once in this case,
// as long as the materialName includes the full path to the material
Cr::Containers::Optional<Mn::Trade::MaterialData> materialData =
importer.material(iMaterial);
if (!materialData) {
LOG(ERROR) << "Cannot load material, skipping";
continue;
}
std::unique_ptr<gfx::MaterialData> finalMaterial;
int textureBaseIndex = loadedAssetData.meshMetaData.textureIndex.first;
if (loadedAssetData.assetInfo.requiresLighting &&
materialData->types() &
Magnum::Trade::MaterialType::PbrMetallicRoughness) {
const auto& pbrMaterialData =
materialData->as<Mn::Trade::PbrMetallicRoughnessMaterialData>();
if (flags_ & Flag::BuildPhongFromPbr) {
finalMaterial = gfx::buildPhongFromPbrMetallicRoughness(
pbrMaterialData, textureBaseIndex, textures_);
} else {
finalMaterial =
buildPbrShadedMaterialData(pbrMaterialData, textureBaseIndex);
}
} else {
ASSERT(materialData);
if (!(materialData->types() & Magnum::Trade::MaterialType::Phong)) {
LOG(ERROR) << "Cannot load material, skipping";
continue;
}
const auto& phongMaterialData =
materialData->as<Mn::Trade::PhongMaterialData>();
if (loadedAssetData.assetInfo.requiresLighting) {
finalMaterial =
buildPhongShadedMaterialData(phongMaterialData, textureBaseIndex);
} else {
finalMaterial =
buildFlatShadedMaterialData(phongMaterialData, textureBaseIndex);
}
}
// for now, just use unique ID for material key. This may change if we
// expose materials to user for post-load modification
shaderManager_.set(std::to_string(currentMaterialID),
finalMaterial.release());
}
} // ResourceManager::loadMaterials
gfx::PhongMaterialData::uptr ResourceManager::buildFlatShadedMaterialData(
const Mn::Trade::PhongMaterialData& material,
int textureBaseIndex) {
// NOLINTNEXTLINE(google-build-using-namespace)
using namespace Mn::Math::Literals;
auto finalMaterial = gfx::PhongMaterialData::create_unique();
finalMaterial->ambientColor = 0xffffffff_rgbaf;
finalMaterial->diffuseColor = 0x00000000_rgbaf;
finalMaterial->specularColor = 0x00000000_rgbaf;
if (material.hasAttribute(Mn::Trade::MaterialAttribute::AmbientTexture)) {
finalMaterial->ambientTexture =
textures_.at(textureBaseIndex + material.ambientTexture()).get();
} else if (material.hasAttribute(
Mn::Trade::MaterialAttribute::DiffuseTexture)) {
// if we want to force flat shading, but we don't have ambient texture,
// check for diffuse texture and use that instead
finalMaterial->ambientTexture =
textures_.at(textureBaseIndex + material.diffuseTexture()).get();
}
if (material.hasAttribute(Mn::Trade::MaterialAttribute::DiffuseColor)) {
finalMaterial->ambientColor = material.diffuseColor();
} else if (material.hasAttribute(
Mn::Trade::MaterialAttribute::AmbientColor)) {
finalMaterial->ambientColor = material.ambientColor();
}
return finalMaterial;
}
gfx::PhongMaterialData::uptr ResourceManager::buildPhongShadedMaterialData(
const Mn::Trade::PhongMaterialData& material,
int textureBaseIndex) const {
// NOLINTNEXTLINE(google-build-using-namespace)
using namespace Mn::Math::Literals;
auto finalMaterial = gfx::PhongMaterialData::create_unique();
finalMaterial->shininess = material.shininess();
// texture transform, if there's none the matrix is an identity
finalMaterial->textureMatrix = material.commonTextureMatrix();
// ambient material properties
finalMaterial->ambientColor = material.ambientColor();
if (material.hasAttribute(Mn::Trade::MaterialAttribute::AmbientTexture)) {
finalMaterial->ambientTexture =
textures_.at(textureBaseIndex + material.ambientTexture()).get();
}
// diffuse material properties
finalMaterial->diffuseColor = material.diffuseColor();
if (material.hasAttribute(Mn::Trade::MaterialAttribute::DiffuseTexture)) {
finalMaterial->diffuseTexture =
textures_.at(textureBaseIndex + material.diffuseTexture()).get();
}
// specular material properties
finalMaterial->specularColor = material.specularColor();
if (material.hasSpecularTexture()) {
finalMaterial->specularTexture =
textures_.at(textureBaseIndex + material.specularTexture()).get();
}
// normal mapping
if (material.hasAttribute(Mn::Trade::MaterialAttribute::NormalTexture)) {
finalMaterial->normalTexture =
textures_.at(textureBaseIndex + material.normalTexture()).get();
}
return finalMaterial;
}
gfx::PbrMaterialData::uptr ResourceManager::buildPbrShadedMaterialData(
const Mn::Trade::PbrMetallicRoughnessMaterialData& material,
int textureBaseIndex) const {
// NOLINTNEXTLINE(google-build-using-namespace)
using namespace Mn::Math::Literals;
auto finalMaterial = gfx::PbrMaterialData::create_unique();
// texture transform, if there's none the matrix is an identity
finalMaterial->textureMatrix = material.commonTextureMatrix();
// base color (albedo)
finalMaterial->baseColor = material.baseColor();
if (material.hasAttribute(Mn::Trade::MaterialAttribute::BaseColorTexture)) {
finalMaterial->baseColorTexture =
textures_.at(textureBaseIndex + material.baseColorTexture()).get();
}
// normal map
if (material.hasAttribute(Mn::Trade::MaterialAttribute::NormalTexture)) {
// must be inside the if clause otherwise assertion fails if no normal
// texture is presented
finalMaterial->normalTextureScale = material.normalTextureScale();
finalMaterial->normalTexture =
textures_.at(textureBaseIndex + material.normalTexture()).get();
}
// emission
finalMaterial->emissiveColor = material.emissiveColor();
if (material.hasAttribute(Mn::Trade::MaterialAttribute::EmissiveTexture)) {
finalMaterial->emissiveTexture =
textures_.at(textureBaseIndex + material.emissiveTexture()).get();
if (!material.hasAttribute(Mn::Trade::MaterialAttribute::EmissiveColor)) {
finalMaterial->emissiveColor = Mn::Vector3{1.0f};
}
}
// roughness
finalMaterial->roughness = material.roughness();
if (material.hasRoughnessTexture()) {
finalMaterial->roughnessTexture =
textures_.at(textureBaseIndex + material.roughnessTexture()).get();
}
// metallic
finalMaterial->metallic = material.metalness();
if (material.hasMetalnessTexture()) {
finalMaterial->metallicTexture =
textures_.at(textureBaseIndex + material.metalnessTexture()).get();
}
// sanity check when both metallic and roughness materials are presented
if (material.hasMetalnessTexture() && material.hasRoughnessTexture()) {
/*
sanity check using hasNoneRoughnessMetallicTexture() to ensure that:
- both use the same texture coordinate attribute,
- both have the same texture transformation, and
- the metalness is in B and roughness is in G
It checks for a subset of hasOcclusionRoughnessMetallicTexture(),
so hasOcclusionRoughnessMetallicTexture() is not needed here.
The normal/roughness/metallic is a totally different packing (in BA
instead of GB), and it is NOT supported in the current version.
so hasNormalRoughnessMetallicTexture() is not needed here.
*/
CORRADE_ASSERT(
material.hasNoneRoughnessMetallicTexture(),
"::buildPbrShadedMaterialData(): if both the metallic "
"and roughness texture exist, they must be packed in the same texture "
"based on glTF 2.0 Spec.",
finalMaterial);
}
// TODO:
// Support NormalRoughnessMetallicTexture packing
CORRADE_ASSERT(!material.hasNormalRoughnessMetallicTexture(),
"::buildPbrShadedMaterialData(): "
"Sorry. NormalRoughnessMetallicTexture is not supported in "
"the current version. We will work on it.",
finalMaterial);
// double-sided
finalMaterial->doubleSided = material.isDoubleSided();
return finalMaterial;
}
void ResourceManager::loadMeshes(Importer& importer,
LoadedAssetData& loadedAssetData) {
int meshStart = nextMeshID_;
int meshEnd = meshStart + importer.meshCount() - 1;
nextMeshID_ = meshEnd + 1;
loadedAssetData.meshMetaData.setMeshIndices(meshStart, meshEnd);
for (int iMesh = 0; iMesh < importer.meshCount(); ++iMesh) {
// don't need normals if we aren't using lighting
auto gltfMeshData = std::make_unique<GenericMeshData>(
loadedAssetData.assetInfo.requiresLighting);
gltfMeshData->importAndSetMeshData(importer, iMesh);
// compute the mesh bounding box
gltfMeshData->BB = computeMeshBB(gltfMeshData.get());
gltfMeshData->uploadBuffersToGPU(false);
meshes_.emplace(meshStart + iMesh, std::move(gltfMeshData));
}
} // ResourceManager::loadMeshes
//! Recursively load the transformation chain specified by the mesh file
void ResourceManager::loadMeshHierarchy(Importer& importer,
MeshTransformNode& parent,
int componentID) {
std::unique_ptr<Magnum::Trade::ObjectData3D> objectData =
importer.object3D(componentID);
if (!objectData) {
LOG(ERROR) << "Cannot import object " << importer.object3DName(componentID)
<< ", skipping";
return;
}
// Add the new node to the hierarchy and set its transformation
parent.children.emplace_back();
parent.children.back().transformFromLocalToParent =
objectData->transformation();
parent.children.back().componentID = componentID;
const int meshIDLocal = objectData->instance();
// Add a mesh index
if (objectData->instanceType() == Magnum::Trade::ObjectInstanceType3D::Mesh &&
meshIDLocal != ID_UNDEFINED) {
parent.children.back().meshIDLocal = meshIDLocal;
if (requiresTextures_) {
auto* mod3D =
static_cast<Magnum::Trade::MeshObjectData3D*>(objectData.get());
if (mod3D->material() != ID_UNDEFINED) {
// we've already loaded the materials, so we can get the global index
// from the material count
parent.children.back().materialID = std::to_string(
mod3D->material() + nextMaterialID_ - importer.materialCount());
}
}
}
// Recursively add children
for (auto childObjectID : objectData->children()) {
loadMeshHierarchy(importer, parent.children.back(), childObjectID);
}
} // ResourceManager::loadMeshHierarchy
void ResourceManager::loadTextures(Importer& importer,
LoadedAssetData& loadedAssetData) {
int textureStart = nextTextureID_;
int textureEnd = textureStart + importer.textureCount() - 1;
nextTextureID_ = textureEnd + 1;
loadedAssetData.meshMetaData.setTextureIndices(textureStart, textureEnd);
for (int iTexture = 0; iTexture < importer.textureCount(); ++iTexture) {
auto currentTextureID = textureStart + iTexture;
textures_.emplace(currentTextureID,
std::make_shared<Magnum::GL::Texture2D>());
auto& currentTexture = textures_.at(currentTextureID);
auto textureData = importer.texture(iTexture);
if (!textureData ||
textureData->type() != Magnum::Trade::TextureData::Type::Texture2D) {
LOG(ERROR) << "Cannot load texture " << iTexture << " skipping";
currentTexture = nullptr;
continue;
}
// Configure the texture
Mn::GL::Texture2D& texture = *(textures_.at(textureStart + iTexture).get());
texture.setMagnificationFilter(textureData->magnificationFilter())
.setMinificationFilter(textureData->minificationFilter(),
textureData->mipmapFilter())
.setWrapping(textureData->wrapping().xy());
// Load all mip levels
const std::uint32_t levelCount =
importer.image2DLevelCount(textureData->image());
bool generateMipmap = false;
for (std::uint32_t level = 0; level != levelCount; ++level) {
// TODO:
// it seems we have a way to just load the image once in this case,
// as long as the image2DName include the full path to the image
Cr::Containers::Optional<Mn::Trade::ImageData2D> image =
importer.image2D(textureData->image(), level);
if (!image) {
LOG(ERROR) << "Cannot load texture image, skipping";
currentTexture = nullptr;
break;
}
Mn::GL::TextureFormat format;
if (image->isCompressed()) {
format = Mn::GL::textureFormat(image->compressedFormat());
} else {
format = Mn::GL::textureFormat(image->format());
}
// For the very first level, allocate the texture
if (level == 0) {
// If there is just one level and the image is not compressed, we'll
// generate mips ourselves
if (levelCount == 1 && !image->isCompressed()) {
texture.setStorage(Mn::Math::log2(image->size().max()) + 1, format,
image->size());
generateMipmap = true;
} else
texture.setStorage(levelCount, format, image->size());
}
if (image->isCompressed())
texture.setCompressedSubImage(level, {}, *image);
else
texture.setSubImage(level, {}, *image);
}
// Mip level loading failed, fail the whole texture
if (currentTexture == nullptr)
continue;
// Generate a mipmap if requested
if (generateMipmap)
texture.generateMipmap();
}
} // ResourceManager::loadTextures
bool ResourceManager::instantiateAssetsOnDemand(
const metadata::attributes::ObjectAttributes::ptr& objectAttributes) {
if (!objectAttributes) {
return false;
}
const std::string& objectTemplateHandle = objectAttributes->getHandle();
// if attributes are "dirty" (important values have changed since last
// registered) then re-register. Should never return ID_UNDEFINED - this
// would mean something has corrupted the library.
// NOTE : this is called when an new object is being made, but before the
// object has acquired a copy of its parent attributes. No object should
// ever have a copy of attributes with isDirty == true - any editing of
// attributes for objects requires object rebuilding.
if (objectAttributes->getIsDirty()) {
CORRADE_ASSERT(
(ID_UNDEFINED != getObjectAttributesManager()->registerObject(
objectAttributes, objectTemplateHandle)),
"::instantiateAssetsOnDemand : Unknown failure "
"attempting to register modified template :"
<< objectTemplateHandle
<< "before asset instantiation. Aborting. ",
false);
}
// get render asset handle
std::string renderAssetHandle = objectAttributes->getRenderAssetHandle();
// whether attributes requires lighting
bool requiresLighting = objectAttributes->getRequiresLighting();
bool renderMeshSuccess = false;
// no resource dict entry exists for renderAssetHandle
if (resourceDict_.count(renderAssetHandle) == 0) {
if (objectAttributes->getRenderAssetIsPrimitive()) {
// needs to have a primitive asset attributes with same name
if (!getAssetAttributesManager()->getObjectLibHasHandle(
renderAssetHandle)) {
// this is bad, means no render primitive template exists with
// expected name. should never happen
LOG(ERROR) << "No primitive asset attributes exists with name :"
<< renderAssetHandle
<< " so unable to instantiate primitive-based render "
"object. Aborting.";
return false;
}
// build primitive asset for this object based on defined primitive
// attributes
buildPrimitiveAssetData(renderAssetHandle);
} else {
// load/check_for render mesh metadata and load assets
renderMeshSuccess = loadObjectMeshDataFromFile(
renderAssetHandle, objectAttributes, "render", requiresLighting);
}
} // if no render asset exists
// check if uses collision mesh
// TODO : handle visualization-only objects lacking collision assets
// Probably just need to check attr->isCollidable()
if (!objectAttributes->getCollisionAssetIsPrimitive()) {
const auto collisionAssetHandle =
objectAttributes->getCollisionAssetHandle();
if (resourceDict_.count(collisionAssetHandle) == 0) {
bool collisionMeshSuccess = loadObjectMeshDataFromFile(
collisionAssetHandle, objectAttributes, "collision",
!renderMeshSuccess && requiresLighting);
if (!collisionMeshSuccess) {
return false;
}
}
// check if collision handle exists in collision mesh groups yet. if not
// then instance
if (collisionMeshGroups_.count(collisionAssetHandle) == 0) {
// set collision mesh data
const MeshMetaData& meshMetaData = getMeshMetaData(collisionAssetHandle);
int start = meshMetaData.meshIndex.first;
int end = meshMetaData.meshIndex.second;
//! Gather mesh components for meshGroup data
std::vector<CollisionMeshData> meshGroup;
for (int mesh_i = start; mesh_i <= end; ++mesh_i) {
GenericMeshData& gltfMeshData =
dynamic_cast<GenericMeshData&>(*meshes_.at(mesh_i).get());
CollisionMeshData& meshData = gltfMeshData.getCollisionMeshData();
meshGroup.push_back(meshData);
}
collisionMeshGroups_.emplace(collisionAssetHandle, meshGroup);
}
}
return true;
} // ResourceManager::instantiateAssetsOnDemand
void ResourceManager::addObjectToDrawables(
const ObjectAttributes::ptr& ObjectAttributes,
scene::SceneNode* parent,
DrawableGroup* drawables,
std::vector<scene::SceneNode*>& visNodeCache,
const std::string& lightSetupKey) {
if (parent != nullptr and drawables != nullptr) {
//! Add mesh to rendering stack
const std::string& renderObjectName =
ObjectAttributes->getRenderAssetHandle();
RenderAssetInstanceCreationInfo::Flags flags;
flags |= RenderAssetInstanceCreationInfo::Flag::IsRGBD;
flags |= RenderAssetInstanceCreationInfo::Flag::IsSemantic;
RenderAssetInstanceCreationInfo creation(
renderObjectName, ObjectAttributes->getScale(), flags, lightSetupKey);
createRenderAssetInstance(creation, parent, drawables, &visNodeCache);
} // should always be specified, otherwise won't do anything
} // addObjectToDrawables
//! Add component to rendering stack, based on importer loading
void ResourceManager::addComponent(
const MeshMetaData& metaData,
scene::SceneNode& parent,
const Mn::ResourceKey& lightSetupKey,
DrawableGroup* drawables,
const MeshTransformNode& meshTransformNode,
std::vector<scene::SceneNode*>& visNodeCache,
bool computeAbsoluteAABBs,
std::vector<StaticDrawableInfo>& staticDrawableInfo) {
// Add the object to the scene and set its transformation
scene::SceneNode& node = parent.createChild();
visNodeCache.push_back(&node);
node.MagnumObject::setTransformation(
meshTransformNode.transformFromLocalToParent);
const int meshIDLocal = meshTransformNode.meshIDLocal;
// Add a drawable if the object has a mesh and the mesh is loaded
if (meshIDLocal != ID_UNDEFINED) {
const int meshID = metaData.meshIndex.first + meshIDLocal;
Magnum::GL::Mesh& mesh = *meshes_.at(meshID)->getMagnumGLMesh();
Mn::ResourceKey materialKey = meshTransformNode.materialID;
gfx::Drawable::Flags meshAttributeFlags{};
const auto& meshData = meshes_.at(meshID)->getMeshData();
if (meshData != Cr::Containers::NullOpt) {
if (meshData->hasAttribute(Mn::Trade::MeshAttribute::Tangent)) {
meshAttributeFlags |= gfx::Drawable::Flag::HasTangent;
// if it has tangent, then check if it has bitangent
if (meshData->hasAttribute(Mn::Trade::MeshAttribute::Bitangent)) {
meshAttributeFlags |= gfx::Drawable::Flag::HasSeparateBitangent;
}
}
if (meshData->hasAttribute(Mn::Trade::MeshAttribute::Color)) {
meshAttributeFlags |= gfx::Drawable::Flag::HasVertexColor;
}
}
createDrawable(mesh, // render mesh
meshAttributeFlags, // mesh attribute flags
node, // scene node
lightSetupKey, // lightSetup Key
materialKey, // material key
drawables); // drawable group
// compute the bounding box for the mesh we are adding
if (computeAbsoluteAABBs) {
staticDrawableInfo.emplace_back(StaticDrawableInfo{node, meshID});
}
BaseMesh* meshBB = meshes_.at(meshID).get();
node.setMeshBB(computeMeshBB(meshBB));
}
// Recursively add children
for (const auto& child : meshTransformNode.children) {
addComponent(metaData, // mesh metadata
node, // parent scene node
lightSetupKey, // lightSetup key
drawables, // drawable group
child, // mesh transform node
visNodeCache, // a vector of scene nodes, the visNodeCache
computeAbsoluteAABBs, // compute absolute aabbs
staticDrawableInfo); // a vector of static drawable info
}
} // addComponent
void ResourceManager::addPrimitiveToDrawables(int primitiveID,
scene::SceneNode& node,
DrawableGroup* drawables) {
CHECK(primitive_meshes_.count(primitiveID));
// TODO:
// currently we assume the primitives does not have normal texture
// so do not need to worry about the tangent or bitangent.
// it might be changed in the future.
gfx::Drawable::Flags meshAttributeFlags{};
createDrawable(*primitive_meshes_.at(primitiveID), // render mesh
meshAttributeFlags, // meshAttributeFlags
node, // scene node
NO_LIGHT_KEY, // lightSetup key
WHITE_MATERIAL_KEY, // material key
drawables); // drawable group
}
void ResourceManager::removePrimitiveMesh(int primitiveID) {
CHECK(primitive_meshes_.count(primitiveID));
primitive_meshes_.erase(primitiveID);
}
void ResourceManager::createDrawable(Mn::GL::Mesh& mesh,
gfx::Drawable::Flags& meshAttributeFlags,
scene::SceneNode& node,
const Mn::ResourceKey& lightSetupKey,
const Mn::ResourceKey& materialKey,
DrawableGroup* group /* = nullptr */) {
const auto& materialDataType =
shaderManager_.get<gfx::MaterialData>(materialKey)->type;
switch (materialDataType) {
case gfx::MaterialDataType::None:
CORRADE_INTERNAL_ASSERT_UNREACHABLE();
break;
case gfx::MaterialDataType::Phong:
node.addFeature<gfx::GenericDrawable>(
mesh, // render mesh
meshAttributeFlags, // mesh attribute flags
shaderManager_, // shader manager
lightSetupKey, // lightSetup key
materialKey, // material key
group); // drawable group
break;
case gfx::MaterialDataType::Pbr:
node.addFeature<gfx::PbrDrawable>(
mesh, // render mesh
meshAttributeFlags, // mesh attribute flags
shaderManager_, // shader manager
lightSetupKey, // lightSetup key
materialKey, // material key
group); // drawable group
break;
}
} // ResourceManager::createDrawable
bool ResourceManager::loadSUNCGHouseFile(const AssetInfo& houseInfo,
scene::SceneNode* parent,
DrawableGroup* drawables) {
ASSERT(parent != nullptr);
LOG(WARNING) << "SUNCG support is deprecated. This codepath is untested.";
std::string houseFile = Cr::Utility::Directory::join(
Cr::Utility::Directory::current(), houseInfo.filepath);
const auto& json = io::parseJsonFile(houseFile);
const auto& levels = json["levels"].GetArray();
std::vector<std::string> pathTokens = io::tokenize(houseFile, "/", 0, true);
ASSERT(pathTokens.size() >= 3);
pathTokens.pop_back(); // house.json
const std::string houseId = pathTokens.back();
pathTokens.pop_back(); // <houseId>
pathTokens.pop_back(); // house
const std::string basePath = Cr::Utility::String::join(pathTokens, '/');
// store nodeIds to obtain linearized index for semantic masks
std::vector<std::string> nodeIds;
for (const auto& level : levels) {
const auto& nodes = level["nodes"].GetArray();
for (const auto& node : nodes) {
const std::string nodeId = node["id"].GetString();
const std::string nodeType = node["type"].GetString();
const int valid = node["valid"].GetInt();
if (valid == 0) {
continue;
}
// helper for creating object nodes
auto createObjectFunc = [&](const AssetInfo& info,
const std::string& id) -> scene::SceneNode& {
scene::SceneNode& objectNode = parent->createChild();
const int nodeIndex = nodeIds.size();
nodeIds.push_back(id);
objectNode.setId(nodeIndex);
if (info.type == AssetType::SUNCG_OBJECT) {
CHECK(loadRenderAsset(info));
RenderAssetInstanceCreationInfo::Flags flags;
flags |= RenderAssetInstanceCreationInfo::Flag::IsRGBD;
flags |= RenderAssetInstanceCreationInfo::Flag::IsSemantic;
RenderAssetInstanceCreationInfo objectCreation(
info.filepath, Cr::Containers::NullOpt, flags, NO_LIGHT_KEY);
createRenderAssetInstance(objectCreation, &objectNode, drawables);
}
return objectNode;
};
const std::string roomPath =
basePath + std::string("/room/").append(houseId).append("/");
if (nodeType == "Room") {
const std::string roomBase = roomPath + node["modelId"].GetString();
const int hideCeiling = node["hideCeiling"].GetInt();
const int hideFloor = node["hideFloor"].GetInt();
const int hideWalls = node["hideWalls"].GetInt();
if (hideCeiling != 1) {
createObjectFunc({AssetType::SUNCG_OBJECT, roomBase + "c.glb"},
nodeId + "c");
}
if (hideWalls != 1) {
createObjectFunc({AssetType::SUNCG_OBJECT, roomBase + "w.glb"},
nodeId + "w");
}
if (hideFloor != 1) {
createObjectFunc({AssetType::SUNCG_OBJECT, roomBase + "f.glb"},
nodeId + "f");
}
} else if (nodeType == "Object") {
const std::string modelId = node["modelId"].GetString();
// Parse model-to-scene transformation matrix
// NOTE: only "Object" nodes have transform, other nodes are directly
// specified in scene coordinates
std::vector<float> transformVec;
io::toFloatVector(node["transform"], &transformVec);
mat4f transform(transformVec.data());
const AssetInfo info{AssetType::SUNCG_OBJECT,
basePath + std::string("/object/")
.append(modelId)
.append("/")
.append(modelId)
.append(".glb")};
createObjectFunc(info, nodeId)
.setTransformation(Magnum::Matrix4{transform});
} else if (nodeType == "Box") {
// TODO(MS): create Box geometry
createObjectFunc({}, nodeId);
} else if (nodeType == "Ground") {
const std::string roomBase = roomPath + node["modelId"].GetString();
const AssetInfo info{AssetType::SUNCG_OBJECT, roomBase + "f.glb"};
createObjectFunc(info, nodeId);
} else {
LOG(ERROR) << "Unrecognized SUNCG house node type " << nodeType;
}
}
}
return true;
}
void ResourceManager::initDefaultLightSetups() {
shaderManager_.set(NO_LIGHT_KEY, gfx::LightSetup{});
shaderManager_.setFallback(gfx::LightSetup{});
}
void ResourceManager::initDefaultMaterials() {
shaderManager_.set<gfx::MaterialData>(DEFAULT_MATERIAL_KEY,
new gfx::PhongMaterialData{});
auto* whiteMaterialData = new gfx::PhongMaterialData;
whiteMaterialData->ambientColor = Magnum::Color4{1.0};
shaderManager_.set<gfx::MaterialData>(WHITE_MATERIAL_KEY, whiteMaterialData);
auto* perVertexObjectId = new gfx::PhongMaterialData{};
perVertexObjectId->perVertexObjectId = true;
perVertexObjectId->ambientColor = Mn::Color4{1.0};
shaderManager_.set<gfx::MaterialData>(PER_VERTEX_OBJECT_ID_MATERIAL_KEY,
perVertexObjectId);
shaderManager_.setFallback<gfx::MaterialData>(new gfx::PhongMaterialData{});
}
bool ResourceManager::isLightSetupCompatible(
const LoadedAssetData& loadedAssetData,
const Magnum::ResourceKey& lightSetupKey) const {
// if light setup has lights in it, but asset was loaded in as flat shaded,
// there may be an error when rendering.
return lightSetupKey == Mn::ResourceKey{NO_LIGHT_KEY} ||
loadedAssetData.assetInfo.requiresLighting;
}
//! recursively join all sub-components of a mesh into a single unified
//! MeshData.
void ResourceManager::joinHierarchy(
MeshData& mesh,
const MeshMetaData& metaData,
const MeshTransformNode& node,
const Magnum::Matrix4& transformFromParentToWorld) const {
Magnum::Matrix4 transformFromLocalToWorld =
transformFromParentToWorld * node.transformFromLocalToParent;
if (node.meshIDLocal != ID_UNDEFINED) {
CollisionMeshData& meshData =
meshes_.at(node.meshIDLocal + metaData.meshIndex.first)
->getCollisionMeshData();
int lastIndex = mesh.vbo.size();
for (auto& pos : meshData.positions) {
mesh.vbo.push_back(Magnum::EigenIntegration::cast<vec3f>(
transformFromLocalToWorld.transformPoint(pos)));
}
for (auto& index : meshData.indices) {
mesh.ibo.push_back(index + lastIndex);
}
}
for (const auto& child : node.children) {
joinHierarchy(mesh, metaData, child, transformFromLocalToWorld);
}
}
std::unique_ptr<MeshData> ResourceManager::createJoinedCollisionMesh(
const std::string& filename) const {
std::unique_ptr<MeshData> mesh = std::make_unique<MeshData>();
CHECK(resourceDict_.count(filename) > 0);
const MeshMetaData& metaData = getMeshMetaData(filename);
Magnum::Matrix4 identity;
joinHierarchy(*mesh, metaData, metaData.root, identity);
return mesh;
}
#ifdef ESP_BUILD_WITH_VHACD
bool ResourceManager::outputMeshMetaDataToObj(
const std::string& MeshMetaDataFile,
const std::string& new_filename,
const std::string& filepath) const {
bool success = Cr::Utility::Directory::mkpath(filepath);
const MeshMetaData& metaData = getMeshMetaData(MeshMetaDataFile);
std::string out = "# chd Mesh group \n";
// write vertex info to file
int numVertices = 0;
for (const MeshTransformNode& node : metaData.root.children) {
CollisionMeshData& meshData =
meshes_.at(node.meshIDLocal + metaData.meshIndex.first)
->getCollisionMeshData();
for (auto& pos : meshData.positions) {
Mn::Utility::formatInto(out, out.size(), "{0} {1} {2} {3}{4}", "v",
pos[0], pos[1], pos[2], "\n");
numVertices++;
}
}
Mn::Utility::formatInto(out, out.size(), "{0} {1} {2}",
"# Number of vertices", numVertices, "\n\n");
// Now do second pass to write indices for each group (node)
int globalVertexNum = 1;
int numParts = 1;
for (const MeshTransformNode& node : metaData.root.children) {
CollisionMeshData& meshData =
meshes_.at(node.meshIDLocal + metaData.meshIndex.first)
->getCollisionMeshData();
Mn::Utility::formatInto(out, out.size(), "{0}{1} {2}", "g part_", numParts,
"mesh\n");
for (int ix = 0; ix < meshData.indices.size(); ix += 3) {
Mn::Utility::formatInto(out, out.size(), "{0} {1} {2} {3}{4}", "f",
meshData.indices[ix] + globalVertexNum,
meshData.indices[ix + 1] + globalVertexNum,
meshData.indices[ix + 2] + globalVertexNum, "\n");
}
numParts++;
globalVertexNum += meshData.positions.size();
}
Cr::Utility::Directory::writeString(filepath + "/" + new_filename, out);
return success;
} // ResourceManager::outputMeshMetaDataToObj
bool ResourceManager::isAssetDataRegistered(
const std::string& resourceName) const {
return (resourceDict_.count(resourceName) > 0);
}
void ResourceManager::createConvexHullDecomposition(
const std::string& filename,
const std::string& chdFilename,
const VHACDParameters& params,
const bool saveChdToObj) {
if (resourceDict_.count(filename) == 0) {
// retrieve existing, or create new, object attributes corresponding to
// passed filename
auto objAttributes =
getObjectAttributesManager()->getObjectCopyByHandle(filename);
if (objAttributes == nullptr) {
objAttributes =
getObjectAttributesManager()->createObject(filename, false);
}
// load/check for render MeshMetaData and load assets
loadObjectMeshDataFromFile(filename, objAttributes, "render", true);
} // if no render asset exists
// get joined mesh data
assets::MeshData::uptr joinedMesh = assets::MeshData::create_unique();
joinedMesh = createJoinedCollisionMesh(filename);
// use VHACD
interfaceVHACD->Compute(&joinedMesh->vbo[0][0], joinedMesh->vbo.size(),
&joinedMesh->ibo[0], joinedMesh->ibo.size() / 3,
params);
Cr::Utility::Debug() << "== VHACD ran ==";
// convert convex hulls into MeshDatas, CollisionMeshDatas
int meshStart = meshes_.size();
std::vector<CollisionMeshData> collisionMeshGroup;
int nConvexHulls = interfaceVHACD->GetNConvexHulls();
Cr::Utility::Debug() << "Num Convex Hulls: " << nConvexHulls;
Cr::Utility::Debug() << "Resolution: " << params.m_resolution;
VHACD::IVHACD::ConvexHull ch{};
std::unique_ptr<GenericMeshData> genCHMeshData;
for (unsigned int p = 0; p < nConvexHulls; ++p) {
// for each convex hull, transfer the data to a newly created MeshData
interfaceVHACD->GetConvexHull(p, ch);
std::vector<Magnum::Vector3> positions;
// add the vertices
positions.resize(ch.m_nPoints);
for (size_t vix = 0; vix < ch.m_nPoints; vix++) {
positions[vix] =
Magnum::Vector3(ch.m_points[vix * 3], ch.m_points[vix * 3 + 1],
ch.m_points[vix * 3 + 2]);
}
// add indices
Cr::Containers::ArrayView<const Mn::UnsignedInt> indices{
ch.m_triangles, ch.m_nTriangles * 3};
// create an owned MeshData
Cr::Containers::Optional<Mn::Trade::MeshData> CHMesh = Mn::MeshTools::owned(
Mn::Trade::MeshData{Mn::MeshPrimitive::Triangles,
{},
indices,
Mn::Trade::MeshIndexData{indices},
{},
positions,
{Mn::Trade::MeshAttributeData{
Mn::Trade::MeshAttribute::Position,
Cr::Containers::arrayView(positions)}}});
// Create a GenericMeshData (needsNormals_ = true and uploadBuffersToGPU in
// order to render the collision asset)
genCHMeshData = std::make_unique<GenericMeshData>(true);
genCHMeshData->setMeshData(*std::move(CHMesh));
genCHMeshData->BB = computeMeshBB(genCHMeshData.get());
genCHMeshData->uploadBuffersToGPU(true);
// Create CollisionMeshData and add to collisionMeshGroup vector
CollisionMeshData CHCollisionMesh = genCHMeshData->getCollisionMeshData();
collisionMeshGroup.push_back(CHCollisionMesh);
// register GenericMeshData in meshes_ dict
meshes_.emplace(meshes_.size(), std::move(genCHMeshData));
}
// make MeshMetaData
int meshEnd = meshes_.size() - 1;
MeshMetaData meshMetaData{meshStart, meshEnd};
// get original componentID (REVISIT)
int componentID = getMeshMetaData(filename).root.componentID;
// populate MeshMetaData root children
for (unsigned int p = 0; p < nConvexHulls; ++p) {
MeshTransformNode transformNode;
transformNode.meshIDLocal = p;
transformNode.componentID = componentID;
meshMetaData.root.children.push_back(transformNode);
}
// make assetInfo
AssetInfo info{AssetType::PRIMITIVE};
info.requiresLighting = true;
// make LoadedAssetData corresponding to this asset
LoadedAssetData loadedAssetData{info, meshMetaData};
// Register collision mesh group
auto insertedCollisionMeshGroup =
collisionMeshGroups_.emplace(chdFilename, std::move(collisionMeshGroup));
// insert MeshMetaData into resourceDict_
auto insertedResourceDict =
resourceDict_.emplace(chdFilename, std::move(loadedAssetData));
if (saveChdToObj) {
std::string objDirectory = Cr::Utility::Directory::join(
Corrade::Utility::Directory::current(), "data/VHACD_outputs");
std::string new_filename =
Cr::Utility::Directory::filename(
Cr::Utility::Directory::splitExtension(chdFilename).first) +
".obj";
outputMeshMetaDataToObj(chdFilename, new_filename, objDirectory);
}
}
#endif
} // namespace assets
} // namespace esp
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Runtime::ExceptionServices
namespace System::Runtime::ExceptionServices {
// Forward declaring type: ExceptionDispatchInfo
class ExceptionDispatchInfo;
}
// Completed forward declares
// Type namespace: Mono.Net.Security
namespace Mono::Net::Security {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: Mono.Net.Security.AsyncProtocolResult
class AsyncProtocolResult : public ::Il2CppObject {
public:
// [CompilerGeneratedAttribute] Offset: 0xD887DC
// private readonly System.Int32 <UserResult>k__BackingField
// Size: 0x4
// Offset: 0x10
int UserResult;
// Field size check
static_assert(sizeof(int) == 0x4);
// Padding between fields: UserResult and: Error
char __padding0[0x4] = {};
// [CompilerGeneratedAttribute] Offset: 0xD887EC
// private readonly System.Runtime.ExceptionServices.ExceptionDispatchInfo <Error>k__BackingField
// Size: 0x8
// Offset: 0x18
System::Runtime::ExceptionServices::ExceptionDispatchInfo* Error;
// Field size check
static_assert(sizeof(System::Runtime::ExceptionServices::ExceptionDispatchInfo*) == 0x8);
// Creating value type constructor for type: AsyncProtocolResult
AsyncProtocolResult(int UserResult_ = {}, System::Runtime::ExceptionServices::ExceptionDispatchInfo* Error_ = {}) noexcept : UserResult{UserResult_}, Error{Error_} {}
// public System.Int32 get_UserResult()
// Offset: 0x15D5E30
int get_UserResult();
// public System.Runtime.ExceptionServices.ExceptionDispatchInfo get_Error()
// Offset: 0x15D5E38
System::Runtime::ExceptionServices::ExceptionDispatchInfo* get_Error();
// public System.Void .ctor(System.Int32 result)
// Offset: 0x15D5C00
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AsyncProtocolResult* New_ctor(int result) {
static auto ___internal__logger = ::Logger::get().WithContext("Mono::Net::Security::AsyncProtocolResult::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AsyncProtocolResult*, creationType>(result)));
}
// public System.Void .ctor(System.Runtime.ExceptionServices.ExceptionDispatchInfo error)
// Offset: 0x15D5DA4
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AsyncProtocolResult* New_ctor(System::Runtime::ExceptionServices::ExceptionDispatchInfo* error) {
static auto ___internal__logger = ::Logger::get().WithContext("Mono::Net::Security::AsyncProtocolResult::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AsyncProtocolResult*, creationType>(error)));
}
}; // Mono.Net.Security.AsyncProtocolResult
#pragma pack(pop)
static check_size<sizeof(AsyncProtocolResult), 24 + sizeof(System::Runtime::ExceptionServices::ExceptionDispatchInfo*)> __Mono_Net_Security_AsyncProtocolResultSizeCheck;
static_assert(sizeof(AsyncProtocolResult) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(Mono::Net::Security::AsyncProtocolResult*, "Mono.Net.Security", "AsyncProtocolResult");
|
/*
* Copyright (c) 2012 cocos2d-x.org
* http://www.cocos2d-x.org
*
* Copyright 2011 Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "CCControlButton.h"
#include "CCScale9Sprite.h"
#include "2d/CCLabel.h"
#include "2d/CCAction.h"
#include "2d/CCActionInterval.h"
using namespace std;
NS_CC_EXT_BEGIN
enum
{
kZoomActionTag = 0xCCCB0001,
};
ControlButton::ControlButton()
: _isPushed(false)
, _parentInited(false)
, _doesAdjustBackgroundImage(false)
, _currentTitleColor(Color3B::WHITE)
, _titleLabel(nullptr)
, _backgroundSprite(nullptr)
, _zoomOnTouchDown(false)
, _marginV(ControlButtonMarginTB)
, _marginH(ControlButtonMarginLR)
{
}
ControlButton::~ControlButton()
{
CC_SAFE_RELEASE(_titleLabel);
CC_SAFE_RELEASE(_backgroundSprite);
}
//initialisers
bool ControlButton::init()
{
return this->initWithLabelAndBackgroundSprite(Label::createWithSystemFont("", "Helvetica", 12), Scale9Sprite::create());
}
bool ControlButton::initWithLabelAndBackgroundSprite(Node* node, Scale9Sprite* backgroundSprite)
{
if (Control::init())
{
CCASSERT(node != nullptr, "Label must not be nil.");
LabelProtocol* label = dynamic_cast<LabelProtocol*>(node);
CCASSERT(backgroundSprite != nullptr, "Background sprite must not be nil.");
CCASSERT(label != nullptr || backgroundSprite != nullptr, "");
_parentInited = true;
_isPushed = false;
// Adjust the background image by default
setAdjustBackgroundImage(true);
setPreferredSize(Size::ZERO);
// Zooming button by default
_zoomOnTouchDown = true;
_scaleRatio = 1.1f;
// Set the default anchor point
ignoreAnchorPointForPosition(false);
setAnchorPoint(Vec2::ANCHOR_MIDDLE);
// Set the nodes
setTitleLabel(node);
setBackgroundSprite(backgroundSprite);
// Set the default color and opacity
setColor(Color3B::WHITE);
setOpacity(255.0f);
setOpacityModifyRGB(true);
// Initialize the dispatch table
setTitleForState(label->getString(), Control::State::NORMAL);
setTitleColorForState(node->getColor(), Control::State::NORMAL);
setTitleLabelForState(node, Control::State::NORMAL);
setBackgroundSpriteForState(backgroundSprite, Control::State::NORMAL);
setLabelAnchorPoint(Vec2::ANCHOR_MIDDLE);
// Layout update
needsLayout();
return true;
}
//couldn't init the Control
else
{
return false;
}
}
ControlButton* ControlButton::create(Node* label, Scale9Sprite* backgroundSprite)
{
ControlButton *pRet = new ControlButton();
pRet->initWithLabelAndBackgroundSprite(label, backgroundSprite);
pRet->autorelease();
return pRet;
}
bool ControlButton::initWithTitleAndFontNameAndFontSize(const std::string& title, const std::string& fontName, float fontSize)
{
return initWithLabelAndBackgroundSprite(Label::createWithSystemFont(title, fontName, fontSize), Scale9Sprite::create());
}
ControlButton* ControlButton::create(const std::string& title, const std::string& fontName, float fontSize)
{
ControlButton *pRet = new ControlButton();
pRet->initWithTitleAndFontNameAndFontSize(title, fontName, fontSize);
pRet->autorelease();
return pRet;
}
bool ControlButton::initWithBackgroundSprite(Scale9Sprite* sprite)
{
Label *label = Label::createWithSystemFont("", "Arial", 30);//
return initWithLabelAndBackgroundSprite(label, sprite);
}
ControlButton* ControlButton::create(Scale9Sprite* sprite)
{
ControlButton *pRet = new ControlButton();
pRet->initWithBackgroundSprite(sprite);
pRet->autorelease();
return pRet;
}
void ControlButton::setMargins(int marginH, int marginV)
{
_marginV = marginV;
_marginH = marginH;
needsLayout();
}
void ControlButton::setEnabled(bool enabled)
{
Control::setEnabled(enabled);
needsLayout();
}
void ControlButton::setSelected(bool enabled)
{
Control::setSelected(enabled);
needsLayout();
}
void ControlButton::setHighlighted(bool enabled)
{
if (enabled == true)
{
_state = Control::State::HIGH_LIGHTED;
}
else
{
_state = Control::State::NORMAL;
}
Control::setHighlighted(enabled);
Action *action = getActionByTag(kZoomActionTag);
if (action)
{
stopAction(action);
}
needsLayout();
if( _zoomOnTouchDown )
{
float scaleValue = (isHighlighted() && isEnabled() && !isSelected()) ? _scaleRatio : 1.0f;
Action *zoomAction = ScaleTo::create(0.05f, scaleValue);
zoomAction->setTag(kZoomActionTag);
runAction(zoomAction);
}
}
void ControlButton::setZoomOnTouchDown(bool zoomOnTouchDown)
{
_zoomOnTouchDown = zoomOnTouchDown;
}
bool ControlButton::getZoomOnTouchDown()
{
return _zoomOnTouchDown;
}
void ControlButton::setPreferredSize(const Size& size)
{
if(size.width == 0 && size.height == 0)
{
_doesAdjustBackgroundImage = true;
}
else
{
_doesAdjustBackgroundImage = false;
for (auto iter = _backgroundSpriteDispatchTable.begin(); iter != _backgroundSpriteDispatchTable.end(); ++iter)
{
iter->second->setPreferredSize(size);
}
}
_preferredSize = size;
needsLayout();
}
const Size& ControlButton::getPreferredSize() const
{
return _preferredSize;
}
void ControlButton::setAdjustBackgroundImage(bool adjustBackgroundImage)
{
_doesAdjustBackgroundImage=adjustBackgroundImage;
needsLayout();
}
bool ControlButton::doesAdjustBackgroundImage()
{
return _doesAdjustBackgroundImage;
}
const Vec2& ControlButton::getLabelAnchorPoint() const
{
return this->_labelAnchorPoint;
}
void ControlButton::setLabelAnchorPoint(const Vec2& labelAnchorPoint)
{
this->_labelAnchorPoint = labelAnchorPoint;
if (_titleLabel != nullptr)
{
this->_titleLabel->setAnchorPoint(labelAnchorPoint);
}
}
std::string ControlButton::getTitleForState(State state)
{
auto iter = _titleDispatchTable.find((int)state);
if (iter != _titleDispatchTable.end())
{
return iter->second;
}
iter = _titleDispatchTable.find((int)Control::State::NORMAL);
return iter != _titleDispatchTable.end() ? iter->second : "";
}
void ControlButton::setTitleForState(const std::string& title, State state)
{
_titleDispatchTable.erase((int)state);
if (!title.empty())
{
_titleDispatchTable[(int)state] = title;
}
// If the current state if equal to the given state we update the layout
if (getState() == state)
{
needsLayout();
}
}
Color3B ControlButton::getTitleColorForState(State state) const
{
Color3B returnColor = Color3B::WHITE;
auto iter = _titleColorDispatchTable.find((int)state);
if (iter != _titleColorDispatchTable.end())
{
returnColor = iter->second;
}
else
{
iter = _titleColorDispatchTable.find((int)Control::State::NORMAL);
if (iter != _titleColorDispatchTable.end())
{
returnColor = iter->second;
}
}
return returnColor;
}
void ControlButton::setTitleColorForState(const Color3B& color, State state)
{
_titleColorDispatchTable.erase((int)state);
_titleColorDispatchTable[(int)state] = color;
// If the current state if equal to the given state we update the layout
if (getState() == state)
{
needsLayout();
}
}
Node* ControlButton::getTitleLabelForState(State state)
{
Node* titleLabel = _titleLabelDispatchTable.at((int)state);
if (titleLabel)
{
return titleLabel;
}
return _titleLabelDispatchTable.at((int)Control::State::NORMAL);
}
void ControlButton::setTitleLabelForState(Node* titleLabel, State state)
{
Node* previousLabel = _titleLabelDispatchTable.at((int)state);
if (previousLabel)
{
removeChild(previousLabel, true);
_titleLabelDispatchTable.erase((int)state);
}
_titleLabelDispatchTable.insert((int)state, titleLabel);
titleLabel->setVisible(false);
titleLabel->setAnchorPoint(Vec2(0.5f, 0.5f));
addChild(titleLabel, 1);
// If the current state if equal to the given state we update the layout
if (getState() == state)
{
needsLayout();
}
}
void ControlButton::setTitleTTFForState(const std::string& fontName, State state)
{
this->setTitleLabelForState(Label::createWithSystemFont(getTitleForState(state), fontName, 12), state);
}
const std::string& ControlButton::getTitleTTFForState(State state)
{
LabelProtocol* label = dynamic_cast<LabelProtocol*>(this->getTitleLabelForState(state));
Label* labelTTF = dynamic_cast<Label*>(label);
if(labelTTF != 0)
{
return labelTTF->getSystemFontName();
}
static std::string ret("");
return ret;
}
void ControlButton::setTitleTTFSizeForState(float size, State state)
{
LabelProtocol* label = dynamic_cast<LabelProtocol*>(this->getTitleLabelForState(state));
if(label)
{
Label* labelTTF = dynamic_cast<Label*>(label);
if(labelTTF != 0)
{
return labelTTF->setSystemFontSize(size);
}
}
}
float ControlButton::getTitleTTFSizeForState(State state)
{
LabelProtocol* label = dynamic_cast<LabelProtocol*>(this->getTitleLabelForState(state));
Label* labelTTF = dynamic_cast<Label*>(label);
if(labelTTF != 0)
{
return labelTTF->getSystemFontSize();
}
else
{
return 0;
}
}
void ControlButton::setTitleBMFontForState(const std::string& fntFile, State state)
{
std::string title = this->getTitleForState(state);
this->setTitleLabelForState(Label::createWithBMFont(fntFile, title), state);
}
const std::string& ControlButton::getTitleBMFontForState(State state)
{
LabelProtocol* label = dynamic_cast<LabelProtocol*>(this->getTitleLabelForState(state));
auto labelBMFont = dynamic_cast<Label*>(label);
if(labelBMFont != 0)
{
return labelBMFont->getBMFontFilePath();
}
static std::string ret("");
return ret;
}
Scale9Sprite* ControlButton::getBackgroundSpriteForState(State state)
{
auto backgroundSprite = _backgroundSpriteDispatchTable.at((int)state);
if (backgroundSprite)
{
return backgroundSprite;
}
return _backgroundSpriteDispatchTable.at((int)Control::State::NORMAL);
}
void ControlButton::setBackgroundSpriteForState(Scale9Sprite* sprite, State state)
{
Size oldPreferredSize = _preferredSize;
auto previousBackgroundSprite = _backgroundSpriteDispatchTable.at((int)state);
if (previousBackgroundSprite)
{
removeChild(previousBackgroundSprite, true);
_backgroundSpriteDispatchTable.erase((int)state);
}
_backgroundSpriteDispatchTable.insert((int)state, sprite);
sprite->setVisible(false);
sprite->setAnchorPoint(Vec2(0.5f, 0.5f));
addChild(sprite);
if (this->_preferredSize.width != 0 || this->_preferredSize.height != 0)
{
if (oldPreferredSize.equals(_preferredSize))
{
// Force update of preferred size
sprite->setPreferredSize(Size(oldPreferredSize.width+1, oldPreferredSize.height+1));
}
sprite->setPreferredSize(this->_preferredSize);
}
// If the current state if equal to the given state we update the layout
if (getState() == state)
{
needsLayout();
}
}
void ControlButton::setBackgroundSpriteFrameForState(SpriteFrame * spriteFrame, State state)
{
Scale9Sprite * sprite = Scale9Sprite::createWithSpriteFrame(spriteFrame);
this->setBackgroundSpriteForState(sprite, state);
}
void ControlButton::needsLayout()
{
if (!_parentInited) {
return;
}
// Hide the background and the label
if (_titleLabel != nullptr) {
_titleLabel->setVisible(false);
}
if (_backgroundSprite) {
_backgroundSprite->setVisible(false);
}
// Update anchor of all labels
this->setLabelAnchorPoint(this->_labelAnchorPoint);
// Update the label to match with the current state
_currentTitle = getTitleForState(_state);
_currentTitleColor = getTitleColorForState(_state);
this->setTitleLabel(getTitleLabelForState(_state));
LabelProtocol* label = dynamic_cast<LabelProtocol*>(_titleLabel);
if (label && !_currentTitle.empty())
{
label->setString(_currentTitle);
}
if (_titleLabel)
{
_titleLabel->setColor(_currentTitleColor);
}
if (_titleLabel != nullptr)
{
_titleLabel->setPosition(Vec2 (getContentSize().width / 2, getContentSize().height / 2));
}
// Update the background sprite
this->setBackgroundSprite(this->getBackgroundSpriteForState(_state));
if (_backgroundSprite != nullptr)
{
_backgroundSprite->setPosition(Vec2 (getContentSize().width / 2, getContentSize().height / 2));
}
// Get the title label size
Size titleLabelSize;
if (_titleLabel != nullptr)
{
titleLabelSize = _titleLabel->getBoundingBox().size;
}
// Adjust the background image if necessary
if (_doesAdjustBackgroundImage)
{
// Add the margins
if (_backgroundSprite != nullptr)
{
_backgroundSprite->setContentSize(Size(titleLabelSize.width + _marginH * 2, titleLabelSize.height + _marginV * 2));
}
}
else
{
//TODO: should this also have margins if one of the preferred sizes is relaxed?
if (_backgroundSprite != nullptr)
{
Size preferredSize = _backgroundSprite->getPreferredSize();
if (preferredSize.width <= 0)
{
preferredSize.width = titleLabelSize.width;
}
if (preferredSize.height <= 0)
{
preferredSize.height = titleLabelSize.height;
}
_backgroundSprite->setContentSize(preferredSize);
}
}
// Set the content size
Rect rectTitle;
if (_titleLabel != nullptr)
{
rectTitle = _titleLabel->getBoundingBox();
}
Rect rectBackground;
if (_backgroundSprite != nullptr)
{
rectBackground = _backgroundSprite->getBoundingBox();
}
Rect maxRect = ControlUtils::RectUnion(rectTitle, rectBackground);
setContentSize(Size(maxRect.size.width, maxRect.size.height));
if (_titleLabel != nullptr)
{
_titleLabel->setPosition(Vec2(getContentSize().width/2, getContentSize().height/2));
// Make visible the background and the label
_titleLabel->setVisible(true);
}
if (_backgroundSprite != nullptr)
{
_backgroundSprite->setPosition(Vec2(getContentSize().width/2, getContentSize().height/2));
_backgroundSprite->setVisible(true);
}
}
bool ControlButton::onTouchBegan(Touch *pTouch, Event *pEvent)
{
if (!isTouchInside(pTouch) || !isEnabled() || !isVisible() || !hasVisibleParents() )
{
return false;
}
for (Node *c = this->_parent; c != nullptr; c = c->getParent())
{
if (c->isVisible() == false)
{
return false;
}
}
_isPushed = true;
this->setHighlighted(true);
sendActionsForControlEvents(Control::EventType::TOUCH_DOWN);
return true;
}
void ControlButton::onTouchMoved(Touch *pTouch, Event *pEvent)
{
if (!isEnabled() || !isPushed() || isSelected())
{
if (isHighlighted())
{
setHighlighted(false);
}
return;
}
bool isTouchMoveInside = isTouchInside(pTouch);
if (isTouchMoveInside && !isHighlighted())
{
setHighlighted(true);
sendActionsForControlEvents(Control::EventType::DRAG_ENTER);
}
else if (isTouchMoveInside && isHighlighted())
{
sendActionsForControlEvents(Control::EventType::DRAG_INSIDE);
}
else if (!isTouchMoveInside && isHighlighted())
{
setHighlighted(false);
sendActionsForControlEvents(Control::EventType::DRAG_EXIT);
}
else if (!isTouchMoveInside && !isHighlighted())
{
sendActionsForControlEvents(Control::EventType::DRAG_OUTSIDE);
}
}
void ControlButton::onTouchEnded(Touch *pTouch, Event *pEvent)
{
_isPushed = false;
setHighlighted(false);
if (isTouchInside(pTouch))
{
sendActionsForControlEvents(Control::EventType::TOUCH_UP_INSIDE);
}
else
{
sendActionsForControlEvents(Control::EventType::TOUCH_UP_OUTSIDE);
}
}
void ControlButton::setOpacity(GLubyte opacity)
{
Control::setOpacity(opacity);
for (auto iter = _backgroundSpriteDispatchTable.begin(); iter != _backgroundSpriteDispatchTable.end(); ++iter)
{
iter->second->setOpacity(opacity);
}
for (auto iter = _titleLabelDispatchTable.begin(); iter != _titleLabelDispatchTable.end(); ++iter)
{
iter->second->setOpacity(opacity);
}
}
void ControlButton::updateDisplayedOpacity(GLubyte parentOpacity)
{
Control::updateDisplayedOpacity(parentOpacity);
for (auto iter = _backgroundSpriteDispatchTable.begin(); iter != _backgroundSpriteDispatchTable.end(); ++iter)
{
iter->second->updateDisplayedOpacity(parentOpacity);
}
for (auto iter = _titleLabelDispatchTable.begin(); iter != _titleLabelDispatchTable.end(); ++iter)
{
iter->second->updateDisplayedOpacity(parentOpacity);
}
}
void ControlButton::setColor(const Color3B & color)
{
Control::setColor(color);
for (auto iter = _backgroundSpriteDispatchTable.begin(); iter != _backgroundSpriteDispatchTable.end(); ++iter)
{
iter->second->setColor(color);
}
for (auto iter = _titleLabelDispatchTable.begin(); iter != _titleLabelDispatchTable.end(); ++iter)
{
iter->second->setColor(color);
}
}
void ControlButton::updateDisplayedColor(const Color3B& parentColor)
{
Control::updateDisplayedColor(parentColor);
for (auto iter = _backgroundSpriteDispatchTable.begin(); iter != _backgroundSpriteDispatchTable.end(); ++iter)
{
iter->second->updateDisplayedColor(parentColor);
}
for (auto iter = _titleLabelDispatchTable.begin(); iter != _titleLabelDispatchTable.end(); ++iter)
{
iter->second->updateDisplayedColor(parentColor);
}
}
void ControlButton::onTouchCancelled(Touch *pTouch, Event *pEvent)
{
_isPushed = false;
setHighlighted(false);
sendActionsForControlEvents(Control::EventType::TOUCH_CANCEL);
}
ControlButton* ControlButton::create()
{
ControlButton *pControlButton = new ControlButton();
if (pControlButton && pControlButton->init())
{
pControlButton->autorelease();
return pControlButton;
}
CC_SAFE_DELETE(pControlButton);
return nullptr;
}
NS_CC_EXT_END
|
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include "mindspore/lite/tools/converter/parser/onnx/onnx_constant_parser.h"
namespace mindspore {
namespace lite {
STATUS OnnxConstantParser::Parse(const onnx::GraphProto &onnx_graph,
const onnx::NodeProto &onnx_node,
schema::CNodeT *op) {
if (op != nullptr) {
op->primitive = std::make_unique<schema::PrimitiveT>();
op->primitive->value.type = schema::PrimitiveType_Constant;
op->primitive->value.value = nullptr;
}
return RET_OK;
}
OnnxNodeRegistrar g_onnxConstantParser("Constant", new OnnxConstantParser());
} // namespace lite
} // namespace mindspore
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/input/tap_suppression_controller.h"
#include "base/logging.h"
#include "base/trace_event/trace_event.h"
#include "ui/events/gesture_detection/gesture_configuration.h"
namespace content {
TapSuppressionController::Config::Config()
: enabled(false),
max_cancel_to_down_time(base::TimeDelta::FromMilliseconds(180)) {
}
TapSuppressionController::TapSuppressionController(const Config& config)
: state_(config.enabled ? NOTHING : DISABLED),
max_cancel_to_down_time_(config.max_cancel_to_down_time) {}
TapSuppressionController::~TapSuppressionController() {}
void TapSuppressionController::GestureFlingCancelStoppedFling() {
base::TimeTicks event_time = Now();
switch (state_) {
case DISABLED:
case SUPPRESSING_TAPS:
break;
case NOTHING:
fling_cancel_time_ = event_time;
state_ = LAST_CANCEL_STOPPED_FLING;
break;
case LAST_CANCEL_STOPPED_FLING:
break;
}
}
bool TapSuppressionController::ShouldSuppressTapDown() {
base::TimeTicks event_time = Now();
switch (state_) {
case DISABLED:
case NOTHING:
return false;
case LAST_CANCEL_STOPPED_FLING:
if ((event_time - fling_cancel_time_) < max_cancel_to_down_time_) {
state_ = SUPPRESSING_TAPS;
return true;
} else {
state_ = NOTHING;
return false;
}
// Stop suppressing tap end events.
case SUPPRESSING_TAPS:
state_ = NOTHING;
return false;
}
NOTREACHED() << "Invalid state";
return false;
}
bool TapSuppressionController::ShouldSuppressTapEnd() {
switch (state_) {
case DISABLED:
case NOTHING:
return false;
case LAST_CANCEL_STOPPED_FLING:
NOTREACHED() << "Invalid tap end on LAST_CANCEL_STOPPED_FLING state";
return true;
case SUPPRESSING_TAPS:
return true;
}
return false;
}
base::TimeTicks TapSuppressionController::Now() {
return base::TimeTicks::Now();
}
} // namespace content
|
/*******************************************************************************
* Copyright 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/// @example performance_profiling.cpp
/// This example demonstrates the best practices for application performance
/// optimizations with DNNL.
///
/// > Annotated version: @ref performance_profiling_cpp
/// @page performance_profiling_cpp Performance Profiling Example
#include <chrono>
#include <iostream>
#include <stdio.h>
#include <vector>
#include "example_utils.hpp"
/// > Example code: @ref performance_profiling.cpp
///
/// This example uses [DNNL_VERBOSE](@ref dev_guide_verbose) trace output
/// to tune DNNL code to align
/// with the [best practices](@ref dev_guide_inference).
///
/// It will assume knowledge of memory formats and their usage in
/// DNNL. You can read more about this topic
/// [here](@ref memory_format_propagation_cpp).
///
/// The example has three different implementations of the mathematical
/// operation:
/// 1. *Naive implementation* executes 2D convolution followed by
/// ReLU on the data in **NCHW** format. This implementation
/// does not align with DNNL best practices and results in
/// suboptimal performance.
/// 2. *Blocked format implementation* executes the same operations
/// sequence on the **blocked format** optimized for convolution
/// performance. This implementation uses `format_tag=ANY` to create a
/// convolution memory descriptor to determine the data format optimal
/// for the convolution implementation. It then **propagates the blocked
/// format** to the non-intensive ReLU. This implementation results
/// in better overall performance than the naive implementation.
/// 3. *Fused implementation* executes convolution fused with ReLU on
/// blocked data format. This implementation uses
/// `format_tag=ANY` to create a convolution memory descriptor, and then
/// adds ReLU as a **post-op** to the convolution primitive. This version
/// implements all of the best practices for inference resulting in the
/// best overall performance.
///
/// @section performance_profiling_cpp_walkthrough Walkthrough
///
/// The program in \ref performance_profiling.cpp includes all three
/// implementations introduced above. You can select the specific implementation
/// using command line options.
///
/// After compilation, you can execute each implementation with:
/// ~~~sh
/// ./program.exe implementation
/// ~~~
///
/// Before you run the program, set your `DNNL_VERBOSE` environment
/// variable to 1:
/// ~~~sh
/// export DNNL_VERBOSE=1
/// ~~~
///
/// The program starts by creating DNNL memory objects in **NCHW**
/// format. These are called `user_` because they are meant to represent the
/// user's source data entering DNNL with the NCHW format.
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Set dimensions
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create memory objects
/// @page performance_profiling_cpp
/// @note You can change the batch size to easily increase/decrease the workload.
///
/// The following descriptions of each implementation will reference each other,
/// and are meant to be read in order.
///
using namespace dnnl;
// [Prologue]
// Set Strides and Padding
const memory::dims strides = {4, 4};
const memory::dims padding = {0, 0};
// [Prologue]
//
// function to init data
void init_data(memory &m, float v) {
size_t size = m.get_desc().get_size() / sizeof(float);
std::vector<float> data(size);
read_from_dnnl_memory(data.data(), m);
for (size_t i = 0; i < size; ++i)
data[i] = v;
}
// function to execute non-fused relu
void create_and_execute_relu(memory &data, engine &eng, stream &s) {
// relu operates on whatever data format is given to it
// create a primitive
auto relu_d = eltwise_forward::desc(prop_kind::forward_inference,
algorithm::eltwise_relu, data.get_desc(), 0.f, 0.f);
auto relu_pd = eltwise_forward::primitive_desc(relu_d, eng);
auto relu = eltwise_forward(relu_pd);
// execute it (in-place)
relu.execute(s, {{DNNL_ARG_SRC, data}, {DNNL_ARG_DST, data}});
}
// [Create post_op attr with relu]
// function to create post-op attribute for fused relu
primitive_attr create_attr_with_relu_post_op() {
// create a post-op with relu
post_ops ops;
ops.append_eltwise(1.f, algorithm::eltwise_relu, 0.f, 0.f);
// create an attribute and set the corresponding post op
primitive_attr attr;
attr.set_post_ops(ops);
return attr;
}
// [Create post_op attr with relu]
// Implementation for naive convolution on nchw (data) and oihw (weights),
// followed by execution of non-fused relu
void conv_relu_naive(memory user_src, memory user_wei, memory user_dst,
engine &eng, stream &s) {
/// @section performance_profiling_cpp_implementation1 Naive Implementation
/// This implementation is launched with the following shell code:
/// ~~~sh
/// ./program.exe naive
/// ~~~
/// The program will call the implementation defined in the function
/// `conv_relu_naive()`.
///
/// First it sets the dimensions and format for convolution memory
/// descriptors (`_md`) to match `user_` values--one `md` each for source,
/// destination, and weight data. Then it uses those `md` to create the
/// convolution descriptor `conv_d`, which tells DNNL to use
/// plain format (NCHW) for the convolution.
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create mem_desc
// [Create mem_desc]
// copy the dimensions and format from user's memory
auto conv_src_md = memory::desc(user_src.get_desc());
auto conv_wei_md = memory::desc(user_wei.get_desc());
auto conv_dst_md = memory::desc(user_dst.get_desc());
// [Create mem_desc]
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create conv_desc
// [Create conv_desc]
// create a convolution descriptor
auto conv_d = convolution_forward::desc(prop_kind::forward_inference,
algorithm::convolution_direct, conv_src_md, conv_wei_md,
conv_dst_md, strides, padding, padding);
// [Create conv_desc]
/// Next the program creates a convolution primitive descriptor `conv_pd`
/// and convolution primitive `conv`. These structs will inherit
/// NCHW format from `md` by way of the `conv_d`. Finally it creates
/// the convolution primitive `conv` and adds it to the stream `s`, and then
/// executes the `create_and_execute_relu(user_dst)` function.
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create conv_prim_desc
// [Create conv_prim_desc]
// create a convolution primitive descriptor
auto conv_pd = convolution_forward::primitive_desc(conv_d, eng);
// [Create conv_prim_desc]
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create conv_primitive
// [Create conv_primitive]
// create convolution primitive
auto conv = convolution_forward(conv_pd);
// [Create conv_primitive]
// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Add to stream
// [Add to stream]
// execute convolution by adding it to the stream s
conv.execute(s,
{{DNNL_ARG_SRC, user_src}, {DNNL_ARG_WEIGHTS, user_wei},
{DNNL_ARG_DST, user_dst}});
// [Add to stream]
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create and execute relu
// [Create and execute relu]
// execute relu (on convolution's destination format, whatever it is)
create_and_execute_relu(user_dst, eng, s);
// [Create and execute relu]
/// @page performance_profiling_cpp
/// @note The function for creation and execution of ReLU primitive is
/// defined elsewhere to keep this example clean. It is an non-intensive
/// operation, so the `create_and_execute_relu()` function uses whatever
/// the input data format is at the time it is called.
///
/// Using NCHW data format may result in suboptimal performance for compute
/// intensives primitives, as shown in the following DNNL_VERBOSE output
/// by the convolution and relu execution
/// times of 235.9 and 100.3 milliseconds, respectively.
///
/// *DNNL_VERBOSE output (see configuration notice\*):*
/// ~~~sh
/// dnnl_verbose,exec,convolution,gemm:jit,forward_inference,src_f32::
/// blocked:abcd:f0 wei_f32::blocked:abcd:f0 dst_f32::
/// blocked:abcd:f0,alg:convolution_direct,
/// mb1000_ic3oc96_ih227oh55kh11sh4dh0ph0_iw227ow55kw11sw4dw0pw0,235.86
/// dnnl_verbose,exec,eltwise,jit:avx512_common,forward_inference,
/// data_f32::blocked:abcd:f0,alg:eltwise_relu,1000x96x55x55,100.264
/// ~~~
/// In *Blocked format implementation*, we will incorporate the best
/// practice of letting DNNL determine the optimal format
/// for convolution primitive.
}
// Implementation for convolution on blocked format for data and
// weights, followed by execution of non-fused relu
void conv_relu_blocked(memory user_src, memory user_wei, memory user_dst,
engine &eng, stream &s) {
/// @page performance_profiling_cpp
/// @section performance_profiling_cpp_implementation2 Blocked format implementation
/// This implementation is launched with the following shell code:
/// ~~~sh
/// ./program.exe blocked
/// ~~~
/// The program will call the implementation defined in the function
/// `conv_relu_blocked()`.
///
/// First it creates the md as in **naive implementation**. Next it changes
/// the dnnl::memory::format_tag for each md to `ANY`. Then it uses those
/// md to create the convolution descriptor conv_d, which tells Intel
/// DNNL to use whatever format it recommends for the convolution.
/// DNNL will choose the a friendly blocked format.
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create mem_desc with tag=any
// [Create mem_desc with tag=any]
// copy the dimensions and format from user's memory
auto conv_src_md = memory::desc(user_src.get_desc());
auto conv_wei_md = memory::desc(user_wei.get_desc());
auto conv_dst_md = memory::desc(user_dst.get_desc());
// reset format to "any" to allow convolution to pick the best implementation
conv_src_md.data.format_kind = dnnl_format_kind_any;
conv_wei_md.data.format_kind = dnnl_format_kind_any;
conv_dst_md.data.format_kind = dnnl_format_kind_any;
// [Create mem_desc with tag=any]
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create conv_desc implementation2
// [Create conv_desc implementation2]
// create a convolution descriptor
auto conv_d = convolution_forward::desc(prop_kind::forward_inference,
algorithm::convolution_direct, conv_src_md, conv_wei_md,
conv_dst_md, strides, padding, padding);
// [Create conv_desc implementation2]
/// Next the program creates a convolution primitive descriptor conv_pd and
/// convolution primitive conv as in naive implementation.
/// However, in this implementation the structs will inherit blocked format
/// from md by way of the conv_d.
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create conv_prim_desc implementation2
// [Create conv_prim_desc implementation2]
// create a convolution primitive descriptor and primitive
auto conv_pd = convolution_forward::primitive_desc(conv_d, eng);
// [Create conv_prim_desc implementation2]
/// Since the resulting convolution primitive will expect
/// blocked source data, conditional reorders are inserted to convert
/// input data to blocked format if required.
/// The input data user_src is NCHW, so this conditional will be triggered:
///
/// @note The reoders are applied using DNNL `reorder` primitive.
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Conditionally create and execute reorder prims
// [Conditionally create and execute reorder prims]
// prepare convolution source
memory conv_src = user_src;
if (conv_pd.src_desc() != user_src.get_desc()) {
conv_src = memory(conv_pd.src_desc(), eng);
auto r_pd = reorder::primitive_desc(user_src, conv_src);
reorder(r_pd).execute(s, user_src, conv_src);
}
// prepare convolution weights
memory conv_wei = user_wei;
if (conv_pd.weights_desc() != user_wei.get_desc()) {
conv_wei = memory(conv_pd.weights_desc(), eng);
auto r_pd = reorder::primitive_desc(user_wei, conv_wei);
reorder(r_pd).execute(s, user_wei, conv_wei);
}
// prepare convolution destination
memory conv_dst = user_dst;
if (conv_pd.dst_desc() != user_dst.get_desc())
conv_dst = memory(conv_pd.dst_desc(), eng);
// [Conditionally create and execute reorder prims]
/// Finally it creates the convolution primitive `conv` and adds it to the
/// stream `s` with the reordered data (`conv_src`, `conv_wei`, `conv_dst1`)
/// as inputs and then executes the
/// `create_and_execute_relu(conv_dst)` function.
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create conv_primitive implementation2
// [Create conv_primitive implementation2]
// create convolution primitive
auto conv = convolution_forward(conv_pd);
// [Create conv_primitive implementation2]
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Add to stream implementation2
// [Add to stream implementation2]
// execute convolution by adding it to the stream s
conv.execute(s,
{{DNNL_ARG_SRC, conv_src}, {DNNL_ARG_WEIGHTS, conv_wei},
{DNNL_ARG_DST, conv_dst}});
// [Add to stream implementation2]
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create and execute relu implementation2
// [Create and execute relu implementation2]
// execute relu (on convolution's destination format, whatever it is)
create_and_execute_relu(conv_dst, eng, s);
// [Create and execute relu implementation2]
if (conv_pd.dst_desc() != user_dst.get_desc()) {
auto r_pd = reorder::primitive_desc(conv_dst, user_dst);
reorder(r_pd).execute(s, conv_dst, user_dst);
}
/// @page performance_profiling_cpp
/// Blocked memory format is recommended for DNNL primitive
/// execution and provides better performance, as shown in the
/// DNNL_VERBOSE output by the convolution and relu execution times of
/// 119.6 and 34.4 milliseconds (down from 235.9 and 100.3 in
/// *naive implementation*), respectively.
/// In this implementation, there is an additional reorder operation that
/// executes before and after the the conv + relu. This small cost is worth
/// the gain from executing in blocked format. If fact, it becomes
/// negligible when chaining together multiple DNNL operations in
/// succession. In these situations, you can do one reorder at the beginning
/// and one at the end of the chain, and only pay the reorder penalty at
/// those points in the execution.
///
/// *DNNL_VERBOSE output (see configuration notice\*):*
/// ~~~sh
/// dnnl_verbose,exec,reorder,jit:uni,undef,src_f32::blocked:abcd:f0
/// dst_f32::blocked:Acdb16a:f0,num:1,96x3x11x11,3.71387
/// dnnl_verbose,exec,convolution,jit:avx512_common,forward_inference,
/// src_f32::blocked:abcd:f0 wei_f32::blocked:Acdb16a:f0
/// dst_f32::blocked:aBcd16b:f0,alg:convolution_direct,
/// mb1000_ic3oc96_ih227oh55kh11sh4dh0ph0_iw227ow55kw11sw4dw0pw0,119.649
/// dnnl_verbose,exec,eltwise,jit:avx512_common,forward_inference,
/// data_f32::blocked:aBcd16b:f0,alg:eltwise_relu,1000x96x55x55,34.417
/// dnnl_verbose,exec,reorder,jit:uni,undef,src_f32::blocked:aBcd16b:f0
/// dst_f32::blocked:abcd:f0,num:1,1000x96x55x55,97.3352
/// ~~~
/// This inference implementation is closer to best practices than
/// *naive implementation* because it uses DNNL recommended memory
/// format. *fused implementation* will futher optimize the performance by
/// using a fused version of the conv + ReLU primitive emplying the Intel
/// DNNL [post-ops attribute](@ref dev_guide_attributes_post_ops)
// reorder data to the user's format if needed.
}
// Implementation for convolution on blocked format for data and
// weights and the relu operation fused via a post-op attribute added to the
// convolution prim_descriptor
void conv_relu_fused(memory user_src, memory user_wei, memory user_dst,
engine eng, stream s) {
/// @section performance_profiling_cpp_implementation3 Fused Implementation
/// This implementation is launched with the following shell code:
/// ~~~sh
/// ./program.exe fused
/// ~~~
/// The program will call the implementation defined in the function
/// `conv_relu_fused()`.
/// @page performance_profiling_cpp
///
/// First the memory descriptors and convolution descriptor are created as
/// in *naive implementation*.
// copy the dimensions and format from user's memory
auto conv_src_md = memory::desc(user_src.get_desc());
auto conv_wei_md = memory::desc(user_wei.get_desc());
auto conv_dst_md = memory::desc(user_dst.get_desc());
// reset format to any to allow convolution to pick the best implementation
conv_src_md.data.format_kind = dnnl_format_kind_any;
conv_wei_md.data.format_kind = dnnl_format_kind_any;
conv_dst_md.data.format_kind = dnnl_format_kind_any;
// create a convolution descriptor
auto conv_d = convolution_forward::desc(prop_kind::forward_inference,
algorithm::convolution_direct, conv_src_md, conv_wei_md,
conv_dst_md, strides, padding, padding);
/// Then in preparation for the convolution prim desctiptor, a ReLU post-op
/// is built and added to the primitive attribute `attr`:
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create post_op attr with relu
// Next the convolution prim descriptor is created, which inherits the ReLU
/// post-op by way of the attributes `attr`:
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create prim_desc with attr
// [Create prim_desc with attr]
// create an attribute for fused relu
auto attr = create_attr_with_relu_post_op();
// create a convolution primitive descriptor
auto conv_pd = convolution_forward::primitive_desc(conv_d, attr, eng);
// [Create prim_desc with attr]
/// Then conditional reorders are applied as in *blocked format
/// implementation* to convert `user_` format NCHW to blocked. Finally, it
/// creates the convolution primitive `conv` and adds it to the stream `s`
/// with the reordered data (`conv_src`, `conv_wei`, `conv_dst1`).
// prepare convolution source
memory conv_src = user_src;
if (conv_pd.src_desc() != user_src.get_desc()) {
conv_src = memory(conv_pd.src_desc(), eng);
auto r_pd = reorder::primitive_desc(user_src, conv_src);
reorder(r_pd).execute(s, user_src, conv_src);
}
// prepare convolution weights
memory conv_wei = user_wei;
if (conv_pd.weights_desc() != user_wei.get_desc()) {
conv_wei = memory(conv_pd.weights_desc(), eng);
auto r_pd = reorder::primitive_desc(user_wei, conv_wei);
reorder(r_pd).execute(s, user_wei, conv_wei);
}
// prepare convolution destination
memory conv_dst = user_dst;
if (conv_pd.dst_desc() != user_dst.get_desc())
conv_dst = memory(conv_pd.dst_desc(), eng);
/// @page performance_profiling_cpp
/// @note There is no separate addition to the stream for the ReLU
/// operation because it has been added as a post-op to the `conv` primitive.
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Create conv_primitive implementation3
// [Create conv_primitive implementation3]
// create convolution primitive
auto conv = convolution_forward(conv_pd);
// [Create conv_primitive implementation3]
/// @page performance_profiling_cpp
/// @snippet performance_profiling.cpp Add to stream implementation3
// [Add to stream implementation3]
// execute convolution by adding it to the stream s
conv.execute(s,
{{DNNL_ARG_SRC, conv_src}, {DNNL_ARG_WEIGHTS, conv_wei},
{DNNL_ARG_DST, conv_dst}});
// [Add to stream implementation3]
// reorder data to user's format if needed
if (conv_pd.dst_desc() != user_dst.get_desc()) {
auto r_pd = reorder::primitive_desc(conv_dst, user_dst);
reorder(r_pd).execute(s, conv_dst, user_dst);
}
/// @page performance_profiling_cpp
/// This implementation complies with best practices for f32 inference by
/// using the DNNL recommended blocked format for convolution and
/// adding ReLU as a post-op to execute a fused version of conv + ReLU.
/// The consequence to following best practices can be seen in the execution
/// time of the fused primitive of 103.9 milliseconds.
///
/// *DNNL_VERBOSE output (see configuration notice\*):*
/// ~~~sh
/// dnnl_verbose,exec,convolution,jit:avx512_common,forward_inference,
/// src_f32::blocked:abcd:f0 wei_f32::blocked:Acdb16a:f0
/// dst_f32::blocked:aBcd16b:f0,alg:convolution_direct,
/// mb1000_ic3oc96_ih227oh55kh11sh4dh0ph0_iw227ow55kw11sw4dw0pw0,103.916
/// ~~~
}
/// @page performance_profiling_cpp
/// @section performance_profiling_cpp_roundup Performance summary
///
/// | Implmentation | Time, ms | Cumulative speedup |
/// | :-- | --: | --: |
/// | Naive | 336.1 | 1.0 |
/// | Blocked format | 154.0 | 2.2 |
/// | Fused | 103.9 | 3.2 |
///
/// ** **
/// @page performance_profiling_cpp
/// @section performance_profiling_cpp_config Configuration Notice
/// @note This example is meant to demonstrate DNNL best practices.
/// @note It is not meant for benchmarking purposes. The platform is not fully
/// @note optimized, so the primitive execution times are only relevant in
/// @note relation to the other times in this example.
///
/// Runtime Settings:
/// * OMP_NUM_THREADS=14
/// * KMP_AFFINITY=granularity=fine,compact,1,0
///
/// Platform:
/// * CPU: Intel(R) Xeon(R) Platinum 8180M CPU @ 2.50GHz
/// * Thread(s) per core: 2
/// * Core(s) per socket: 28
/// * Socket(s): 2
/// * NUMA node(s): 2
/// * RAM (DDR4): 1.45 TB
int main(int argc, char *argv[]) {
// Initialize engine
engine::kind engine_kind = parse_engine_kind(argc, argv, 1);
engine eng(engine_kind, 0);
// Initialize stream
stream s(eng);
// [Set dimensions]
// set dimensions for synthetic data and weights
const memory::dim BATCH = 1000;
const memory::dim IC = 3, OC = 96;
const memory::dim IH = 227, KH = 11, OH = 55;
const memory::dim IW = 227, KW = 11, OW = 55;
// [Set dimensions]
// [Create memory objects]
// create DNNL memory objects for user's tensors (in nchw and oihw formats)
// @note here the library allocates memory
auto user_src = memory({{BATCH, IC, IH, IW}, memory::data_type::f32,
memory::format_tag::nchw},
eng);
auto user_wei = memory({{OC, IC, KH, KW}, memory::data_type::f32,
memory::format_tag::oihw},
eng);
auto user_dst = memory({{BATCH, OC, OH, OW}, memory::data_type::f32,
memory::format_tag::nchw},
eng);
// [Create memory objects]
// fill source, destination, and weights with synthetic data
init_data(user_src, 1);
init_data(user_dst, -1);
init_data(user_wei, .5);
// set implementation ("naive"||"blocked"||"fused") setting implementation
// to "validation" will run all implementations
std::string implementation;
if (argc <= 2)
implementation = "validation";
else if (argc == 3)
implementation = argv[2];
if (!(implementation == "validation" || implementation == "naive"
|| implementation == "blocked" || implementation == "fused")) {
std::cout << "The implementation can be one of:\n";
std::cout << " - naive: NCHW format without fusion\n";
std::cout << " - blocked: format propagation without fusion\n";
std::cout << " - fused: format propagation with fusion\n";
std::cout << " - validation: runs all implementations\n\n";
std::cout << "Validation will run if no parameters are specified\n\n";
return -1;
}
if (implementation == "naive" || implementation == "validation") {
std::cout << "implementation: naive\n";
// run conv + relu w/o fusing
conv_relu_naive(user_src, user_wei, user_dst, eng, s);
std::cout << "conv + relu w/ nchw format completed\n";
}
if (implementation == "blocked" || implementation == "validation") {
std::cout << "implementation: blocked\n";
// run conv + relu w/o fusing
conv_relu_blocked(user_src, user_wei, user_dst, eng, s);
std::cout << "conv + relu w/ blocked format completed\n";
}
if (implementation == "fused" || implementation == "validation") {
std::cout << "implementation: fused\n";
// run conv + relu w/ fusing
conv_relu_fused(user_src, user_wei, user_dst, eng, s);
std::cout << "conv + relu w/ fusing completed\n";
}
return 0;
}
|
#include <iostream>
#include <list>
#include "ex01.h"
#include "ex02.h"
#include "ex03.h"
#include "ex04.h"
int main()
{
std::list<int> nb {1, 2, 3, 4, 5, 5, 4, 3, 2, 1};
std::cout << is_palindrome(nb.begin(), nb.end()) << std::endl;
return 0;
}
|
//
// Alert system
//
#include <algorithm>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/foreach.hpp>
#include <map>
#include "alert.h"
#include "key.h"
#include "net.h"
#include "sync.h"
#include "ui_interface.h"
using namespace std;
map<uint256, CAlert> mapAlerts;
CCriticalSection cs_mapAlerts;
static const char* pszMainKey = "040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9";
static const char* pszTestKey = "04b305cf3105c540b69c97df15ce5869927d6602c418d24059aefeef898a949311fd1215c27b27e2c0727a5fa005b5003fed95206b52780dca29c4269a8ce89c92";
void CUnsignedAlert::SetNull()
{
nVersion = 1;
nRelayUntil = 0;
nExpiration = 0;
nID = 0;
nCancel = 0;
setCancel.clear();
nMinVer = 0;
nMaxVer = 0;
setSubVer.clear();
nPriority = 0;
strComment.clear();
strStatusBar.clear();
strReserved.clear();
}
std::string CUnsignedAlert::ToString() const
{
std::string strSetCancel;
BOOST_FOREACH(int n, setCancel)
strSetCancel += strprintf("%d ", n);
std::string strSetSubVer;
BOOST_FOREACH(std::string str, setSubVer)
strSetSubVer += "\"" + str + "\" ";
return strprintf(
"CAlert(\n"
" nVersion = %d\n"
" nRelayUntil = %"PRI64d"\n"
" nExpiration = %"PRI64d"\n"
" nID = %d\n"
" nCancel = %d\n"
" setCancel = %s\n"
" nMinVer = %d\n"
" nMaxVer = %d\n"
" setSubVer = %s\n"
" nPriority = %d\n"
" strComment = \"%s\"\n"
" strStatusBar = \"%s\"\n"
")\n",
nVersion,
nRelayUntil,
nExpiration,
nID,
nCancel,
strSetCancel.c_str(),
nMinVer,
nMaxVer,
strSetSubVer.c_str(),
nPriority,
strComment.c_str(),
strStatusBar.c_str());
}
void CUnsignedAlert::print() const
{
printf("%s", ToString().c_str());
}
void CAlert::SetNull()
{
CUnsignedAlert::SetNull();
vchMsg.clear();
vchSig.clear();
}
bool CAlert::IsNull() const
{
return (nExpiration == 0);
}
uint256 CAlert::GetHash() const
{
return Hash(this->vchMsg.begin(), this->vchMsg.end());
}
bool CAlert::IsInEffect() const
{
return (GetAdjustedTime() < nExpiration);
}
bool CAlert::Cancels(const CAlert& alert) const
{
if (!IsInEffect())
return false; // this was a no-op before 31403
return (alert.nID <= nCancel || setCancel.count(alert.nID));
}
bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const
{
// TODO: rework for client-version-embedded-in-strSubVer ?
return (IsInEffect() &&
nMinVer <= nVersion && nVersion <= nMaxVer &&
(setSubVer.empty() || setSubVer.count(strSubVerIn)));
}
bool CAlert::AppliesToMe() const
{
return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
}
bool CAlert::RelayTo(CNode* pnode) const
{
if (!IsInEffect())
return false;
// returns true if wasn't already contained in the set
if (pnode->setKnown.insert(GetHash()).second)
{
if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
AppliesToMe() ||
GetAdjustedTime() < nRelayUntil)
{
pnode->PushMessage("alert", *this);
return true;
}
}
return false;
}
bool CAlert::CheckSignature() const
{
CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey));
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
return error("CAlert::CheckSignature() : verify signature failed");
// Now unserialize the data
CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
sMsg >> *(CUnsignedAlert*)this;
return true;
}
CAlert CAlert::getAlertByHash(const uint256 &hash)
{
CAlert retval;
{
LOCK(cs_mapAlerts);
map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
if(mi != mapAlerts.end())
retval = mi->second;
}
return retval;
}
bool CAlert::ProcessAlert(bool fThread)
{
if (!CheckSignature())
return false;
if (!IsInEffect())
return false;
// alert.nID=max is reserved for if the alert key is
// compromised. It must have a pre-defined message,
// must never expire, must apply to all versions,
// and must cancel all previous
// alerts or it will be ignored (so an attacker can't
// send an "everything is OK, don't panic" version that
// cannot be overridden):
int maxInt = std::numeric_limits<int>::max();
if (nID == maxInt)
{
if (!(
nExpiration == maxInt &&
nCancel == (maxInt-1) &&
nMinVer == 0 &&
nMaxVer == maxInt &&
setSubVer.empty() &&
nPriority == maxInt &&
strStatusBar == "URGENT: Alert key compromised, upgrade required"
))
return false;
}
{
LOCK(cs_mapAlerts);
// Cancel previous alerts
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
{
const CAlert& alert = (*mi).second;
if (Cancels(alert))
{
printf("cancelling alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
}
else if (!alert.IsInEffect())
{
printf("expiring alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
}
else
mi++;
}
// Check if this alert has been cancelled
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.Cancels(*this))
{
printf("alert already cancelled by %d\n", alert.nID);
return false;
}
}
// Add to mapAlerts
mapAlerts.insert(make_pair(GetHash(), *this));
// Notify UI and -alertnotify if it applies to me
if(AppliesToMe())
{
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
std::string strCmd = GetArg("-alertnotify", "");
if (!strCmd.empty())
{
// Alert text should be plain ascii coming from a trusted source, but to
// be safe we first strip anything not in safeChars, then add single quotes around
// the whole string before passing it to the shell:
std::string singleQuote("'");
std::string safeStatus = SanitizeString(strStatusBar);
safeStatus = singleQuote+safeStatus+singleQuote;
boost::replace_all(strCmd, "%s", safeStatus);
if (fThread)
boost::thread t(runCommand, strCmd); // thread runs free
else
runCommand(strCmd);
}
}
}
printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
return true;
}
|
/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIEF_OAT_ENUMS_H_
#define LIEF_OAT_ENUMS_H_
namespace LIEF {
namespace OAT {
enum OAT_CLASS_TYPES {
OAT_CLASS_ALL_COMPILED = 0, //! OatClass is followed by an OatMethodOffsets for each method.
OAT_CLASS_SOME_COMPILED = 1, //! A bitmap of which OatMethodOffsets are present follows the OatClass.
OAT_CLASS_NONE_COMPILED = 2, //! All methods are interpreted so no OatMethodOffsets are necessary.
};
// From art/runtime/mirror/class.h
enum OAT_CLASS_STATUS {
STATUS_RETIRED = -2, // Retired, should not be used. Use the newly cloned one instead.
STATUS_ERROR = -1,
STATUS_NOTREADY = 0,
STATUS_IDX = 1, // Loaded, DEX idx in super_class_type_idx_ and interfaces_type_idx_.
STATUS_LOADED = 2, // DEX idx values resolved.
STATUS_RESOLVING = 3, // Just cloned from temporary class object.
STATUS_RESOLVED = 4, // Part of linking.
STATUS_VERIFYING = 5, // In the process of being verified.
STATUS_RETRY_VERIFICATION_AT_RUNTIME = 6, // Compile time verification failed, retry at runtime.
STATUS_VERIFYING_AT_RUNTIME = 7, // Retrying verification at runtime.
STATUS_VERIFIED = 8, // Logically part of linking; done pre-init.
STATUS_INITIALIZING = 9, // Class init in progress.
STATUS_INITIALIZED = 10, // Ready to go.
};
enum HEADER_KEYS {
KEY_IMAGE_LOCATION = 0,
KEY_DEX2OAT_CMD_LINE = 1,
KEY_DEX2OAT_HOST = 2,
KEY_PIC = 3,
KEY_HAS_PATCH_INFO = 4,
KEY_DEBUGGABLE = 5,
KEY_NATIVE_DEBUGGABLE = 6,
KEY_COMPILER_FILTER = 7,
KEY_CLASS_PATH = 8,
KEY_BOOT_CLASS_PATH = 9,
KEY_CONCURRENT_COPYING = 10,
};
enum INSTRUCTION_SETS {
INST_SET_NONE = 0,
INST_SET_ARM = 1,
INST_SET_ARM_64 = 2,
INST_SET_THUMB2 = 3,
INST_SET_X86 = 4,
INST_SET_X86_64 = 5,
INST_SET_MIPS = 6,
INST_SET_MIPS_64 = 7,
};
static const HEADER_KEYS header_keys_list[] = {
HEADER_KEYS::KEY_IMAGE_LOCATION ,
HEADER_KEYS::KEY_DEX2OAT_CMD_LINE ,
HEADER_KEYS::KEY_DEX2OAT_HOST ,
HEADER_KEYS::KEY_PIC ,
HEADER_KEYS::KEY_HAS_PATCH_INFO ,
HEADER_KEYS::KEY_DEBUGGABLE ,
HEADER_KEYS::KEY_NATIVE_DEBUGGABLE ,
HEADER_KEYS::KEY_COMPILER_FILTER ,
HEADER_KEYS::KEY_CLASS_PATH ,
HEADER_KEYS::KEY_BOOT_CLASS_PATH ,
HEADER_KEYS::KEY_CONCURRENT_COPYING ,
};
}
}
#endif
|
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
#ifndef ROCKSDB_LITE
#ifdef GFLAGS
#include "tools/block_cache_analyzer/block_cache_trace_analyzer.h"
#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <random>
#include <sstream>
#include "monitoring/histogram.h"
#include "rocksdb/system_clock.h"
#include "rocksdb/trace_record.h"
#include "util/gflags_compat.h"
#include "util/string_util.h"
using GFLAGS_NAMESPACE::ParseCommandLineFlags;
DEFINE_string(block_cache_trace_path, "", "The trace file path.");
DEFINE_bool(is_block_cache_human_readable_trace, false,
"Is the trace file provided for analysis generated by running "
"block_cache_trace_analyzer with "
"FLAGS_human_readable_trace_file_path is specified.");
DEFINE_string(
block_cache_sim_config_path, "",
"The config file path. One cache configuration per line. The format of a "
"cache configuration is "
"cache_name,num_shard_bits,ghost_capacity,cache_capacity_1,...,cache_"
"capacity_N. Supported cache names are lru, lru_priority, lru_hybrid, and "
"lru_hybrid_no_insert_on_row_miss. User may also add a prefix 'ghost_' to "
"a cache_name to add a ghost cache in front of the real cache. "
"ghost_capacity and cache_capacity can be xK, xM or xG where x is a "
"positive number.");
DEFINE_int32(block_cache_trace_downsample_ratio, 1,
"The trace collected accesses on one in every "
"block_cache_trace_downsample_ratio blocks. We scale "
"down the simulated cache size by this ratio.");
DEFINE_bool(print_block_size_stats, false,
"Print block size distribution and the distribution break down by "
"block type and column family.");
DEFINE_bool(print_access_count_stats, false,
"Print access count distribution and the distribution break down "
"by block type and column family.");
DEFINE_bool(print_data_block_access_count_stats, false,
"Print data block accesses by user Get and Multi-Get.");
DEFINE_int32(cache_sim_warmup_seconds, 0,
"The number of seconds to warmup simulated caches. The hit/miss "
"counters are reset after the warmup completes.");
DEFINE_int32(analyze_bottom_k_access_count_blocks, 0,
"Print out detailed access information for blocks with their "
"number of accesses are the bottom k among all blocks.");
DEFINE_int32(analyze_top_k_access_count_blocks, 0,
"Print out detailed access information for blocks with their "
"number of accesses are the top k among all blocks.");
DEFINE_string(block_cache_analysis_result_dir, "",
"The directory that saves block cache analysis results.");
DEFINE_string(
timeline_labels, "",
"Group the number of accesses per block per second using these labels. "
"Possible labels are a combination of the following: cf (column family), "
"sst, level, bt (block type), caller, block. For example, label \"cf_bt\" "
"means the number of access per second is grouped by unique pairs of "
"\"cf_bt\". A label \"all\" contains the aggregated number of accesses per "
"second across all possible labels.");
DEFINE_string(reuse_distance_labels, "",
"Group the reuse distance of a block using these labels. Reuse "
"distance is defined as the cumulated size of unique blocks read "
"between two consecutive accesses on the same block.");
DEFINE_string(
reuse_distance_buckets, "",
"Group blocks by their reuse distances given these buckets. For "
"example, if 'reuse_distance_buckets' is '1K,1M,1G', we will "
"create four buckets. The first three buckets contain the number of "
"blocks with reuse distance less than 1KB, between 1K and 1M, between 1M "
"and 1G, respectively. The last bucket contains the number of blocks with "
"reuse distance larger than 1G. ");
DEFINE_string(
reuse_interval_labels, "",
"Group the reuse interval of a block using these labels. Reuse "
"interval is defined as the time between two consecutive accesses "
"on the same block.");
DEFINE_string(
reuse_interval_buckets, "",
"Group blocks by their reuse interval given these buckets. For "
"example, if 'reuse_distance_buckets' is '1,10,100', we will "
"create four buckets. The first three buckets contain the number of "
"blocks with reuse interval less than 1 second, between 1 second and 10 "
"seconds, between 10 seconds and 100 seconds, respectively. The last "
"bucket contains the number of blocks with reuse interval longer than 100 "
"seconds.");
DEFINE_string(
reuse_lifetime_labels, "",
"Group the reuse lifetime of a block using these labels. Reuse "
"lifetime is defined as the time interval between the first access on a "
"block and the last access on the same block. For blocks that are only "
"accessed once, its lifetime is set to kMaxUint64.");
DEFINE_string(
reuse_lifetime_buckets, "",
"Group blocks by their reuse lifetime given these buckets. For "
"example, if 'reuse_lifetime_buckets' is '1,10,100', we will "
"create four buckets. The first three buckets contain the number of "
"blocks with reuse lifetime less than 1 second, between 1 second and 10 "
"seconds, between 10 seconds and 100 seconds, respectively. The last "
"bucket contains the number of blocks with reuse lifetime longer than 100 "
"seconds.");
DEFINE_string(
analyze_callers, "",
"The list of callers to perform a detailed analysis on. If speicfied, the "
"analyzer will output a detailed percentage of accesses for each caller "
"break down by column family, level, and block type. A list of available "
"callers are: Get, MultiGet, Iterator, ApproximateSize, VerifyChecksum, "
"SSTDumpTool, ExternalSSTIngestion, Repair, Prefetch, Compaction, "
"CompactionRefill, Flush, SSTFileReader, Uncategorized.");
DEFINE_string(access_count_buckets, "",
"Group number of blocks by their access count given these "
"buckets. If specified, the analyzer will output a detailed "
"analysis on the number of blocks grouped by their access count "
"break down by block type and column family.");
DEFINE_int32(analyze_blocks_reuse_k_reuse_window, 0,
"Analyze the percentage of blocks that are accessed in the "
"[k, 2*k] seconds are accessed again in the next [2*k, 3*k], "
"[3*k, 4*k],...,[k*(n-1), k*n] seconds. ");
DEFINE_string(analyze_get_spatial_locality_labels, "",
"Group data blocks using these labels.");
DEFINE_string(analyze_get_spatial_locality_buckets, "",
"Group data blocks by their statistics using these buckets.");
DEFINE_string(skew_labels, "",
"Group the access count of a block using these labels.");
DEFINE_string(skew_buckets, "", "Group the skew labels using these buckets.");
DEFINE_bool(mrc_only, false,
"Evaluate alternative cache policies only. When this flag is true, "
"the analyzer does NOT maintain states of each block in memory for "
"analysis. It only feeds the accesses into the cache simulators.");
DEFINE_string(
analyze_correlation_coefficients_labels, "",
"Analyze the correlation coefficients of features such as number of past "
"accesses with regard to the number of accesses till the next access.");
DEFINE_int32(analyze_correlation_coefficients_max_number_of_values, 1000000,
"The maximum number of values for a feature. If the number of "
"values for a feature is larger than this max, it randomly "
"selects 'max' number of values.");
DEFINE_string(human_readable_trace_file_path, "",
"The filt path that saves human readable access records.");
namespace ROCKSDB_NAMESPACE {
namespace {
const std::string kMissRatioCurveFileName = "mrc";
const std::string kGroupbyBlock = "block";
const std::string kGroupbyTable = "table";
const std::string kGroupbyColumnFamily = "cf";
const std::string kGroupbySSTFile = "sst";
const std::string kGroupbyBlockType = "bt";
const std::string kGroupbyCaller = "caller";
const std::string kGroupbyLevel = "level";
const std::string kGroupbyAll = "all";
const std::set<std::string> kGroupbyLabels{
kGroupbyBlock, kGroupbyColumnFamily, kGroupbySSTFile, kGroupbyLevel,
kGroupbyBlockType, kGroupbyCaller, kGroupbyAll};
const std::string kSupportedCacheNames =
" lru ghost_lru lru_priority ghost_lru_priority lru_hybrid "
"ghost_lru_hybrid lru_hybrid_no_insert_on_row_miss "
"ghost_lru_hybrid_no_insert_on_row_miss ";
// The suffix for the generated csv files.
const std::string kFileNameSuffixMissRatioTimeline = "miss_ratio_timeline";
const std::string kFileNameSuffixMissTimeline = "miss_timeline";
const std::string kFileNameSuffixSkew = "skewness";
const std::string kFileNameSuffixAccessTimeline = "access_timeline";
const std::string kFileNameSuffixCorrelation = "correlation_input";
const std::string kFileNameSuffixAvgReuseIntervalNaccesses =
"avg_reuse_interval_naccesses";
const std::string kFileNameSuffixAvgReuseInterval = "avg_reuse_interval";
const std::string kFileNameSuffixReuseInterval = "access_reuse_interval";
const std::string kFileNameSuffixReuseLifetime = "reuse_lifetime";
const std::string kFileNameSuffixAccessReuseBlocksTimeline =
"reuse_blocks_timeline";
const std::string kFileNameSuffixPercentOfAccessSummary =
"percentage_of_accesses_summary";
const std::string kFileNameSuffixPercentRefKeys = "percent_ref_keys";
const std::string kFileNameSuffixPercentDataSizeOnRefKeys =
"percent_data_size_on_ref_keys";
const std::string kFileNameSuffixPercentAccessesOnRefKeys =
"percent_accesses_on_ref_keys";
const std::string kFileNameSuffixAccessCountSummary = "access_count_summary";
std::string block_type_to_string(TraceType type) {
switch (type) {
case kBlockTraceFilterBlock:
return "Filter";
case kBlockTraceDataBlock:
return "Data";
case kBlockTraceIndexBlock:
return "Index";
case kBlockTraceRangeDeletionBlock:
return "RangeDeletion";
case kBlockTraceUncompressionDictBlock:
return "UncompressionDict";
default:
break;
}
// This cannot happen.
return "InvalidType";
}
std::string caller_to_string(TableReaderCaller caller) {
switch (caller) {
case kUserGet:
return "Get";
case kUserMultiGet:
return "MultiGet";
case kUserIterator:
return "Iterator";
case kUserApproximateSize:
return "ApproximateSize";
case kUserVerifyChecksum:
return "VerifyChecksum";
case kSSTDumpTool:
return "SSTDumpTool";
case kExternalSSTIngestion:
return "ExternalSSTIngestion";
case kRepair:
return "Repair";
case kPrefetch:
return "Prefetch";
case kCompaction:
return "Compaction";
case kCompactionRefill:
return "CompactionRefill";
case kFlush:
return "Flush";
case kSSTFileReader:
return "SSTFileReader";
case kUncategorized:
return "Uncategorized";
default:
break;
}
// This cannot happen.
return "InvalidCaller";
}
TableReaderCaller string_to_caller(std::string caller_str) {
if (caller_str == "Get") {
return kUserGet;
} else if (caller_str == "MultiGet") {
return kUserMultiGet;
} else if (caller_str == "Iterator") {
return kUserIterator;
} else if (caller_str == "ApproximateSize") {
return kUserApproximateSize;
} else if (caller_str == "VerifyChecksum") {
return kUserVerifyChecksum;
} else if (caller_str == "SSTDumpTool") {
return kSSTDumpTool;
} else if (caller_str == "ExternalSSTIngestion") {
return kExternalSSTIngestion;
} else if (caller_str == "Repair") {
return kRepair;
} else if (caller_str == "Prefetch") {
return kPrefetch;
} else if (caller_str == "Compaction") {
return kCompaction;
} else if (caller_str == "CompactionRefill") {
return kCompactionRefill;
} else if (caller_str == "Flush") {
return kFlush;
} else if (caller_str == "SSTFileReader") {
return kSSTFileReader;
} else if (caller_str == "Uncategorized") {
return kUncategorized;
}
return TableReaderCaller::kMaxBlockCacheLookupCaller;
}
bool is_user_access(TableReaderCaller caller) {
switch (caller) {
case kUserGet:
case kUserMultiGet:
case kUserIterator:
case kUserApproximateSize:
case kUserVerifyChecksum:
return true;
default:
break;
}
return false;
}
const char kBreakLine[] =
"***************************************************************\n";
void print_break_lines(uint32_t num_break_lines) {
for (uint32_t i = 0; i < num_break_lines; i++) {
fprintf(stdout, kBreakLine);
}
}
double percent(uint64_t numerator, uint64_t denomenator) {
if (denomenator == 0) {
return -1;
}
return static_cast<double>(numerator * 100.0 / denomenator);
}
std::map<uint64_t, uint64_t> adjust_time_unit(
const std::map<uint64_t, uint64_t>& time_stats, uint64_t time_unit) {
if (time_unit == 1) {
return time_stats;
}
std::map<uint64_t, uint64_t> adjusted_time_stats;
for (auto const& time : time_stats) {
adjusted_time_stats[static_cast<uint64_t>(time.first / time_unit)] +=
time.second;
}
return adjusted_time_stats;
}
} // namespace
void BlockCacheTraceAnalyzer::WriteMissRatioCurves() const {
if (!cache_simulator_) {
return;
}
if (output_dir_.empty()) {
return;
}
uint64_t trace_duration =
trace_end_timestamp_in_seconds_ - trace_start_timestamp_in_seconds_;
uint64_t total_accesses = access_sequence_number_;
const std::string output_miss_ratio_curve_path =
output_dir_ + "/" + std::to_string(trace_duration) + "_" +
std::to_string(total_accesses) + "_" + kMissRatioCurveFileName;
std::ofstream out(output_miss_ratio_curve_path);
if (!out.is_open()) {
return;
}
// Write header.
const std::string header =
"cache_name,num_shard_bits,ghost_capacity,capacity,miss_ratio,total_"
"accesses";
out << header << std::endl;
for (auto const& config_caches : cache_simulator_->sim_caches()) {
const CacheConfiguration& config = config_caches.first;
for (uint32_t i = 0; i < config.cache_capacities.size(); i++) {
double miss_ratio =
config_caches.second[i]->miss_ratio_stats().miss_ratio();
// Write the body.
out << config.cache_name;
out << ",";
out << config.num_shard_bits;
out << ",";
out << config.ghost_cache_capacity;
out << ",";
out << config.cache_capacities[i];
out << ",";
out << std::fixed << std::setprecision(4) << miss_ratio;
out << ",";
out << config_caches.second[i]->miss_ratio_stats().total_accesses();
out << std::endl;
}
}
out.close();
}
void BlockCacheTraceAnalyzer::UpdateFeatureVectors(
const std::vector<uint64_t>& access_sequence_number_timeline,
const std::vector<uint64_t>& access_timeline, const std::string& label,
std::map<std::string, Features>* label_features,
std::map<std::string, Predictions>* label_predictions) const {
if (access_sequence_number_timeline.empty() || access_timeline.empty()) {
return;
}
assert(access_timeline.size() == access_sequence_number_timeline.size());
uint64_t prev_access_sequence_number = access_sequence_number_timeline[0];
uint64_t prev_access_timestamp = access_timeline[0];
for (uint32_t i = 0; i < access_sequence_number_timeline.size(); i++) {
uint64_t num_accesses_since_last_access =
access_sequence_number_timeline[i] - prev_access_sequence_number;
uint64_t elapsed_time_since_last_access =
access_timeline[i] - prev_access_timestamp;
prev_access_sequence_number = access_sequence_number_timeline[i];
prev_access_timestamp = access_timeline[i];
if (i < access_sequence_number_timeline.size() - 1) {
(*label_features)[label].num_accesses_since_last_access.push_back(
num_accesses_since_last_access);
(*label_features)[label].num_past_accesses.push_back(i);
(*label_features)[label].elapsed_time_since_last_access.push_back(
elapsed_time_since_last_access);
}
if (i >= 1) {
(*label_predictions)[label].num_accesses_till_next_access.push_back(
num_accesses_since_last_access);
(*label_predictions)[label].elapsed_time_till_next_access.push_back(
elapsed_time_since_last_access);
}
}
}
void BlockCacheTraceAnalyzer::WriteMissRatioTimeline(uint64_t time_unit) const {
if (!cache_simulator_ || output_dir_.empty()) {
return;
}
std::map<uint64_t, std::map<std::string, std::map<uint64_t, double>>>
cs_name_timeline;
uint64_t start_time = port::kMaxUint64;
uint64_t end_time = 0;
const std::map<uint64_t, uint64_t>& trace_num_misses =
adjust_time_unit(miss_ratio_stats_.num_misses_timeline(), time_unit);
const std::map<uint64_t, uint64_t>& trace_num_accesses =
adjust_time_unit(miss_ratio_stats_.num_accesses_timeline(), time_unit);
assert(trace_num_misses.size() == trace_num_accesses.size());
for (auto const& num_miss : trace_num_misses) {
uint64_t time = num_miss.first;
start_time = std::min(start_time, time);
end_time = std::max(end_time, time);
uint64_t miss = num_miss.second;
auto it = trace_num_accesses.find(time);
assert(it != trace_num_accesses.end());
uint64_t access = it->second;
cs_name_timeline[port::kMaxUint64]["trace"][time] = percent(miss, access);
}
for (auto const& config_caches : cache_simulator_->sim_caches()) {
const CacheConfiguration& config = config_caches.first;
std::string cache_label = config.cache_name + "-" +
std::to_string(config.num_shard_bits) + "-" +
std::to_string(config.ghost_cache_capacity);
for (uint32_t i = 0; i < config.cache_capacities.size(); i++) {
const std::map<uint64_t, uint64_t>& num_misses = adjust_time_unit(
config_caches.second[i]->miss_ratio_stats().num_misses_timeline(),
time_unit);
const std::map<uint64_t, uint64_t>& num_accesses = adjust_time_unit(
config_caches.second[i]->miss_ratio_stats().num_accesses_timeline(),
time_unit);
assert(num_misses.size() == num_accesses.size());
for (auto const& num_miss : num_misses) {
uint64_t time = num_miss.first;
start_time = std::min(start_time, time);
end_time = std::max(end_time, time);
uint64_t miss = num_miss.second;
auto it = num_accesses.find(time);
assert(it != num_accesses.end());
uint64_t access = it->second;
cs_name_timeline[config.cache_capacities[i]][cache_label][time] =
percent(miss, access);
}
}
}
for (auto const& it : cs_name_timeline) {
const std::string output_miss_ratio_timeline_path =
output_dir_ + "/" + std::to_string(it.first) + "_" +
std::to_string(time_unit) + "_" + kFileNameSuffixMissRatioTimeline;
std::ofstream out(output_miss_ratio_timeline_path);
if (!out.is_open()) {
return;
}
std::string header("time");
for (uint64_t now = start_time; now <= end_time; now++) {
header += ",";
header += std::to_string(now);
}
out << header << std::endl;
for (auto const& label : it.second) {
std::string row(label.first);
for (uint64_t now = start_time; now <= end_time; now++) {
auto misses = label.second.find(now);
row += ",";
if (misses != label.second.end()) {
row += std::to_string(misses->second);
} else {
row += "0";
}
}
out << row << std::endl;
}
out.close();
}
}
void BlockCacheTraceAnalyzer::WriteMissTimeline(uint64_t time_unit) const {
if (!cache_simulator_ || output_dir_.empty()) {
return;
}
std::map<uint64_t, std::map<std::string, std::map<uint64_t, uint64_t>>>
cs_name_timeline;
uint64_t start_time = port::kMaxUint64;
uint64_t end_time = 0;
const std::map<uint64_t, uint64_t>& trace_num_misses =
adjust_time_unit(miss_ratio_stats_.num_misses_timeline(), time_unit);
for (auto const& num_miss : trace_num_misses) {
uint64_t time = num_miss.first;
start_time = std::min(start_time, time);
end_time = std::max(end_time, time);
uint64_t miss = num_miss.second;
cs_name_timeline[port::kMaxUint64]["trace"][time] = miss;
}
for (auto const& config_caches : cache_simulator_->sim_caches()) {
const CacheConfiguration& config = config_caches.first;
std::string cache_label = config.cache_name + "-" +
std::to_string(config.num_shard_bits) + "-" +
std::to_string(config.ghost_cache_capacity);
for (uint32_t i = 0; i < config.cache_capacities.size(); i++) {
const std::map<uint64_t, uint64_t>& num_misses = adjust_time_unit(
config_caches.second[i]->miss_ratio_stats().num_misses_timeline(),
time_unit);
for (auto const& num_miss : num_misses) {
uint64_t time = num_miss.first;
start_time = std::min(start_time, time);
end_time = std::max(end_time, time);
uint64_t miss = num_miss.second;
cs_name_timeline[config.cache_capacities[i]][cache_label][time] = miss;
}
}
}
for (auto const& it : cs_name_timeline) {
const std::string output_miss_ratio_timeline_path =
output_dir_ + "/" + std::to_string(it.first) + "_" +
std::to_string(time_unit) + "_" + kFileNameSuffixMissTimeline;
std::ofstream out(output_miss_ratio_timeline_path);
if (!out.is_open()) {
return;
}
std::string header("time");
for (uint64_t now = start_time; now <= end_time; now++) {
header += ",";
header += std::to_string(now);
}
out << header << std::endl;
for (auto const& label : it.second) {
std::string row(label.first);
for (uint64_t now = start_time; now <= end_time; now++) {
auto misses = label.second.find(now);
row += ",";
if (misses != label.second.end()) {
row += std::to_string(misses->second);
} else {
row += "0";
}
}
out << row << std::endl;
}
out.close();
}
}
void BlockCacheTraceAnalyzer::WriteSkewness(
const std::string& label_str, const std::vector<uint64_t>& percent_buckets,
TraceType target_block_type) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, uint64_t> label_naccesses;
uint64_t total_naccesses = 0;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType type,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
if (target_block_type != TraceType::kTraceMax &&
target_block_type != type) {
return;
}
const std::string label = BuildLabel(
labels, cf_name, fd, level, type,
TableReaderCaller::kMaxBlockCacheLookupCaller, block_id, block);
label_naccesses[label] += block.num_accesses;
total_naccesses += block.num_accesses;
};
TraverseBlocks(block_callback, &labels);
std::map<std::string, std::map<uint64_t, uint64_t>> label_bucket_naccesses;
std::vector<std::pair<std::string, uint64_t>> pairs;
for (auto const& itr : label_naccesses) {
pairs.push_back(itr);
}
// Sort in descending order.
sort(pairs.begin(), pairs.end(),
[](const std::pair<std::string, uint64_t>& a,
const std::pair<std::string, uint64_t>& b) {
return b.second < a.second;
});
size_t prev_start_index = 0;
for (auto const& percent : percent_buckets) {
label_bucket_naccesses[label_str][percent] = 0;
size_t end_index = 0;
if (percent == port::kMaxUint64) {
end_index = label_naccesses.size();
} else {
end_index = percent * label_naccesses.size() / 100;
}
for (size_t i = prev_start_index; i < end_index; i++) {
label_bucket_naccesses[label_str][percent] += pairs[i].second;
}
prev_start_index = end_index;
}
std::string filename_suffix;
if (target_block_type != TraceType::kTraceMax) {
filename_suffix = block_type_to_string(target_block_type);
filename_suffix += "_";
}
filename_suffix += kFileNameSuffixSkew;
WriteStatsToFile(label_str, percent_buckets, filename_suffix,
label_bucket_naccesses, total_naccesses);
}
void BlockCacheTraceAnalyzer::WriteCorrelationFeatures(
const std::string& label_str, uint32_t max_number_of_values) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, Features> label_features;
std::map<std::string, Predictions> label_predictions;
auto block_callback =
[&](const std::string& cf_name, uint64_t fd, uint32_t level,
TraceType block_type, const std::string& /*block_key*/,
uint64_t /*block_key_id*/, const BlockAccessInfo& block) {
if (block.table_id == 0 && labels.find(kGroupbyTable) != labels.end()) {
// We only know table id information for get requests.
return;
}
if (labels.find(kGroupbyCaller) != labels.end()) {
// Group by caller.
for (auto const& caller_map : block.caller_access_timeline) {
const std::string label =
BuildLabel(labels, cf_name, fd, level, block_type,
caller_map.first, /*block_id=*/0, block);
auto it = block.caller_access_sequence__number_timeline.find(
caller_map.first);
assert(it != block.caller_access_sequence__number_timeline.end());
UpdateFeatureVectors(it->second, caller_map.second, label,
&label_features, &label_predictions);
}
return;
}
const std::string label =
BuildLabel(labels, cf_name, fd, level, block_type,
TableReaderCaller::kMaxBlockCacheLookupCaller,
/*block_id=*/0, block);
UpdateFeatureVectors(block.access_sequence_number_timeline,
block.access_timeline, label, &label_features,
&label_predictions);
};
TraverseBlocks(block_callback, &labels);
WriteCorrelationFeaturesToFile(label_str, label_features, label_predictions,
max_number_of_values);
}
void BlockCacheTraceAnalyzer::WriteCorrelationFeaturesToFile(
const std::string& label,
const std::map<std::string, Features>& label_features,
const std::map<std::string, Predictions>& label_predictions,
uint32_t max_number_of_values) const {
for (auto const& label_feature_vectors : label_features) {
const Features& past = label_feature_vectors.second;
auto it = label_predictions.find(label_feature_vectors.first);
assert(it != label_predictions.end());
const Predictions& future = it->second;
const std::string output_path = output_dir_ + "/" + label + "_" +
label_feature_vectors.first + "_" +
kFileNameSuffixCorrelation;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header(
"num_accesses_since_last_access,elapsed_time_since_last_access,num_"
"past_accesses,num_accesses_till_next_access,elapsed_time_till_next_"
"access");
out << header << std::endl;
std::vector<uint32_t> indexes;
for (uint32_t i = 0; i < past.num_accesses_since_last_access.size(); i++) {
indexes.push_back(i);
}
RandomShuffle(indexes.begin(), indexes.end());
for (uint32_t i = 0; i < max_number_of_values && i < indexes.size(); i++) {
uint32_t rand_index = indexes[i];
out << std::to_string(past.num_accesses_since_last_access[rand_index])
<< ",";
out << std::to_string(past.elapsed_time_since_last_access[rand_index])
<< ",";
out << std::to_string(past.num_past_accesses[rand_index]) << ",";
out << std::to_string(future.num_accesses_till_next_access[rand_index])
<< ",";
out << std::to_string(future.elapsed_time_till_next_access[rand_index])
<< std::endl;
}
out.close();
}
}
void BlockCacheTraceAnalyzer::WriteCorrelationFeaturesForGet(
uint32_t max_number_of_values) const {
std::string label = "GetKeyInfo";
std::map<std::string, Features> label_features;
std::map<std::string, Predictions> label_predictions;
for (auto const& get_info : get_key_info_map_) {
const GetKeyInfo& info = get_info.second;
UpdateFeatureVectors(info.access_sequence_number_timeline,
info.access_timeline, label, &label_features,
&label_predictions);
}
WriteCorrelationFeaturesToFile(label, label_features, label_predictions,
max_number_of_values);
}
std::set<std::string> BlockCacheTraceAnalyzer::ParseLabelStr(
const std::string& label_str) const {
std::stringstream ss(label_str);
std::set<std::string> labels;
// label_str is in the form of "label1_label2_label3", e.g., cf_bt.
while (ss.good()) {
std::string label_name;
getline(ss, label_name, '_');
if (kGroupbyLabels.find(label_name) == kGroupbyLabels.end()) {
// Unknown label name.
fprintf(stderr, "Unknown label name %s, label string %s\n",
label_name.c_str(), label_str.c_str());
return {};
}
labels.insert(label_name);
}
return labels;
}
std::string BlockCacheTraceAnalyzer::BuildLabel(
const std::set<std::string>& labels, const std::string& cf_name,
uint64_t fd, uint32_t level, TraceType type, TableReaderCaller caller,
uint64_t block_key, const BlockAccessInfo& block) const {
std::map<std::string, std::string> label_value_map;
label_value_map[kGroupbyAll] = kGroupbyAll;
label_value_map[kGroupbyLevel] = std::to_string(level);
label_value_map[kGroupbyCaller] = caller_to_string(caller);
label_value_map[kGroupbySSTFile] = std::to_string(fd);
label_value_map[kGroupbyBlockType] = block_type_to_string(type);
label_value_map[kGroupbyColumnFamily] = cf_name;
label_value_map[kGroupbyBlock] = std::to_string(block_key);
label_value_map[kGroupbyTable] = std::to_string(block.table_id);
// Concatenate the label values.
std::string label;
for (auto const& l : labels) {
label += label_value_map[l];
label += "-";
}
if (!label.empty()) {
label.pop_back();
}
return label;
}
void BlockCacheTraceAnalyzer::TraverseBlocks(
std::function<void(const std::string& /*cf_name*/, uint64_t /*fd*/,
uint32_t /*level*/, TraceType /*block_type*/,
const std::string& /*block_key*/,
uint64_t /*block_key_id*/,
const BlockAccessInfo& /*block_access_info*/)>
block_callback,
std::set<std::string>* labels) const {
for (auto const& cf_aggregates : cf_aggregates_map_) {
// Stats per column family.
const std::string& cf_name = cf_aggregates.first;
for (auto const& file_aggregates : cf_aggregates.second.fd_aggregates_map) {
// Stats per SST file.
const uint64_t fd = file_aggregates.first;
const uint32_t level = file_aggregates.second.level;
for (auto const& block_type_aggregates :
file_aggregates.second.block_type_aggregates_map) {
// Stats per block type.
const TraceType type = block_type_aggregates.first;
for (auto const& block_access_info :
block_type_aggregates.second.block_access_info_map) {
// Stats per block.
if (labels && block_access_info.second.table_id == 0 &&
labels->find(kGroupbyTable) != labels->end()) {
// We only know table id information for get requests.
return;
}
block_callback(cf_name, fd, level, type, block_access_info.first,
block_access_info.second.block_id,
block_access_info.second);
}
}
}
}
}
void BlockCacheTraceAnalyzer::WriteGetSpatialLocality(
const std::string& label_str,
const std::vector<uint64_t>& percent_buckets) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, std::map<uint64_t, uint64_t>> label_pnrefkeys_nblocks;
std::map<std::string, std::map<uint64_t, uint64_t>> label_pnrefs_nblocks;
std::map<std::string, std::map<uint64_t, uint64_t>> label_pndatasize_nblocks;
uint64_t nblocks = 0;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType /*block_type*/,
const std::string& /*block_key*/,
uint64_t /*block_key_id*/,
const BlockAccessInfo& block) {
if (block.num_keys == 0) {
return;
}
uint64_t naccesses = 0;
for (auto const& key_access : block.key_num_access_map) {
for (auto const& caller_access : key_access.second) {
if (caller_access.first == TableReaderCaller::kUserGet) {
naccesses += caller_access.second;
}
}
}
const std::string label =
BuildLabel(labels, cf_name, fd, level, TraceType::kBlockTraceDataBlock,
TableReaderCaller::kUserGet, /*block_id=*/0, block);
const uint64_t percent_referenced_for_existing_keys =
static_cast<uint64_t>(std::max(
percent(block.key_num_access_map.size(), block.num_keys), 0.0));
const uint64_t percent_accesses_for_existing_keys =
static_cast<uint64_t>(std::max(
percent(block.num_referenced_key_exist_in_block, naccesses), 0.0));
const uint64_t percent_referenced_data_size = static_cast<uint64_t>(
std::max(percent(block.referenced_data_size, block.block_size), 0.0));
if (label_pnrefkeys_nblocks.find(label) == label_pnrefkeys_nblocks.end()) {
for (auto const& percent_bucket : percent_buckets) {
label_pnrefkeys_nblocks[label][percent_bucket] = 0;
label_pnrefs_nblocks[label][percent_bucket] = 0;
label_pndatasize_nblocks[label][percent_bucket] = 0;
}
}
label_pnrefkeys_nblocks[label]
.upper_bound(percent_referenced_for_existing_keys)
->second += 1;
label_pnrefs_nblocks[label]
.upper_bound(percent_accesses_for_existing_keys)
->second += 1;
label_pndatasize_nblocks[label]
.upper_bound(percent_referenced_data_size)
->second += 1;
nblocks += 1;
};
TraverseBlocks(block_callback, &labels);
WriteStatsToFile(label_str, percent_buckets, kFileNameSuffixPercentRefKeys,
label_pnrefkeys_nblocks, nblocks);
WriteStatsToFile(label_str, percent_buckets,
kFileNameSuffixPercentAccessesOnRefKeys,
label_pnrefs_nblocks, nblocks);
WriteStatsToFile(label_str, percent_buckets,
kFileNameSuffixPercentDataSizeOnRefKeys,
label_pndatasize_nblocks, nblocks);
}
void BlockCacheTraceAnalyzer::WriteAccessTimeline(const std::string& label_str,
uint64_t time_unit,
bool user_access_only) const {
std::set<std::string> labels = ParseLabelStr(label_str);
uint64_t start_time = port::kMaxUint64;
uint64_t end_time = 0;
std::map<std::string, std::map<uint64_t, uint64_t>> label_access_timeline;
std::map<uint64_t, std::vector<std::string>> access_count_block_id_map;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType type,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
uint64_t naccesses = 0;
for (auto const& timeline : block.caller_num_accesses_timeline) {
const TableReaderCaller caller = timeline.first;
if (user_access_only && !is_user_access(caller)) {
continue;
}
const std::string label =
BuildLabel(labels, cf_name, fd, level, type, caller, block_id, block);
for (auto const& naccess : timeline.second) {
const uint64_t timestamp = naccess.first / time_unit;
const uint64_t num = naccess.second;
label_access_timeline[label][timestamp] += num;
start_time = std::min(start_time, timestamp);
end_time = std::max(end_time, timestamp);
naccesses += num;
}
}
if (naccesses > 0) {
access_count_block_id_map[naccesses].push_back(std::to_string(block_id));
}
};
TraverseBlocks(block_callback, &labels);
// We have label_access_timeline now. Write them into a file.
const std::string user_access_prefix =
user_access_only ? "user_access_only_" : "all_access_";
const std::string output_path = output_dir_ + "/" + user_access_prefix +
label_str + "_" + std::to_string(time_unit) +
"_" + kFileNameSuffixAccessTimeline;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("time");
if (labels.find("block") != labels.end()) {
for (uint64_t now = start_time; now <= end_time; now++) {
header += ",";
header += std::to_string(now);
}
out << header << std::endl;
// Write the most frequently accessed blocks first.
for (auto naccess_it = access_count_block_id_map.rbegin();
naccess_it != access_count_block_id_map.rend(); naccess_it++) {
for (auto& block_id_it : naccess_it->second) {
std::string row(block_id_it);
for (uint64_t now = start_time; now <= end_time; now++) {
auto it = label_access_timeline[block_id_it].find(now);
row += ",";
if (it != label_access_timeline[block_id_it].end()) {
row += std::to_string(it->second);
} else {
row += "0";
}
}
out << row << std::endl;
}
}
out.close();
return;
}
for (uint64_t now = start_time; now <= end_time; now++) {
header += ",";
header += std::to_string(now);
}
out << header << std::endl;
for (auto const& label : label_access_timeline) {
std::string row(label.first);
for (uint64_t now = start_time; now <= end_time; now++) {
auto it = label.second.find(now);
row += ",";
if (it != label.second.end()) {
row += std::to_string(it->second);
} else {
row += "0";
}
}
out << row << std::endl;
}
out.close();
}
void BlockCacheTraceAnalyzer::WriteReuseDistance(
const std::string& label_str,
const std::vector<uint64_t>& distance_buckets) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, std::map<uint64_t, uint64_t>> label_distance_num_reuses;
uint64_t total_num_reuses = 0;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType type,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
const std::string label = BuildLabel(
labels, cf_name, fd, level, type,
TableReaderCaller::kMaxBlockCacheLookupCaller, block_id, block);
if (label_distance_num_reuses.find(label) ==
label_distance_num_reuses.end()) {
// The first time we encounter this label.
for (auto const& distance_bucket : distance_buckets) {
label_distance_num_reuses[label][distance_bucket] = 0;
}
}
for (auto const& reuse_distance : block.reuse_distance_count) {
label_distance_num_reuses[label]
.upper_bound(reuse_distance.first)
->second += reuse_distance.second;
total_num_reuses += reuse_distance.second;
}
};
TraverseBlocks(block_callback, &labels);
// We have label_naccesses and label_distance_num_reuses now. Write them into
// a file.
const std::string output_path =
output_dir_ + "/" + label_str + "_reuse_distance";
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("bucket");
for (auto const& label_it : label_distance_num_reuses) {
header += ",";
header += label_it.first;
}
out << header << std::endl;
for (auto const& bucket : distance_buckets) {
std::string row(std::to_string(bucket));
for (auto const& label_it : label_distance_num_reuses) {
auto const& it = label_it.second.find(bucket);
assert(it != label_it.second.end());
row += ",";
row += std::to_string(percent(it->second, total_num_reuses));
}
out << row << std::endl;
}
out.close();
}
void BlockCacheTraceAnalyzer::UpdateReuseIntervalStats(
const std::string& label, const std::vector<uint64_t>& time_buckets,
const std::map<uint64_t, uint64_t> timeline,
std::map<std::string, std::map<uint64_t, uint64_t>>* label_time_num_reuses,
uint64_t* total_num_reuses) const {
assert(label_time_num_reuses);
assert(total_num_reuses);
if (label_time_num_reuses->find(label) == label_time_num_reuses->end()) {
// The first time we encounter this label.
for (auto const& time_bucket : time_buckets) {
(*label_time_num_reuses)[label][time_bucket] = 0;
}
}
auto it = timeline.begin();
uint64_t prev_timestamp = it->first;
const uint64_t prev_num = it->second;
it++;
// Reused within one second.
if (prev_num > 1) {
(*label_time_num_reuses)[label].upper_bound(0)->second += prev_num - 1;
*total_num_reuses += prev_num - 1;
}
while (it != timeline.end()) {
const uint64_t timestamp = it->first;
const uint64_t num = it->second;
const uint64_t reuse_interval = timestamp - prev_timestamp;
(*label_time_num_reuses)[label].upper_bound(reuse_interval)->second += 1;
if (num > 1) {
(*label_time_num_reuses)[label].upper_bound(0)->second += num - 1;
}
prev_timestamp = timestamp;
*total_num_reuses += num;
it++;
}
}
void BlockCacheTraceAnalyzer::WriteStatsToFile(
const std::string& label_str, const std::vector<uint64_t>& time_buckets,
const std::string& filename_suffix,
const std::map<std::string, std::map<uint64_t, uint64_t>>& label_data,
uint64_t ntotal) const {
const std::string output_path =
output_dir_ + "/" + label_str + "_" + filename_suffix;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("bucket");
for (auto const& label_it : label_data) {
header += ",";
header += label_it.first;
}
out << header << std::endl;
for (auto const& bucket : time_buckets) {
std::string row(std::to_string(bucket));
for (auto const& label_it : label_data) {
auto const& it = label_it.second.find(bucket);
assert(it != label_it.second.end());
row += ",";
row += std::to_string(percent(it->second, ntotal));
}
out << row << std::endl;
}
out.close();
}
void BlockCacheTraceAnalyzer::WriteReuseInterval(
const std::string& label_str,
const std::vector<uint64_t>& time_buckets) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, std::map<uint64_t, uint64_t>> label_time_num_reuses;
std::map<std::string, std::map<uint64_t, uint64_t>> label_avg_reuse_nblocks;
std::map<std::string, std::map<uint64_t, uint64_t>> label_avg_reuse_naccesses;
uint64_t total_num_reuses = 0;
uint64_t total_nblocks = 0;
uint64_t total_accesses = 0;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType type,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
total_nblocks++;
total_accesses += block.num_accesses;
uint64_t avg_reuse_interval = 0;
if (block.num_accesses > 1) {
avg_reuse_interval = ((block.last_access_time - block.first_access_time) /
kMicrosInSecond) /
block.num_accesses;
} else {
avg_reuse_interval = port::kMaxUint64 - 1;
}
if (labels.find(kGroupbyCaller) != labels.end()) {
for (auto const& timeline : block.caller_num_accesses_timeline) {
const TableReaderCaller caller = timeline.first;
const std::string label = BuildLabel(labels, cf_name, fd, level, type,
caller, block_id, block);
UpdateReuseIntervalStats(label, time_buckets, timeline.second,
&label_time_num_reuses, &total_num_reuses);
}
return;
}
// Does not group by caller so we need to flatten the access timeline.
const std::string label = BuildLabel(
labels, cf_name, fd, level, type,
TableReaderCaller::kMaxBlockCacheLookupCaller, block_id, block);
std::map<uint64_t, uint64_t> timeline;
for (auto const& caller_timeline : block.caller_num_accesses_timeline) {
for (auto const& time_naccess : caller_timeline.second) {
timeline[time_naccess.first] += time_naccess.second;
}
}
UpdateReuseIntervalStats(label, time_buckets, timeline,
&label_time_num_reuses, &total_num_reuses);
if (label_avg_reuse_nblocks.find(label) == label_avg_reuse_nblocks.end()) {
for (auto const& time_bucket : time_buckets) {
label_avg_reuse_nblocks[label][time_bucket] = 0;
label_avg_reuse_naccesses[label][time_bucket] = 0;
}
}
label_avg_reuse_nblocks[label].upper_bound(avg_reuse_interval)->second += 1;
label_avg_reuse_naccesses[label].upper_bound(avg_reuse_interval)->second +=
block.num_accesses;
};
TraverseBlocks(block_callback, &labels);
// Write the stats into files.
WriteStatsToFile(label_str, time_buckets, kFileNameSuffixReuseInterval,
label_time_num_reuses, total_num_reuses);
WriteStatsToFile(label_str, time_buckets, kFileNameSuffixAvgReuseInterval,
label_avg_reuse_nblocks, total_nblocks);
WriteStatsToFile(label_str, time_buckets,
kFileNameSuffixAvgReuseIntervalNaccesses,
label_avg_reuse_naccesses, total_accesses);
}
void BlockCacheTraceAnalyzer::WriteReuseLifetime(
const std::string& label_str,
const std::vector<uint64_t>& time_buckets) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, std::map<uint64_t, uint64_t>> label_lifetime_nblocks;
uint64_t total_nblocks = 0;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType type,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
uint64_t lifetime = 0;
if (block.num_accesses > 1) {
lifetime =
(block.last_access_time - block.first_access_time) / kMicrosInSecond;
} else {
lifetime = port::kMaxUint64 - 1;
}
const std::string label = BuildLabel(
labels, cf_name, fd, level, type,
TableReaderCaller::kMaxBlockCacheLookupCaller, block_id, block);
if (label_lifetime_nblocks.find(label) == label_lifetime_nblocks.end()) {
// The first time we encounter this label.
for (auto const& time_bucket : time_buckets) {
label_lifetime_nblocks[label][time_bucket] = 0;
}
}
label_lifetime_nblocks[label].upper_bound(lifetime)->second += 1;
total_nblocks += 1;
};
TraverseBlocks(block_callback, &labels);
WriteStatsToFile(label_str, time_buckets, kFileNameSuffixReuseLifetime,
label_lifetime_nblocks, total_nblocks);
}
void BlockCacheTraceAnalyzer::WriteBlockReuseTimeline(
const uint64_t reuse_window, bool user_access_only, TraceType block_type) const {
// A map from block key to an array of bools that states whether a block is
// accessed in a time window.
std::map<uint64_t, std::vector<bool>> block_accessed;
const uint64_t trace_duration =
trace_end_timestamp_in_seconds_ - trace_start_timestamp_in_seconds_;
const uint64_t reuse_vector_size = (trace_duration / reuse_window);
if (reuse_vector_size < 2) {
// The reuse window is less than 2. We cannot calculate the reused
// percentage of blocks.
return;
}
auto block_callback = [&](const std::string& /*cf_name*/, uint64_t /*fd*/,
uint32_t /*level*/, TraceType /*type*/,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
if (block_accessed.find(block_id) == block_accessed.end()) {
block_accessed[block_id].resize(reuse_vector_size);
for (uint64_t i = 0; i < reuse_vector_size; i++) {
block_accessed[block_id][i] = false;
}
}
for (auto const& caller_num : block.caller_num_accesses_timeline) {
const TableReaderCaller caller = caller_num.first;
for (auto const& timeline : caller_num.second) {
const uint64_t timestamp = timeline.first;
const uint64_t elapsed_time =
timestamp - trace_start_timestamp_in_seconds_;
if (!user_access_only || is_user_access(caller)) {
uint64_t index =
std::min(elapsed_time / reuse_window, reuse_vector_size - 1);
block_accessed[block_id][index] = true;
}
}
}
};
TraverseBlocks(block_callback);
// A cell is the number of blocks accessed in a reuse window.
std::unique_ptr<uint64_t[]> reuse_table(new uint64_t[reuse_vector_size * reuse_vector_size]);
for (uint64_t start_time = 0; start_time < reuse_vector_size; start_time++) {
// Initialize the reuse_table.
for (uint64_t i = 0; i < reuse_vector_size; i++) {
reuse_table[start_time * reuse_vector_size + i] = 0;
}
// Examine all blocks.
for (auto const& block : block_accessed) {
for (uint64_t i = start_time; i < reuse_vector_size; i++) {
if (block.second[start_time] && block.second[i]) {
// This block is accessed at start time and at the current time. We
// increment reuse_table[start_time][i] since it is reused at the ith
// window.
reuse_table[start_time * reuse_vector_size + i]++;
}
}
}
}
const std::string user_access_prefix =
user_access_only ? "_user_access_only_" : "_all_access_";
const std::string output_path =
output_dir_ + "/" + block_type_to_string(block_type) +
user_access_prefix + std::to_string(reuse_window) + "_" +
kFileNameSuffixAccessReuseBlocksTimeline;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("start_time");
for (uint64_t start_time = 0; start_time < reuse_vector_size; start_time++) {
header += ",";
header += std::to_string(start_time);
}
out << header << std::endl;
for (uint64_t start_time = 0; start_time < reuse_vector_size; start_time++) {
std::string row(std::to_string(start_time * reuse_window));
for (uint64_t j = 0; j < reuse_vector_size; j++) {
row += ",";
if (j < start_time) {
row += "100.0";
} else {
row += std::to_string(percent(reuse_table[start_time * reuse_vector_size + j],
reuse_table[start_time * reuse_vector_size + start_time]));
}
}
out << row << std::endl;
}
out.close();
}
std::string BlockCacheTraceAnalyzer::OutputPercentAccessStats(
uint64_t total_accesses,
const std::map<std::string, uint64_t>& cf_access_count) const {
std::string row;
for (auto const& cf_aggregates : cf_aggregates_map_) {
const std::string& cf_name = cf_aggregates.first;
const auto& naccess = cf_access_count.find(cf_name);
row += ",";
if (naccess != cf_access_count.end()) {
row += std::to_string(percent(naccess->second, total_accesses));
} else {
row += "0";
}
}
return row;
}
void BlockCacheTraceAnalyzer::WritePercentAccessSummaryStats() const {
std::map<TableReaderCaller, std::map<std::string, uint64_t>>
caller_cf_accesses;
uint64_t total_accesses = 0;
auto block_callback =
[&](const std::string& cf_name, uint64_t /*fd*/, uint32_t /*level*/,
TraceType /*type*/, const std::string& /*block_key*/,
uint64_t /*block_id*/, const BlockAccessInfo& block) {
for (auto const& caller_num : block.caller_num_access_map) {
const TableReaderCaller caller = caller_num.first;
const uint64_t naccess = caller_num.second;
caller_cf_accesses[caller][cf_name] += naccess;
total_accesses += naccess;
}
};
TraverseBlocks(block_callback);
const std::string output_path =
output_dir_ + "/" + kFileNameSuffixPercentOfAccessSummary;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("caller");
for (auto const& cf_name : cf_aggregates_map_) {
header += ",";
header += cf_name.first;
}
out << header << std::endl;
for (auto const& cf_naccess_it : caller_cf_accesses) {
const TableReaderCaller caller = cf_naccess_it.first;
std::string row;
row += caller_to_string(caller);
row += OutputPercentAccessStats(total_accesses, cf_naccess_it.second);
out << row << std::endl;
}
out.close();
}
void BlockCacheTraceAnalyzer::WriteDetailedPercentAccessSummaryStats(
TableReaderCaller analyzing_caller) const {
std::map<uint32_t, std::map<std::string, uint64_t>> level_cf_accesses;
std::map<TraceType, std::map<std::string, uint64_t>> bt_cf_accesses;
uint64_t total_accesses = 0;
auto block_callback =
[&](const std::string& cf_name, uint64_t /*fd*/, uint32_t level,
TraceType type, const std::string& /*block_key*/,
uint64_t /*block_id*/, const BlockAccessInfo& block) {
for (auto const& caller_num : block.caller_num_access_map) {
const TableReaderCaller caller = caller_num.first;
if (caller == analyzing_caller) {
const uint64_t naccess = caller_num.second;
level_cf_accesses[level][cf_name] += naccess;
bt_cf_accesses[type][cf_name] += naccess;
total_accesses += naccess;
}
}
};
TraverseBlocks(block_callback);
{
const std::string output_path =
output_dir_ + "/" + caller_to_string(analyzing_caller) + "_level_" +
kFileNameSuffixPercentOfAccessSummary;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("level");
for (auto const& cf_name : cf_aggregates_map_) {
header += ",";
header += cf_name.first;
}
out << header << std::endl;
for (auto const& level_naccess_it : level_cf_accesses) {
const uint32_t level = level_naccess_it.first;
std::string row;
row += std::to_string(level);
row += OutputPercentAccessStats(total_accesses, level_naccess_it.second);
out << row << std::endl;
}
out.close();
}
{
const std::string output_path =
output_dir_ + "/" + caller_to_string(analyzing_caller) + "_bt_" +
kFileNameSuffixPercentOfAccessSummary;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("bt");
for (auto const& cf_name : cf_aggregates_map_) {
header += ",";
header += cf_name.first;
}
out << header << std::endl;
for (auto const& bt_naccess_it : bt_cf_accesses) {
const TraceType bt = bt_naccess_it.first;
std::string row;
row += block_type_to_string(bt);
row += OutputPercentAccessStats(total_accesses, bt_naccess_it.second);
out << row << std::endl;
}
out.close();
}
}
void BlockCacheTraceAnalyzer::WriteAccessCountSummaryStats(
const std::vector<uint64_t>& access_count_buckets,
bool user_access_only) const {
// x: buckets.
// y: # of accesses.
std::map<std::string, std::map<uint64_t, uint64_t>> bt_access_nblocks;
std::map<std::string, std::map<uint64_t, uint64_t>> cf_access_nblocks;
uint64_t total_nblocks = 0;
auto block_callback =
[&](const std::string& cf_name, uint64_t /*fd*/, uint32_t /*level*/,
TraceType type, const std::string& /*block_key*/,
uint64_t /*block_id*/, const BlockAccessInfo& block) {
const std::string type_str = block_type_to_string(type);
if (cf_access_nblocks.find(cf_name) == cf_access_nblocks.end()) {
// initialize.
for (auto& access : access_count_buckets) {
cf_access_nblocks[cf_name][access] = 0;
}
}
if (bt_access_nblocks.find(type_str) == bt_access_nblocks.end()) {
// initialize.
for (auto& access : access_count_buckets) {
bt_access_nblocks[type_str][access] = 0;
}
}
uint64_t naccesses = 0;
for (auto const& caller_access : block.caller_num_access_map) {
if (!user_access_only || is_user_access(caller_access.first)) {
naccesses += caller_access.second;
}
}
if (naccesses == 0) {
return;
}
total_nblocks += 1;
bt_access_nblocks[type_str].upper_bound(naccesses)->second += 1;
cf_access_nblocks[cf_name].upper_bound(naccesses)->second += 1;
};
TraverseBlocks(block_callback);
const std::string user_access_prefix =
user_access_only ? "user_access_only_" : "all_access_";
WriteStatsToFile("cf", access_count_buckets,
user_access_prefix + kFileNameSuffixAccessCountSummary,
cf_access_nblocks, total_nblocks);
WriteStatsToFile("bt", access_count_buckets,
user_access_prefix + kFileNameSuffixAccessCountSummary,
bt_access_nblocks, total_nblocks);
}
BlockCacheTraceAnalyzer::BlockCacheTraceAnalyzer(
const std::string& trace_file_path, const std::string& output_dir,
const std::string& human_readable_trace_file_path,
bool compute_reuse_distance, bool mrc_only,
bool is_human_readable_trace_file,
std::unique_ptr<BlockCacheTraceSimulator>&& cache_simulator)
: env_(ROCKSDB_NAMESPACE::Env::Default()),
trace_file_path_(trace_file_path),
output_dir_(output_dir),
human_readable_trace_file_path_(human_readable_trace_file_path),
compute_reuse_distance_(compute_reuse_distance),
mrc_only_(mrc_only),
is_human_readable_trace_file_(is_human_readable_trace_file),
cache_simulator_(std::move(cache_simulator)) {}
void BlockCacheTraceAnalyzer::ComputeReuseDistance(
BlockAccessInfo* info) const {
assert(info);
if (info->num_accesses == 0) {
return;
}
uint64_t reuse_distance = 0;
for (auto const& block_key : info->unique_blocks_since_last_access) {
auto const& it = block_info_map_.find(block_key);
// This block must exist.
assert(it != block_info_map_.end());
reuse_distance += it->second->block_size;
}
info->reuse_distance_count[reuse_distance] += 1;
// We clear this hash set since this is the second access on this block.
info->unique_blocks_since_last_access.clear();
}
Status BlockCacheTraceAnalyzer::RecordAccess(
const BlockCacheTraceRecord& access) {
ColumnFamilyAccessInfoAggregate& cf_aggr = cf_aggregates_map_[access.cf_name];
SSTFileAccessInfoAggregate& file_aggr =
cf_aggr.fd_aggregates_map[access.sst_fd_number];
file_aggr.level = access.level;
BlockTypeAccessInfoAggregate& block_type_aggr =
file_aggr.block_type_aggregates_map[access.block_type];
if (block_type_aggr.block_access_info_map.find(access.block_key) ==
block_type_aggr.block_access_info_map.end()) {
block_type_aggr.block_access_info_map[access.block_key].block_id =
unique_block_id_;
unique_block_id_++;
}
BlockAccessInfo& block_access_info =
block_type_aggr.block_access_info_map[access.block_key];
if (compute_reuse_distance_) {
ComputeReuseDistance(&block_access_info);
}
block_access_info.AddAccess(access, access_sequence_number_);
block_info_map_[access.block_key] = &block_access_info;
uint64_t get_key_id = 0;
if (access.caller == TableReaderCaller::kUserGet &&
access.get_id != BlockCacheTraceHelper::kReservedGetId) {
std::string user_key = ExtractUserKey(access.referenced_key).ToString();
if (get_key_info_map_.find(user_key) == get_key_info_map_.end()) {
get_key_info_map_[user_key].key_id = unique_get_key_id_;
unique_get_key_id_++;
}
get_key_id = get_key_info_map_[user_key].key_id;
get_key_info_map_[user_key].AddAccess(access, access_sequence_number_);
}
if (compute_reuse_distance_) {
// Add this block to all existing blocks.
for (auto& cf_aggregates : cf_aggregates_map_) {
for (auto& file_aggregates : cf_aggregates.second.fd_aggregates_map) {
for (auto& block_type_aggregates :
file_aggregates.second.block_type_aggregates_map) {
for (auto& existing_block :
block_type_aggregates.second.block_access_info_map) {
existing_block.second.unique_blocks_since_last_access.insert(
access.block_key);
}
}
}
}
}
return human_readable_trace_writer_.WriteHumanReadableTraceRecord(
access, block_access_info.block_id, get_key_id);
}
Status BlockCacheTraceAnalyzer::Analyze() {
SystemClock* clock = env_->GetSystemClock().get();
std::unique_ptr<BlockCacheTraceReader> reader;
Status s = Status::OK();
if (is_human_readable_trace_file_) {
reader.reset(new BlockCacheHumanReadableTraceReader(trace_file_path_));
} else {
std::unique_ptr<TraceReader> trace_reader;
s = NewFileTraceReader(env_, EnvOptions(), trace_file_path_, &trace_reader);
if (!s.ok()) {
return s;
}
reader.reset(new BlockCacheTraceReader(std::move(trace_reader)));
s = reader->ReadHeader(&header_);
if (!s.ok()) {
return s;
}
}
if (!human_readable_trace_file_path_.empty()) {
s = human_readable_trace_writer_.NewWritableFile(
human_readable_trace_file_path_, env_);
if (!s.ok()) {
return s;
}
}
uint64_t start = clock->NowMicros();
uint64_t time_interval = 0;
while (s.ok()) {
BlockCacheTraceRecord access;
s = reader->ReadAccess(&access);
if (!s.ok()) {
break;
}
if (!mrc_only_) {
s = RecordAccess(access);
if (!s.ok()) {
break;
}
}
if (trace_start_timestamp_in_seconds_ == 0) {
trace_start_timestamp_in_seconds_ =
access.access_timestamp / kMicrosInSecond;
}
trace_end_timestamp_in_seconds_ = access.access_timestamp / kMicrosInSecond;
miss_ratio_stats_.UpdateMetrics(access.access_timestamp,
is_user_access(access.caller),
access.is_cache_hit == Boolean::kFalse);
if (cache_simulator_) {
cache_simulator_->Access(access);
}
access_sequence_number_++;
uint64_t now = clock->NowMicros();
uint64_t duration = (now - start) / kMicrosInSecond;
if (duration > 10 * time_interval) {
uint64_t trace_duration =
trace_end_timestamp_in_seconds_ - trace_start_timestamp_in_seconds_;
fprintf(stdout,
"Running for %" PRIu64 " seconds: Processed %" PRIu64
" records/second. Trace duration %" PRIu64
" seconds. Observed miss ratio %.2f\n",
duration, duration > 0 ? access_sequence_number_ / duration : 0,
trace_duration, miss_ratio_stats_.miss_ratio());
time_interval++;
}
}
uint64_t now = clock->NowMicros();
uint64_t duration = (now - start) / kMicrosInSecond;
uint64_t trace_duration =
trace_end_timestamp_in_seconds_ - trace_start_timestamp_in_seconds_;
fprintf(stdout,
"Running for %" PRIu64 " seconds: Processed %" PRIu64
" records/second. Trace duration %" PRIu64
" seconds. Observed miss ratio %.2f\n",
duration, duration > 0 ? access_sequence_number_ / duration : 0,
trace_duration, miss_ratio_stats_.miss_ratio());
return s;
}
void BlockCacheTraceAnalyzer::PrintBlockSizeStats() const {
HistogramStat bs_stats;
std::map<TraceType, HistogramStat> bt_stats_map;
std::map<std::string, std::map<TraceType, HistogramStat>> cf_bt_stats_map;
auto block_callback =
[&](const std::string& cf_name, uint64_t /*fd*/, uint32_t /*level*/,
TraceType type, const std::string& /*block_key*/,
uint64_t /*block_id*/, const BlockAccessInfo& block) {
if (block.block_size == 0) {
// Block size may be 0 when 1) compaction observes a cache miss and
// does not insert the missing block into the cache again. 2)
// fetching filter blocks in SST files at the last level.
return;
}
bs_stats.Add(block.block_size);
bt_stats_map[type].Add(block.block_size);
cf_bt_stats_map[cf_name][type].Add(block.block_size);
};
TraverseBlocks(block_callback);
fprintf(stdout, "Block size stats: \n%s", bs_stats.ToString().c_str());
for (auto const& bt_stats : bt_stats_map) {
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout, "Block size stats for block type %s: \n%s",
block_type_to_string(bt_stats.first).c_str(),
bt_stats.second.ToString().c_str());
}
for (auto const& cf_bt_stats : cf_bt_stats_map) {
const std::string& cf_name = cf_bt_stats.first;
for (auto const& bt_stats : cf_bt_stats.second) {
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout,
"Block size stats for column family %s and block type %s: \n%s",
cf_name.c_str(), block_type_to_string(bt_stats.first).c_str(),
bt_stats.second.ToString().c_str());
}
}
}
void BlockCacheTraceAnalyzer::PrintAccessCountStats(bool user_access_only,
uint32_t bottom_k,
uint32_t top_k) const {
HistogramStat access_stats;
std::map<TraceType, HistogramStat> bt_stats_map;
std::map<std::string, std::map<TraceType, HistogramStat>> cf_bt_stats_map;
std::map<uint64_t, std::vector<std::string>> access_count_blocks;
auto block_callback = [&](const std::string& cf_name, uint64_t /*fd*/,
uint32_t /*level*/, TraceType type,
const std::string& block_key, uint64_t /*block_id*/,
const BlockAccessInfo& block) {
uint64_t naccesses = 0;
for (auto const& caller_access : block.caller_num_access_map) {
if (!user_access_only || is_user_access(caller_access.first)) {
naccesses += caller_access.second;
}
}
if (naccesses == 0) {
return;
}
if (type == TraceType::kBlockTraceDataBlock) {
access_count_blocks[naccesses].push_back(block_key);
}
access_stats.Add(naccesses);
bt_stats_map[type].Add(naccesses);
cf_bt_stats_map[cf_name][type].Add(naccesses);
};
TraverseBlocks(block_callback);
fprintf(stdout,
"Block access count stats: The number of accesses per block. %s\n%s",
user_access_only ? "User accesses only" : "All accesses",
access_stats.ToString().c_str());
uint32_t bottom_k_index = 0;
for (auto naccess_it = access_count_blocks.begin();
naccess_it != access_count_blocks.end(); naccess_it++) {
bottom_k_index++;
if (bottom_k_index >= bottom_k) {
break;
}
std::map<TableReaderCaller, uint64_t> caller_naccesses;
uint64_t naccesses = 0;
for (auto const& block_id : naccess_it->second) {
BlockAccessInfo* block = block_info_map_.find(block_id)->second;
for (auto const& caller_access : block->caller_num_access_map) {
if (!user_access_only || is_user_access(caller_access.first)) {
caller_naccesses[caller_access.first] += caller_access.second;
naccesses += caller_access.second;
}
}
}
std::string statistics("Caller:");
for (auto const& caller_naccessess_it : caller_naccesses) {
statistics += caller_to_string(caller_naccessess_it.first);
statistics += ":";
statistics +=
std::to_string(percent(caller_naccessess_it.second, naccesses));
statistics += ",";
}
fprintf(stdout,
"Bottom %" PRIu32 " access count. Access count=%" PRIu64
" nblocks=%" ROCKSDB_PRIszt " %s\n",
bottom_k, naccess_it->first, naccess_it->second.size(),
statistics.c_str());
}
uint32_t top_k_index = 0;
for (auto naccess_it = access_count_blocks.rbegin();
naccess_it != access_count_blocks.rend(); naccess_it++) {
top_k_index++;
if (top_k_index >= top_k) {
break;
}
for (auto const& block_id : naccess_it->second) {
BlockAccessInfo* block = block_info_map_.find(block_id)->second;
std::string statistics("Caller:");
uint64_t naccesses = 0;
for (auto const& caller_access : block->caller_num_access_map) {
if (!user_access_only || is_user_access(caller_access.first)) {
naccesses += caller_access.second;
}
}
assert(naccesses > 0);
for (auto const& caller_access : block->caller_num_access_map) {
if (!user_access_only || is_user_access(caller_access.first)) {
statistics += ",";
statistics += caller_to_string(caller_access.first);
statistics += ":";
statistics +=
std::to_string(percent(caller_access.second, naccesses));
}
}
uint64_t ref_keys_accesses = 0;
uint64_t ref_keys_does_not_exist_accesses = 0;
for (auto const& ref_key_caller_access : block->key_num_access_map) {
for (auto const& caller_access : ref_key_caller_access.second) {
if (!user_access_only || is_user_access(caller_access.first)) {
ref_keys_accesses += caller_access.second;
}
}
}
for (auto const& ref_key_caller_access :
block->non_exist_key_num_access_map) {
for (auto const& caller_access : ref_key_caller_access.second) {
if (!user_access_only || is_user_access(caller_access.first)) {
ref_keys_does_not_exist_accesses += caller_access.second;
}
}
}
statistics += ",nkeys=";
statistics += std::to_string(block->num_keys);
statistics += ",block_size=";
statistics += std::to_string(block->block_size);
statistics += ",num_ref_keys=";
statistics += std::to_string(block->key_num_access_map.size());
statistics += ",percent_access_ref_keys=";
statistics += std::to_string(percent(ref_keys_accesses, naccesses));
statistics += ",num_ref_keys_does_not_exist=";
statistics += std::to_string(block->non_exist_key_num_access_map.size());
statistics += ",percent_access_ref_keys_does_not_exist=";
statistics +=
std::to_string(percent(ref_keys_does_not_exist_accesses, naccesses));
statistics += ",ref_data_size=";
statistics += std::to_string(block->referenced_data_size);
fprintf(stdout,
"Top %" PRIu32 " access count blocks access_count=%" PRIu64
" %s\n",
top_k, naccess_it->first, statistics.c_str());
}
}
for (auto const& bt_stats : bt_stats_map) {
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout, "Break down by block type %s: \n%s",
block_type_to_string(bt_stats.first).c_str(),
bt_stats.second.ToString().c_str());
}
for (auto const& cf_bt_stats : cf_bt_stats_map) {
const std::string& cf_name = cf_bt_stats.first;
for (auto const& bt_stats : cf_bt_stats.second) {
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout,
"Break down by column family %s and block type "
"%s: \n%s",
cf_name.c_str(), block_type_to_string(bt_stats.first).c_str(),
bt_stats.second.ToString().c_str());
}
}
}
void BlockCacheTraceAnalyzer::PrintDataBlockAccessStats() const {
HistogramStat existing_keys_stats;
std::map<std::string, HistogramStat> cf_existing_keys_stats_map;
HistogramStat non_existing_keys_stats;
std::map<std::string, HistogramStat> cf_non_existing_keys_stats_map;
HistogramStat block_access_stats;
std::map<std::string, HistogramStat> cf_block_access_info;
HistogramStat percent_referenced_bytes;
std::map<std::string, HistogramStat> cf_percent_referenced_bytes;
// Total number of accesses in a data block / number of keys in a data block.
HistogramStat avg_naccesses_per_key_in_a_data_block;
std::map<std::string, HistogramStat> cf_avg_naccesses_per_key_in_a_data_block;
// The standard deviation on the number of accesses of a key in a data block.
HistogramStat stdev_naccesses_per_key_in_a_data_block;
std::map<std::string, HistogramStat>
cf_stdev_naccesses_per_key_in_a_data_block;
auto block_callback =
[&](const std::string& cf_name, uint64_t /*fd*/, uint32_t /*level*/,
TraceType /*type*/, const std::string& /*block_key*/,
uint64_t /*block_id*/, const BlockAccessInfo& block) {
if (block.num_keys == 0) {
return;
}
// Use four decimal points.
uint64_t percent_referenced_for_existing_keys = (uint64_t)(
((double)block.key_num_access_map.size() / (double)block.num_keys) *
10000.0);
uint64_t percent_referenced_for_non_existing_keys =
(uint64_t)(((double)block.non_exist_key_num_access_map.size() /
(double)block.num_keys) *
10000.0);
uint64_t percent_accesses_for_existing_keys =
(uint64_t)(((double)block.num_referenced_key_exist_in_block /
(double)block.num_accesses) *
10000.0);
HistogramStat hist_naccess_per_key;
for (auto const& key_access : block.key_num_access_map) {
for (auto const& caller_access : key_access.second) {
hist_naccess_per_key.Add(caller_access.second);
}
}
uint64_t avg_accesses =
static_cast<uint64_t>(hist_naccess_per_key.Average());
uint64_t stdev_accesses =
static_cast<uint64_t>(hist_naccess_per_key.StandardDeviation());
avg_naccesses_per_key_in_a_data_block.Add(avg_accesses);
cf_avg_naccesses_per_key_in_a_data_block[cf_name].Add(avg_accesses);
stdev_naccesses_per_key_in_a_data_block.Add(stdev_accesses);
cf_stdev_naccesses_per_key_in_a_data_block[cf_name].Add(stdev_accesses);
existing_keys_stats.Add(percent_referenced_for_existing_keys);
cf_existing_keys_stats_map[cf_name].Add(
percent_referenced_for_existing_keys);
non_existing_keys_stats.Add(percent_referenced_for_non_existing_keys);
cf_non_existing_keys_stats_map[cf_name].Add(
percent_referenced_for_non_existing_keys);
block_access_stats.Add(percent_accesses_for_existing_keys);
cf_block_access_info[cf_name].Add(percent_accesses_for_existing_keys);
};
TraverseBlocks(block_callback);
fprintf(stdout,
"Histogram on the number of referenced keys existing in a block over "
"the total number of keys in a block: \n%s",
existing_keys_stats.ToString().c_str());
for (auto const& cf_stats : cf_existing_keys_stats_map) {
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout, "Break down by column family %s: \n%s",
cf_stats.first.c_str(), cf_stats.second.ToString().c_str());
}
print_break_lines(/*num_break_lines=*/1);
fprintf(
stdout,
"Histogram on the number of referenced keys DO NOT exist in a block over "
"the total number of keys in a block: \n%s",
non_existing_keys_stats.ToString().c_str());
for (auto const& cf_stats : cf_non_existing_keys_stats_map) {
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout, "Break down by column family %s: \n%s",
cf_stats.first.c_str(), cf_stats.second.ToString().c_str());
}
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout,
"Histogram on the number of accesses on keys exist in a block over "
"the total number of accesses in a block: \n%s",
block_access_stats.ToString().c_str());
for (auto const& cf_stats : cf_block_access_info) {
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout, "Break down by column family %s: \n%s",
cf_stats.first.c_str(), cf_stats.second.ToString().c_str());
}
print_break_lines(/*num_break_lines=*/1);
fprintf(
stdout,
"Histogram on the average number of accesses per key in a block: \n%s",
avg_naccesses_per_key_in_a_data_block.ToString().c_str());
for (auto const& cf_stats : cf_avg_naccesses_per_key_in_a_data_block) {
fprintf(stdout, "Break down by column family %s: \n%s",
cf_stats.first.c_str(), cf_stats.second.ToString().c_str());
}
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout,
"Histogram on the standard deviation of the number of accesses per "
"key in a block: \n%s",
stdev_naccesses_per_key_in_a_data_block.ToString().c_str());
for (auto const& cf_stats : cf_stdev_naccesses_per_key_in_a_data_block) {
fprintf(stdout, "Break down by column family %s: \n%s",
cf_stats.first.c_str(), cf_stats.second.ToString().c_str());
}
}
void BlockCacheTraceAnalyzer::PrintStatsSummary() const {
uint64_t total_num_files = 0;
uint64_t total_num_blocks = 0;
uint64_t total_num_accesses = 0;
std::map<TraceType, uint64_t> bt_num_blocks_map;
std::map<TableReaderCaller, uint64_t> caller_num_access_map;
std::map<TableReaderCaller, std::map<TraceType, uint64_t>>
caller_bt_num_access_map;
std::map<TableReaderCaller, std::map<uint32_t, uint64_t>>
caller_level_num_access_map;
for (auto const& cf_aggregates : cf_aggregates_map_) {
// Stats per column family.
const std::string& cf_name = cf_aggregates.first;
uint64_t cf_num_files = 0;
uint64_t cf_num_blocks = 0;
std::map<TraceType, uint64_t> cf_bt_blocks;
uint64_t cf_num_accesses = 0;
std::map<TableReaderCaller, uint64_t> cf_caller_num_accesses_map;
std::map<TableReaderCaller, std::map<uint64_t, uint64_t>>
cf_caller_level_num_accesses_map;
std::map<TableReaderCaller, std::map<uint64_t, uint64_t>>
cf_caller_file_num_accesses_map;
std::map<TableReaderCaller, std::map<TraceType, uint64_t>>
cf_caller_bt_num_accesses_map;
total_num_files += cf_aggregates.second.fd_aggregates_map.size();
for (auto const& file_aggregates : cf_aggregates.second.fd_aggregates_map) {
// Stats per SST file.
const uint64_t fd = file_aggregates.first;
const uint32_t level = file_aggregates.second.level;
cf_num_files++;
for (auto const& block_type_aggregates :
file_aggregates.second.block_type_aggregates_map) {
// Stats per block type.
const TraceType type = block_type_aggregates.first;
cf_bt_blocks[type] +=
block_type_aggregates.second.block_access_info_map.size();
total_num_blocks +=
block_type_aggregates.second.block_access_info_map.size();
bt_num_blocks_map[type] +=
block_type_aggregates.second.block_access_info_map.size();
for (auto const& block_access_info :
block_type_aggregates.second.block_access_info_map) {
// Stats per block.
cf_num_blocks++;
for (auto const& stats :
block_access_info.second.caller_num_access_map) {
// Stats per caller.
const TableReaderCaller caller = stats.first;
const uint64_t num_accesses = stats.second;
// Overall stats.
total_num_accesses += num_accesses;
caller_num_access_map[caller] += num_accesses;
caller_bt_num_access_map[caller][type] += num_accesses;
caller_level_num_access_map[caller][level] += num_accesses;
// Column Family stats.
cf_num_accesses += num_accesses;
cf_caller_num_accesses_map[caller] += num_accesses;
cf_caller_level_num_accesses_map[caller][level] += num_accesses;
cf_caller_file_num_accesses_map[caller][fd] += num_accesses;
cf_caller_bt_num_accesses_map[caller][type] += num_accesses;
}
}
}
}
// Print stats.
print_break_lines(/*num_break_lines=*/3);
fprintf(stdout, "Statistics for column family %s:\n", cf_name.c_str());
fprintf(stdout,
" Number of files:%" PRIu64 " Number of blocks: %" PRIu64
" Number of accesses: %" PRIu64 "\n",
cf_num_files, cf_num_blocks, cf_num_accesses);
for (auto block_type : cf_bt_blocks) {
fprintf(stdout, "Number of %s blocks: %" PRIu64 " Percent: %.2f\n",
block_type_to_string(block_type.first).c_str(), block_type.second,
percent(block_type.second, cf_num_blocks));
}
for (auto caller : cf_caller_num_accesses_map) {
const uint64_t naccesses = caller.second;
print_break_lines(/*num_break_lines=*/1);
fprintf(stdout,
"Caller %s: Number of accesses %" PRIu64 " Percent: %.2f\n",
caller_to_string(caller.first).c_str(), naccesses,
percent(naccesses, cf_num_accesses));
fprintf(stdout, "Caller %s: Number of accesses per level break down\n",
caller_to_string(caller.first).c_str());
for (auto naccess_level :
cf_caller_level_num_accesses_map[caller.first]) {
fprintf(stdout,
"\t Level %" PRIu64 ": Number of accesses: %" PRIu64
" Percent: %.2f\n",
naccess_level.first, naccess_level.second,
percent(naccess_level.second, naccesses));
}
fprintf(stdout, "Caller %s: Number of accesses per file break down\n",
caller_to_string(caller.first).c_str());
for (auto naccess_file : cf_caller_file_num_accesses_map[caller.first]) {
fprintf(stdout,
"\t File %" PRIu64 ": Number of accesses: %" PRIu64
" Percent: %.2f\n",
naccess_file.first, naccess_file.second,
percent(naccess_file.second, naccesses));
}
fprintf(stdout,
"Caller %s: Number of accesses per block type break down\n",
caller_to_string(caller.first).c_str());
for (auto naccess_type : cf_caller_bt_num_accesses_map[caller.first]) {
fprintf(stdout,
"\t Block Type %s: Number of accesses: %" PRIu64
" Percent: %.2f\n",
block_type_to_string(naccess_type.first).c_str(),
naccess_type.second, percent(naccess_type.second, naccesses));
}
}
}
print_break_lines(/*num_break_lines=*/3);
fprintf(stdout, "Overall statistics:\n");
fprintf(stdout,
"Number of files: %" PRIu64 " Number of blocks: %" PRIu64
" Number of accesses: %" PRIu64 "\n",
total_num_files, total_num_blocks, total_num_accesses);
for (auto block_type : bt_num_blocks_map) {
fprintf(stdout, "Number of %s blocks: %" PRIu64 " Percent: %.2f\n",
block_type_to_string(block_type.first).c_str(), block_type.second,
percent(block_type.second, total_num_blocks));
}
for (auto caller : caller_num_access_map) {
print_break_lines(/*num_break_lines=*/1);
uint64_t naccesses = caller.second;
fprintf(stdout, "Caller %s: Number of accesses %" PRIu64 " Percent: %.2f\n",
caller_to_string(caller.first).c_str(), naccesses,
percent(naccesses, total_num_accesses));
fprintf(stdout, "Caller %s: Number of accesses per level break down\n",
caller_to_string(caller.first).c_str());
for (auto naccess_level : caller_level_num_access_map[caller.first]) {
fprintf(stdout,
"\t Level %d: Number of accesses: %" PRIu64 " Percent: %.2f\n",
naccess_level.first, naccess_level.second,
percent(naccess_level.second, naccesses));
}
fprintf(stdout, "Caller %s: Number of accesses per block type break down\n",
caller_to_string(caller.first).c_str());
for (auto naccess_type : caller_bt_num_access_map[caller.first]) {
fprintf(stdout,
"\t Block Type %s: Number of accesses: %" PRIu64
" Percent: %.2f\n",
block_type_to_string(naccess_type.first).c_str(),
naccess_type.second, percent(naccess_type.second, naccesses));
}
}
}
std::vector<CacheConfiguration> parse_cache_config_file(
const std::string& config_path) {
std::ifstream file(config_path);
if (!file.is_open()) {
return {};
}
std::vector<CacheConfiguration> configs;
std::string line;
while (getline(file, line)) {
CacheConfiguration cache_config;
std::stringstream ss(line);
std::vector<std::string> config_strs;
while (ss.good()) {
std::string substr;
getline(ss, substr, ',');
config_strs.push_back(substr);
}
// Sanity checks.
if (config_strs.size() < 4) {
fprintf(stderr, "Invalid cache simulator configuration %s\n",
line.c_str());
exit(1);
}
if (kSupportedCacheNames.find(" " + config_strs[0] + " ") ==
std::string::npos) {
fprintf(stderr, "Invalid cache name %s. Supported cache names are %s\n",
line.c_str(), kSupportedCacheNames.c_str());
exit(1);
}
cache_config.cache_name = config_strs[0];
cache_config.num_shard_bits = ParseUint32(config_strs[1]);
cache_config.ghost_cache_capacity = ParseUint64(config_strs[2]);
for (uint32_t i = 3; i < config_strs.size(); i++) {
uint64_t capacity = ParseUint64(config_strs[i]);
if (capacity == 0) {
fprintf(stderr, "Invalid cache capacity %s, %s\n",
config_strs[i].c_str(), line.c_str());
exit(1);
}
cache_config.cache_capacities.push_back(capacity);
}
configs.push_back(cache_config);
}
file.close();
return configs;
}
std::vector<uint64_t> parse_buckets(const std::string& bucket_str) {
std::vector<uint64_t> buckets;
std::stringstream ss(bucket_str);
while (ss.good()) {
std::string bucket;
getline(ss, bucket, ',');
buckets.push_back(ParseUint64(bucket));
}
buckets.push_back(port::kMaxUint64);
return buckets;
}
int block_cache_trace_analyzer_tool(int argc, char** argv) {
ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_block_cache_trace_path.empty()) {
fprintf(stderr, "block cache trace path is empty\n");
exit(1);
}
uint64_t warmup_seconds =
FLAGS_cache_sim_warmup_seconds > 0 ? FLAGS_cache_sim_warmup_seconds : 0;
uint32_t downsample_ratio = FLAGS_block_cache_trace_downsample_ratio > 0
? FLAGS_block_cache_trace_downsample_ratio
: 0;
std::vector<CacheConfiguration> cache_configs =
parse_cache_config_file(FLAGS_block_cache_sim_config_path);
std::unique_ptr<BlockCacheTraceSimulator> cache_simulator;
if (!cache_configs.empty()) {
cache_simulator.reset(new BlockCacheTraceSimulator(
warmup_seconds, downsample_ratio, cache_configs));
Status s = cache_simulator->InitializeCaches();
if (!s.ok()) {
fprintf(stderr, "Cannot initialize cache simulators %s\n",
s.ToString().c_str());
exit(1);
}
}
BlockCacheTraceAnalyzer analyzer(
FLAGS_block_cache_trace_path, FLAGS_block_cache_analysis_result_dir,
FLAGS_human_readable_trace_file_path,
!FLAGS_reuse_distance_labels.empty(), FLAGS_mrc_only,
FLAGS_is_block_cache_human_readable_trace, std::move(cache_simulator));
Status s = analyzer.Analyze();
if (!s.IsIncomplete() && !s.ok()) {
// Read all traces.
fprintf(stderr, "Cannot process the trace %s\n", s.ToString().c_str());
exit(1);
}
fprintf(stdout, "Status: %s\n", s.ToString().c_str());
analyzer.WriteMissRatioCurves();
analyzer.WriteMissRatioTimeline(1);
analyzer.WriteMissRatioTimeline(kSecondInMinute);
analyzer.WriteMissRatioTimeline(kSecondInHour);
analyzer.WriteMissTimeline(1);
analyzer.WriteMissTimeline(kSecondInMinute);
analyzer.WriteMissTimeline(kSecondInHour);
if (FLAGS_mrc_only) {
fprintf(stdout,
"Skipping the analysis statistics since the user wants to compute "
"MRC only");
return 0;
}
analyzer.PrintStatsSummary();
if (FLAGS_print_access_count_stats) {
print_break_lines(/*num_break_lines=*/3);
analyzer.PrintAccessCountStats(
/*user_access_only=*/false, FLAGS_analyze_bottom_k_access_count_blocks,
FLAGS_analyze_top_k_access_count_blocks);
print_break_lines(/*num_break_lines=*/3);
analyzer.PrintAccessCountStats(
/*user_access_only=*/true, FLAGS_analyze_bottom_k_access_count_blocks,
FLAGS_analyze_top_k_access_count_blocks);
}
if (FLAGS_print_block_size_stats) {
print_break_lines(/*num_break_lines=*/3);
analyzer.PrintBlockSizeStats();
}
if (FLAGS_print_data_block_access_count_stats) {
print_break_lines(/*num_break_lines=*/3);
analyzer.PrintDataBlockAccessStats();
}
print_break_lines(/*num_break_lines=*/3);
if (!FLAGS_timeline_labels.empty()) {
std::stringstream ss(FLAGS_timeline_labels);
while (ss.good()) {
std::string label;
getline(ss, label, ',');
if (label.find("block") != std::string::npos) {
analyzer.WriteAccessTimeline(label, kSecondInMinute, true);
analyzer.WriteAccessTimeline(label, kSecondInMinute, false);
analyzer.WriteAccessTimeline(label, kSecondInHour, true);
analyzer.WriteAccessTimeline(label, kSecondInHour, false);
} else {
analyzer.WriteAccessTimeline(label, kSecondInMinute, false);
analyzer.WriteAccessTimeline(label, kSecondInHour, false);
}
}
}
if (!FLAGS_analyze_callers.empty()) {
analyzer.WritePercentAccessSummaryStats();
std::stringstream ss(FLAGS_analyze_callers);
while (ss.good()) {
std::string caller;
getline(ss, caller, ',');
analyzer.WriteDetailedPercentAccessSummaryStats(string_to_caller(caller));
}
}
if (!FLAGS_access_count_buckets.empty()) {
std::vector<uint64_t> buckets = parse_buckets(FLAGS_access_count_buckets);
analyzer.WriteAccessCountSummaryStats(buckets, /*user_access_only=*/true);
analyzer.WriteAccessCountSummaryStats(buckets, /*user_access_only=*/false);
}
if (!FLAGS_reuse_distance_labels.empty() &&
!FLAGS_reuse_distance_buckets.empty()) {
std::vector<uint64_t> buckets = parse_buckets(FLAGS_reuse_distance_buckets);
std::stringstream ss(FLAGS_reuse_distance_labels);
while (ss.good()) {
std::string label;
getline(ss, label, ',');
analyzer.WriteReuseDistance(label, buckets);
}
}
if (!FLAGS_reuse_interval_labels.empty() &&
!FLAGS_reuse_interval_buckets.empty()) {
std::vector<uint64_t> buckets = parse_buckets(FLAGS_reuse_interval_buckets);
std::stringstream ss(FLAGS_reuse_interval_labels);
while (ss.good()) {
std::string label;
getline(ss, label, ',');
analyzer.WriteReuseInterval(label, buckets);
}
}
if (!FLAGS_reuse_lifetime_labels.empty() &&
!FLAGS_reuse_lifetime_buckets.empty()) {
std::vector<uint64_t> buckets = parse_buckets(FLAGS_reuse_lifetime_buckets);
std::stringstream ss(FLAGS_reuse_lifetime_labels);
while (ss.good()) {
std::string label;
getline(ss, label, ',');
analyzer.WriteReuseLifetime(label, buckets);
}
}
if (FLAGS_analyze_blocks_reuse_k_reuse_window != 0) {
std::vector<TraceType> block_types{TraceType::kBlockTraceIndexBlock,
TraceType::kBlockTraceDataBlock,
TraceType::kBlockTraceFilterBlock};
for (auto block_type : block_types) {
analyzer.WriteBlockReuseTimeline(
FLAGS_analyze_blocks_reuse_k_reuse_window,
/*user_access_only=*/true, block_type);
analyzer.WriteBlockReuseTimeline(
FLAGS_analyze_blocks_reuse_k_reuse_window,
/*user_access_only=*/false, block_type);
}
}
if (!FLAGS_analyze_get_spatial_locality_labels.empty() &&
!FLAGS_analyze_get_spatial_locality_buckets.empty()) {
std::vector<uint64_t> buckets =
parse_buckets(FLAGS_analyze_get_spatial_locality_buckets);
std::stringstream ss(FLAGS_analyze_get_spatial_locality_labels);
while (ss.good()) {
std::string label;
getline(ss, label, ',');
analyzer.WriteGetSpatialLocality(label, buckets);
}
}
if (!FLAGS_analyze_correlation_coefficients_labels.empty()) {
std::stringstream ss(FLAGS_analyze_correlation_coefficients_labels);
while (ss.good()) {
std::string label;
getline(ss, label, ',');
analyzer.WriteCorrelationFeatures(
label, FLAGS_analyze_correlation_coefficients_max_number_of_values);
}
analyzer.WriteCorrelationFeaturesForGet(
FLAGS_analyze_correlation_coefficients_max_number_of_values);
}
if (!FLAGS_skew_labels.empty() && !FLAGS_skew_buckets.empty()) {
std::vector<uint64_t> buckets = parse_buckets(FLAGS_skew_buckets);
std::stringstream ss(FLAGS_skew_labels);
while (ss.good()) {
std::string label;
getline(ss, label, ',');
if (label.find("block") != std::string::npos) {
analyzer.WriteSkewness(label, buckets,
TraceType::kBlockTraceIndexBlock);
analyzer.WriteSkewness(label, buckets,
TraceType::kBlockTraceFilterBlock);
analyzer.WriteSkewness(label, buckets, TraceType::kBlockTraceDataBlock);
analyzer.WriteSkewness(label, buckets, TraceType::kTraceMax);
} else {
analyzer.WriteSkewness(label, buckets, TraceType::kTraceMax);
}
}
}
return 0;
}
} // namespace ROCKSDB_NAMESPACE
#endif // GFLAGS
#endif // ROCKSDB_LITE
|
User-agent: *
Disallow: /*action=edit
Disallow: /*action=diff
Disallow: /*action=print$
Disallow: /*action=upload
Disallow: /*action=login$
Disallow: /*action=logout$
Disallow: /*action=sourceblock
|
/** \file
* \brief This class is a simple layout that places nodes next to each other
* and draws edges as bows above the nodes.
* The user may decide whether to use a custom permutation or use the ordering
* given by the nodes indices.
*
* \author Sebastian Semper
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* 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.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#include <ogdf/misclayout/LinearLayout.h>
namespace ogdf {
LinearLayout::LinearLayout(double w, ListPure<node> o) {
m_outWidth = w;
m_nodeOrder = o;
m_customOrder = 0;
}
LinearLayout::LinearLayout() {
m_outWidth = 100;
m_customOrder = 0;
}
LinearLayout::~LinearLayout() {
}
void LinearLayout::call(GraphAttributes& GA) {
const Graph& G = GA.constGraph();
ListPure<node> nodes;
if (m_customOrder) {
nodes = m_nodeOrder;
} else {
G.allNodes(nodes);
}
double x(0);
double step(m_outWidth / double(nodes.size()-1));
//first position all nodes next to each other
for (auto &n : nodes) {
GA.x(n) = x;
x += step;
}
//then bend all the edges
ListPure<edge> edges;
G.allEdges(edges);
for (auto &e : edges) {
node n1 = e->source();
node n2 = e->target();
if (!(++(nodes.search(n1)) == nodes.search(n2)) && !(++(nodes.search(n2)) == nodes.search(n1))) {
DPolyline &pL = GA.bends(e);
const double m(0.5 * (GA.x(n1) + GA.x(n2)));
const double r(std::abs(GA.x(n1) - m));
const double sgn(GA.x(n1) > GA.x(n2) ? 1.0 : -1.0);
int segments = int(sqrt(r*Math::pi / 0.2));
for (int i = segments; i--;) {
const double di = double(i);
const double newX = m - sgn*r*cos(di / segments*Math::pi);
const double newY = 0.5*GA.height(n1) - r*sin(di / segments*Math::pi);
pL.pushBack(DPoint(newX, newY));
}
}
}
}
void LinearLayout::setCustomOrder(bool o) {
m_customOrder = o;
}
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: OVR.OpenVR.IVRChaperoneSetup
#include "OVR/OpenVR/IVRChaperoneSetup.hpp"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: OVR::OpenVR
namespace OVR::OpenVR {
// Forward declaring type: HmdMatrix34_t
struct HmdMatrix34_t;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
// Type namespace: OVR.OpenVR
namespace OVR::OpenVR {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: OVR.OpenVR.IVRChaperoneSetup/OVR.OpenVR._GetWorkingSeatedZeroPoseToRawTrackingPose
// [TokenAttribute] Offset: FFFFFFFF
// [UnmanagedFunctionPointerAttribute] Offset: DF3288
class IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose : public System::MulticastDelegate {
public:
// Creating value type constructor for type: _GetWorkingSeatedZeroPoseToRawTrackingPose
_GetWorkingSeatedZeroPoseToRawTrackingPose() noexcept {}
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x15CE70C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose* New_ctor(::Il2CppObject* object, System::IntPtr method) {
static auto ___internal__logger = ::Logger::get().WithContext("OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose*, creationType>(object, method)));
}
// public System.Boolean Invoke(ref OVR.OpenVR.HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose)
// Offset: 0x15C51E8
bool Invoke(ByRef<OVR::OpenVR::HmdMatrix34_t> pmatSeatedZeroPoseToRawTrackingPose);
// public System.IAsyncResult BeginInvoke(ref OVR.OpenVR.HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose, System.AsyncCallback callback, System.Object object)
// Offset: 0x15CE71C
System::IAsyncResult* BeginInvoke(ByRef<OVR::OpenVR::HmdMatrix34_t> pmatSeatedZeroPoseToRawTrackingPose, System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.Boolean EndInvoke(ref OVR.OpenVR.HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose, System.IAsyncResult result)
// Offset: 0x15CE7B0
bool EndInvoke(ByRef<OVR::OpenVR::HmdMatrix34_t> pmatSeatedZeroPoseToRawTrackingPose, System::IAsyncResult* result);
}; // OVR.OpenVR.IVRChaperoneSetup/OVR.OpenVR._GetWorkingSeatedZeroPoseToRawTrackingPose
#pragma pack(pop)
}
DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose*, "OVR.OpenVR", "IVRChaperoneSetup/_GetWorkingSeatedZeroPoseToRawTrackingPose");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::Invoke
// Il2CppName: Invoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::*)(ByRef<OVR::OpenVR::HmdMatrix34_t>)>(&OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::Invoke)> {
static const MethodInfo* get() {
static auto* pmatSeatedZeroPoseToRawTrackingPose = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "HmdMatrix34_t")->this_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pmatSeatedZeroPoseToRawTrackingPose});
}
};
// Writing MetadataGetter for method: OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::BeginInvoke
// Il2CppName: BeginInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IAsyncResult* (OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::*)(ByRef<OVR::OpenVR::HmdMatrix34_t>, System::AsyncCallback*, ::Il2CppObject*)>(&OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::BeginInvoke)> {
static const MethodInfo* get() {
static auto* pmatSeatedZeroPoseToRawTrackingPose = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "HmdMatrix34_t")->this_arg;
static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg;
static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pmatSeatedZeroPoseToRawTrackingPose, callback, object});
}
};
// Writing MetadataGetter for method: OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::EndInvoke
// Il2CppName: EndInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::*)(ByRef<OVR::OpenVR::HmdMatrix34_t>, System::IAsyncResult*)>(&OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose::EndInvoke)> {
static const MethodInfo* get() {
static auto* pmatSeatedZeroPoseToRawTrackingPose = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "HmdMatrix34_t")->this_arg;
static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRChaperoneSetup::_GetWorkingSeatedZeroPoseToRawTrackingPose*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pmatSeatedZeroPoseToRawTrackingPose, result});
}
};
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
enum $5B6AFD24AD83D8D7CFBE616142A2693C
{
code_war = 0xFF,
code_chaos = 0xFE,
};
END_ATF_NAMESPACE
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "PuzzlePlatformsGameMode.h"
#include "PuzzlePlatformsCharacter.h"
#include "UObject/ConstructorHelpers.h"
APuzzlePlatformsGameMode::APuzzlePlatformsGameMode()
{
// set default pawn class to our Blueprinted character
static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonCPP/Blueprints/ThirdPersonCharacter"));
if (PlayerPawnBPClass.Class != NULL)
{
DefaultPawnClass = PlayerPawnBPClass.Class;
}
}
|
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/engines/scene.h>
#include <babylon/helpers/environment_helper.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/loading/plugins/gltf/gltf_file_loader.h>
#include <babylon/loading/scene_loader.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
namespace Samples {
/**
* @brief Flight Helmet Scene (glTF).
* @see https://doc.babylonjs.com/how_to/load_from_any_file_type
* @see https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/FlightHelmet
*/
struct FlightHelmetScene : public IRenderableScene {
FlightHelmetScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
{
GLTF2::GLTFFileLoader::RegisterAsSceneLoaderPlugin();
}
~FlightHelmetScene() override = default;
const char* getName() override
{
return "Flight Helmet Scene (glTF)";
}
void initializeScene(ICanvas* /*canvas*/, Scene* scene) override
{
SceneLoader::ImportMesh(
{}, "glTF-Sample-Models/2.0/FlightHelmet/glTF/", "FlightHelmet.gltf", scene,
[scene](const std::vector<AbstractMeshPtr>& /*meshes*/,
const std::vector<IParticleSystemPtr>& /*particleSystems*/,
const std::vector<SkeletonPtr>& /*skeletons*/,
const std::vector<AnimationGroupPtr>& /*animationGroups*/) {
scene->createDefaultCameraOrLight(true, true, true);
// Set the camera position
auto camera = std::static_pointer_cast<ArcRotateCamera>(scene->activeCamera());
if (camera) {
camera->setTarget(Vector3::Zero());
camera->alpha = Math::PI * (3.f / 4.f);
camera->beta = 1.f;
camera->radius = Math::PI * 0.5f;
}
});
}
}; // end of struct FlightHelmetScene
BABYLON_REGISTER_SAMPLE("Loaders - glTF format", FlightHelmetScene)
} // end of namespace Samples
} // end of namespace BABYLON
|
/** @file
*
* The implementation of the MultiplyElement class.
*
* @author Nicolas Bock <nicolas.bock@freeon.org>
* @author Matt Challacombe <matt.challacombe@freeon.org>
*/
#include "config.h"
#include "multiplyelement.h"
#include "chunk.h"
#include "index.h"
#include "lapack_interface.h"
#include "logger.h"
#include "messages.h"
#include "types.h"
#include "utilities.h"
#include <assert.h>
#include <bitset>
/** Some convenience macros for logging. Wrap the logging format string with
* LB and LE. */
#define LB "tier %d ME(%d,%d,%d) "
/** Some convenience macros for logging. Wrap the logging format string with
* LB and LE. */
#define LE , tier, thisIndex.x, thisIndex.y, thisIndex.z
/** The constructor.
*
* @param N The matrix size.
* @param blocksize The blocksize.
* @param N_basic The size of the basic submatrix.
* @param tier The tier.
* @param depth The depth of the matrix.
* @param A The Nodes of this tier in A.
* @param B The Nodes of this tier in B.
* @param C The Nodes of this tier in C.
*/
MultiplyElement::MultiplyElement (
int N,
int blocksize,
int N_basic,
int tier,
int depth,
CProxy_Node A,
CProxy_Node B,
CProxy_Node C)
{
DEBUG(LB"constructor\n"LE);
this->blocksize = blocksize;
this->N_basic = N_basic;
this->tier = tier;
this->depth = depth;
this->A = A;
this->B = B;
this->C = C;
this->norm_product = 0;
this->complexity = 0;
this->N = N;
iLower = thisIndex.x*blocksize;
jLower = thisIndex.y*blocksize;
/* Calculate the linear index. */
std::bitset<8*sizeof(int)> iIndex(thisIndex.x);
std::bitset<8*sizeof(int)> jIndex(thisIndex.y);
std::bitset<8*sizeof(int)> kIndex(thisIndex.z);
std::bitset<8*sizeof(int)> tempIndex(1);
for(int i = 0; i < tier; i++)
{
tempIndex <<= 3;
if(iIndex[i]) { tempIndex |= 4; }
if(jIndex[i]) { tempIndex |= 2; }
if(kIndex[i]) { tempIndex |= 1; }
}
index = tempIndex.to_ulong();
chunksize = 0;
CResult = NULL;
#ifndef PRUNE_CONVOLUTION
isEnabled = true;
#endif
}
/** The migration constructor.
*
* @param msg The migration message.
*/
MultiplyElement::MultiplyElement (CkMigrateMessage *msg)
{
DEBUG("ME(%d,%d,%d) migration constructor\n", thisIndex.x, thisIndex.y,
thisIndex.z);
CResult = NULL;
}
/** The destructor.
*/
MultiplyElement::~MultiplyElement ()
{
DEBUG(LB"destructor\n"LE);
if(CResult != NULL)
{
DEBUG("free'ing chunk at %p\n", CResult);
chunk_delete(&CResult);
CResult = NULL;
chunksize = 0;
}
}
/** The PUP method.
*
* @param p The PUP::er object.
*/
void MultiplyElement::pup (PUP::er &p)
{
CBase_MultiplyElement::pup(p);
p|index;
p|blocksize;
p|N_basic;
p|depth;
p|tier;
p|A;
p|B;
p|C;
p|norm_product;
p|complexity;
#ifndef PRUNE_CONVOLUTION
p|isEnabled;
#endif
p|nextConvolution;
p|chunksize;
p|N;
p|iLower;
p|jLower;
bool resultSet = (CResult != NULL);
p|resultSet;
if(resultSet)
{
if(p.isUnpacking())
{
CResult = malloc(chunk_sizeof(blocksize, N_basic));
assert(chunksize == chunk_sizeof(blocksize, N_basic));
}
PUParray(p, (char*) CResult, chunksize);
}
DEBUG(LB"pup()\n"LE);
}
/** Initialize this MultiplyElement.
*
* @param cb The callback to reduce to.
*/
void MultiplyElement::init (CkCallback &cb)
{
INFO(LB"initializing\n"LE);
contribute(cb);
}
/** Multiply nodes.
*
* @f[ C \leftarrow \beta C + \alpha A \times B @f]
*
* @param tolerance The multiplication tolerance.
* @param cb The callback.
*/
void MultiplyElement::multiply (
double tolerance,
bool symbolic_only,
CkCallback &cb)
{
assert(tier == depth);
DEBUG(LB"multiply\n"LE);
#ifndef PRUNE_CONVOLUTION
if(isEnabled)
#endif
{
NodeInfoMsg *AInfo = A(thisIndex.x, thisIndex.z).info();
NodeInfoMsg *BInfo = B(thisIndex.z, thisIndex.y).info();
norm_product = AInfo->norm*BInfo->norm;
DEBUG(LB"multiplying blocks, ANorm*BNorm = %e\n"LE, norm_product);
delete AInfo;
delete BInfo;
if(norm_product > tolerance)
{
if(CResult != NULL)
{
ABORT(LB"result is not NULL\n"LE);
}
DEBUG(LB"creating result chunk, N = %d\n"LE, N);
CResult = chunk_alloc(blocksize, N_basic, N, iLower, jLower);
chunksize = chunk_sizeof(blocksize, N_basic);
/* Calculate C_{ij} = A_{ik} B_{kj}. */
DEBUG(LB"requesting ChunkMsg from A and B\n"LE);
ChunkMsg *AChunk = A(thisIndex.x, thisIndex.z).getChunk();
ChunkMsg *BChunk = B(thisIndex.z, thisIndex.y).getChunk();
#ifdef PRINT_MATRICES
chunk_print(AChunk->chunk, "tier %d ME(%d,%d,%d) AChunk(%d,%d):", tier,
thisIndex.x, thisIndex.y, thisIndex.z, thisIndex.x, thisIndex.z);
chunk_print(BChunk->chunk, "tier %d ME(%d,%d,%d) BChunk(%d,%d):", tier,
thisIndex.x, thisIndex.y, thisIndex.z, thisIndex.z, thisIndex.y);
#endif
DEBUG(LB"calling multiply on result\n"LE);
chunk_multiply(tolerance, AChunk->chunk, BChunk->chunk, CResult,
(symbolic_only ? 1 : 0));
#ifdef MEASURE_COMPLEXITY
complexity = chunk_get_complexity(CResult);
DEBUG(LB"setting complexity to %d\n"LE, complexity);
#endif
#ifdef PRINT_MATRICES
/** For debugging. */
chunk_print(CResult, LB"result:"LE);
#endif
DEBUG(LB"deleting ChunkMsg from A and B\n"LE);
delete AChunk;
delete BChunk;
}
#ifndef PRUNE_CONVOLUTION
else
{
INFO(LB"this product was enabled but its norm product was below the tolerance\n"LE);
}
#endif
}
#ifndef PRUNE_CONVOLUTION
else
{
DEBUG(LB"skipping disabled element\n"LE);
norm_product = 0;
}
#endif
if(symbolic_only)
{
chunk_delete(&CResult);
CResult = NULL;
DEBUG(LB"deleted CResult (symbolic_only)\n"LE);
}
DEBUG(LB"contributing to reduction\n"LE);
contribute(cb);
}
#ifdef PRUNE_CONVOLUTION
/** Prune the next tier based on the Node norms by applying the SpAMM
* tolerance.
*
* @param NTier The size of the convolution array.
* @param nextConvolutionMap A bool map indicating which MultiplyElement is
* active.
* @param tolerance The SpAMM tolerance.
* @param ANodes The @link Node nodes @endlink of Matrix A on the tier below this one.
* @param BNodes The @link Node nodes @endlink of Matrix B on the tier below this one.
* @param cb The callback to reduce to.
*/
void MultiplyElement::pruneProduct (
int NTier,
bool *nextConvolutionMap,
double tolerance,
CProxy_Node ANodes,
CProxy_Node BNodes,
CkCallback &cb)
#else
/** Prune the next tier based on the Node norms by applying the SpAMM
* tolerance.
*
* @param tolerance The SpAMM tolerance.
* @param ANodes The @link Node nodes @endlink of Matrix A on the tier below this one.
* @param BNodes The @link Node nodes @endlink of Matrix B on the tier below this one.
* @param cb The callback to reduce to.
*/
void MultiplyElement::pruneProduct (double tolerance,
CProxy_Node ANodes,
CProxy_Node BNodes,
CkCallback &cb)
#endif
{
DEBUG(LB"pruning next tier\n"LE);
#ifndef PRUNE_CONVOLUTION
if(isEnabled)
#endif
{
for(int i = 0; i < 2; i++)
{
int nextX = (thisIndex.x << 1) | i;
for(int j = 0; j < 2; j++)
{
int nextY = (thisIndex.y << 1) | j;
for(int k = 0; k < 2; k++)
{
int nextZ = (thisIndex.z << 1) | k;
NodeInfoMsg *AInfo = ANodes(nextX, nextZ).info();
NodeInfoMsg *BInfo = BNodes(nextZ, nextY).info();
if(AInfo->norm*BInfo->norm > tolerance)
{
/* If necessary, create MultiplyElement. */
DEBUG(LB"keeping tier %d, convolution(%d,%d,%d) "
"A[%d:%d,%d:%d]*B[%d:%d,%d:%d] "
"(%e * %e = %e > %e)\n"LE, tier+1,
nextX, nextY, nextZ,
AInfo->iLower, AInfo->iUpper, AInfo->jLower, AInfo->jUpper,
BInfo->iLower, BInfo->iUpper, BInfo->jLower, BInfo->jUpper,
AInfo->norm, BInfo->norm, AInfo->norm*BInfo->norm, tolerance);
#ifdef PRUNE_CONVOLUTION
if(!nextConvolutionMap[BLOCK_INDEX_3(nextX, nextY, nextZ, NTier)])
{
nextConvolution(nextX, nextY, nextZ).insert(blocksize, tier+1, depth, A, B, C);
nextConvolutionMap[BLOCK_INDEX_3(nextX, nextY, nextZ, NTier)] = false;
}
#else
nextConvolution(nextX, nextY, nextZ).enable(CkCallbackResumeThread());
#endif
}
else
{
/* If necessary, destroy MultiplyElement. */
DEBUG(LB"pruning tier %d, convolution(%d,%d,%d) "
"A[%d:%d,%d:%d]*B[%d:%d,%d:%d] "
"(%e * %e = %e <= %e)\n"LE, tier+1,
nextX, nextY, nextZ,
AInfo->iLower, AInfo->iUpper, AInfo->jLower, AInfo->jUpper,
BInfo->iLower, BInfo->iUpper, BInfo->jLower, BInfo->jUpper,
AInfo->norm, BInfo->norm, AInfo->norm*BInfo->norm, tolerance);
#ifdef PRUNE_CONVOLUTION
if(nextConvolutionMap[BLOCK_INDEX_3(nextX, nextY, nextZ, NTier)])
{
nextConvolution(nextX, nextY, nextZ).ckDestroy();
nextConvolutionMap[BLOCK_INDEX_3(nextX, nextY, nextZ, NTier)] = true;
}
#else
nextConvolution(nextX, nextY, nextZ).disable(CkCallbackResumeThread());
#endif
}
delete AInfo;
delete BInfo;
}
}
}
}
contribute(cb);
}
/** Set the convolution of the next tier.
*
* @param nextConvolution The chare array of @link MultiplyElement
* MultiplyEleemnts @endlink of the next tier.
*/
void MultiplyElement::setNextConvolution (CProxy_MultiplyElement nextConvolution)
{
this->nextConvolution = nextConvolution;
}
#ifndef PRUNE_CONVOLUTION
/** Enable this MultiplyElement.
*
* @param cb The callback to send to.
*/
void MultiplyElement::enable (CkCallback &cb)
{
if(!isEnabled)
{
isEnabled = true;
DEBUG(LB"enabling previously disabled element\n"LE);
}
cb.send();
}
/** Disable this MultiplyElement.
*
* @param cb The callback to send to.
*/
void MultiplyElement::disable (CkCallback &cb)
{
if(isEnabled == true)
{
DEBUG(LB"disabling\n"LE);
if(tier < depth)
{
/* Disable the elements below this one. */
for(int i = 0; i < 2; i++)
{
int nextX = (thisIndex.x << 1) | i;
for(int j = 0; j < 2; j++)
{
int nextY = (thisIndex.y << 1) | j;
for(int k = 0; k < 2; k++)
{
int nextZ = (thisIndex.z << 1) | k;
DEBUG(LB"disabling nextConvolution(%d,%d,%d)\n"LE, nextX, nextY,
nextZ);
nextConvolution(nextX, nextY, nextZ).disable(CkCallbackResumeThread());
}
}
}
}
/* Disable this MultiplyElement. */
isEnabled = false;
}
cb.send();
}
#endif
/** Push the C submatrices back into the C Matrix.
*
* @param alpha The factor @f$ \alpha @f$.
* @param cb The callback.
*/
void MultiplyElement::storeBack (
double alpha,
CkCallback &cb)
{
assert(tier == depth);
#ifndef PRUNE_CONVOLUTION
if(isEnabled)
#endif
{
DEBUG(LB"storing in C\n"LE);
if(CResult != NULL)
{
DEBUG(LB"calling blockAdd with Chunk at %p\n"LE, CResult);
C(thisIndex.x, thisIndex.y).chunkAdd(alpha, chunksize, (char*) CResult);
/* Reset result for possible next iteration. */
DEBUG(LB"deleting CResult at %p for next iteration\n"LE, CResult);
chunk_delete(&CResult);
CResult = NULL;
}
}
contribute(cb);
}
/** Create a PE map of the Matrix @link Node nodes @endlink.
*
* @param cb The callback for the reduction.
*/
void MultiplyElement::PEMap (CkCallback &cb)
{
DEBUG(LB"PE %d, norm = %e\n"LE, CkMyPe(), norm_product);
struct PEMap_MultiplyElement_t *result = (struct PEMap_MultiplyElement_t*)
malloc(sizeof(PEMap_MultiplyElement_t));
result->index[0] = thisIndex.x;
result->index[1] = thisIndex.y;
result->index[2] = thisIndex.z;
result->PE = CkMyPe();
result->norm_product = norm_product;
contribute(sizeof(PEMap_MultiplyElement_t), result, CkReduction::set, cb);
}
/** Update the complexity of this Multiply.
*
* @param cb The callback for the reduction.
*/
void MultiplyElement::updateComplexity (CkCallback &cb)
{
double converted_complexity = (double) complexity;
#ifndef PRUNE_CONVOLUTION
if(!isEnabled) { complexity = 0; }
#endif
contribute(sizeof(double), &converted_complexity, CkReduction::sum_double, cb);
}
#include "multiplyelement.def.h"
|
//===- ConsG.cpp -- Constraint graph representation-----------------------------//
//
// SVF: Static Value-Flow Analysis
//
// Copyright (C) <2013-2017> <Yulei Sui>
//
// 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 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
/*
* ConstraintGraph.cpp
*
* Created on: Oct 14, 2013
* Author: Yulei Sui
*/
#include "Graphs/ConsG.h"
#include "Util/Options.h"
using namespace SVF;
using namespace SVFUtil;
ConstraintNode::SCCEdgeFlag ConstraintNode::sccEdgeFlag = ConstraintNode::Direct;
/*!
* Start building constraint graph
*/
void ConstraintGraph::buildCG()
{
// initialize nodes
for(PAG::iterator it = pag->begin(), eit = pag->end(); it!=eit; ++it)
{
addConstraintNode(new ConstraintNode(it->first), it->first);
}
// initialize edges
PAGEdge::PAGEdgeSetTy& addrs = getPAGEdgeSet(PAGEdge::Addr);
for (PAGEdge::PAGEdgeSetTy::iterator iter = addrs.begin(), eiter =
addrs.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addAddrCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& copys = getPAGEdgeSet(PAGEdge::Copy);
for (PAGEdge::PAGEdgeSetTy::iterator iter = copys.begin(), eiter =
copys.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& calls = getPAGEdgeSet(PAGEdge::Call);
for (PAGEdge::PAGEdgeSetTy::iterator iter = calls.begin(), eiter =
calls.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& rets = getPAGEdgeSet(PAGEdge::Ret);
for (PAGEdge::PAGEdgeSetTy::iterator iter = rets.begin(), eiter =
rets.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& tdfks = getPAGEdgeSet(PAGEdge::ThreadFork);
for (PAGEdge::PAGEdgeSetTy::iterator iter = tdfks.begin(), eiter =
tdfks.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& tdjns = getPAGEdgeSet(PAGEdge::ThreadJoin);
for (PAGEdge::PAGEdgeSetTy::iterator iter = tdjns.begin(), eiter =
tdjns.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addCopyCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& ngeps = getPAGEdgeSet(PAGEdge::NormalGep);
for (PAGEdge::PAGEdgeSetTy::iterator iter = ngeps.begin(), eiter =
ngeps.end(); iter != eiter; ++iter)
{
NormalGepPE* edge = SVFUtil::cast<NormalGepPE>(*iter);
addNormalGepCGEdge(edge->getSrcID(),edge->getDstID(),edge->getLocationSet());
}
PAGEdge::PAGEdgeSetTy& vgeps = getPAGEdgeSet(PAGEdge::VariantGep);
for (PAGEdge::PAGEdgeSetTy::iterator iter = vgeps.begin(), eiter =
vgeps.end(); iter != eiter; ++iter)
{
VariantGepPE* edge = SVFUtil::cast<VariantGepPE>(*iter);
addVariantGepCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& stores = getPAGEdgeSet(PAGEdge::Load);
for (PAGEdge::PAGEdgeSetTy::iterator iter = stores.begin(), eiter =
stores.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addLoadCGEdge(edge->getSrcID(),edge->getDstID());
}
PAGEdge::PAGEdgeSetTy& loads = getPAGEdgeSet(PAGEdge::Store);
for (PAGEdge::PAGEdgeSetTy::iterator iter = loads.begin(), eiter =
loads.end(); iter != eiter; ++iter)
{
PAGEdge* edge = *iter;
addStoreCGEdge(edge->getSrcID(),edge->getDstID());
}
}
/*!
* Memory has been cleaned up at GenericGraph
*/
void ConstraintGraph::destroy()
{
}
/*!
* Constructor for address constraint graph edge
*/
AddrCGEdge::AddrCGEdge(ConstraintNode* s, ConstraintNode* d, EdgeID id)
: ConstraintEdge(s,d,Addr,id)
{
// Retarget addr edges may lead s to be a dummy node
PAGNode* node = PAG::getPAG()->getPAGNode(s->getId());
if (!SVFModule::pagReadFromTXT())
assert(!SVFUtil::isa<DummyValPN>(node) && "a dummy node??");
}
/*!
* Add an address edge
*/
AddrCGEdge* ConstraintGraph::addAddrCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::Addr))
return nullptr;
AddrCGEdge* edge = new AddrCGEdge(srcNode, dstNode, edgeIndex++);
bool added = AddrCGEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingAddrEdge(edge);
dstNode->addIncomingAddrEdge(edge);
return edge;
}
/*!
* Add Copy edge
*/
CopyCGEdge* ConstraintGraph::addCopyCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::Copy)
|| srcNode == dstNode)
return nullptr;
CopyCGEdge* edge = new CopyCGEdge(srcNode, dstNode, edgeIndex++);
bool added = directEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingCopyEdge(edge);
dstNode->addIncomingCopyEdge(edge);
return edge;
}
/*!
* Add Gep edge
*/
NormalGepCGEdge* ConstraintGraph::addNormalGepCGEdge(NodeID src, NodeID dst, const LocationSet& ls)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::NormalGep))
return nullptr;
NormalGepCGEdge* edge = new NormalGepCGEdge(srcNode, dstNode,ls, edgeIndex++);
bool added = directEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingGepEdge(edge);
dstNode->addIncomingGepEdge(edge);
return edge;
}
/*!
* Add variant gep edge
*/
VariantGepCGEdge* ConstraintGraph::addVariantGepCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::VariantGep))
return nullptr;
VariantGepCGEdge* edge = new VariantGepCGEdge(srcNode, dstNode, edgeIndex++);
bool added = directEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingGepEdge(edge);
dstNode->addIncomingGepEdge(edge);
return edge;
}
/*!
* Add Load edge
*/
LoadCGEdge* ConstraintGraph::addLoadCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::Load))
return nullptr;
LoadCGEdge* edge = new LoadCGEdge(srcNode, dstNode, edgeIndex++);
bool added = LoadCGEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingLoadEdge(edge);
dstNode->addIncomingLoadEdge(edge);
return edge;
}
/*!
* Add Store edge
*/
StoreCGEdge* ConstraintGraph::addStoreCGEdge(NodeID src, NodeID dst)
{
ConstraintNode* srcNode = getConstraintNode(src);
ConstraintNode* dstNode = getConstraintNode(dst);
if(hasEdge(srcNode,dstNode,ConstraintEdge::Store))
return nullptr;
StoreCGEdge* edge = new StoreCGEdge(srcNode, dstNode, edgeIndex++);
bool added = StoreCGEdgeSet.insert(edge).second;
assert(added && "not added??");
srcNode->addOutgoingStoreEdge(edge);
dstNode->addIncomingStoreEdge(edge);
return edge;
}
/*!
* Re-target dst node of an edge
*
* (1) Remove edge from old dst target,
* (2) Change edge dst id and
* (3) Add modifed edge into new dst
*/
void ConstraintGraph::reTargetDstOfEdge(ConstraintEdge* edge, ConstraintNode* newDstNode)
{
NodeID newDstNodeID = newDstNode->getId();
NodeID srcId = edge->getSrcID();
if(LoadCGEdge* load = SVFUtil::dyn_cast<LoadCGEdge>(edge))
{
removeLoadEdge(load);
addLoadCGEdge(srcId,newDstNodeID);
}
else if(StoreCGEdge* store = SVFUtil::dyn_cast<StoreCGEdge>(edge))
{
removeStoreEdge(store);
addStoreCGEdge(srcId,newDstNodeID);
}
else if(CopyCGEdge* copy = SVFUtil::dyn_cast<CopyCGEdge>(edge))
{
removeDirectEdge(copy);
addCopyCGEdge(srcId,newDstNodeID);
}
else if(NormalGepCGEdge* gep = SVFUtil::dyn_cast<NormalGepCGEdge>(edge))
{
const LocationSet ls = gep->getLocationSet();
removeDirectEdge(gep);
addNormalGepCGEdge(srcId,newDstNodeID,ls);
}
else if(VariantGepCGEdge* gep = SVFUtil::dyn_cast<VariantGepCGEdge>(edge))
{
removeDirectEdge(gep);
addVariantGepCGEdge(srcId,newDstNodeID);
}
else if(AddrCGEdge* addr = SVFUtil::dyn_cast<AddrCGEdge>(edge))
{
removeAddrEdge(addr);
}
else
assert(false && "no other edge type!!");
}
/*!
* Re-target src node of an edge
* (1) Remove edge from old src target,
* (2) Change edge src id and
* (3) Add modified edge into new src
*/
void ConstraintGraph::reTargetSrcOfEdge(ConstraintEdge* edge, ConstraintNode* newSrcNode)
{
NodeID newSrcNodeID = newSrcNode->getId();
NodeID dstId = edge->getDstID();
if(LoadCGEdge* load = SVFUtil::dyn_cast<LoadCGEdge>(edge))
{
removeLoadEdge(load);
addLoadCGEdge(newSrcNodeID,dstId);
}
else if(StoreCGEdge* store = SVFUtil::dyn_cast<StoreCGEdge>(edge))
{
removeStoreEdge(store);
addStoreCGEdge(newSrcNodeID,dstId);
}
else if(CopyCGEdge* copy = SVFUtil::dyn_cast<CopyCGEdge>(edge))
{
removeDirectEdge(copy);
addCopyCGEdge(newSrcNodeID,dstId);
}
else if(NormalGepCGEdge* gep = SVFUtil::dyn_cast<NormalGepCGEdge>(edge))
{
const LocationSet ls = gep->getLocationSet();
removeDirectEdge(gep);
addNormalGepCGEdge(newSrcNodeID,dstId,ls);
}
else if(VariantGepCGEdge* gep = SVFUtil::dyn_cast<VariantGepCGEdge>(edge))
{
removeDirectEdge(gep);
addVariantGepCGEdge(newSrcNodeID,dstId);
}
else if(AddrCGEdge* addr = SVFUtil::dyn_cast<AddrCGEdge>(edge))
{
removeAddrEdge(addr);
}
else
assert(false && "no other edge type!!");
}
/*!
* Remove addr edge from their src and dst edge sets
*/
void ConstraintGraph::removeAddrEdge(AddrCGEdge* edge)
{
getConstraintNode(edge->getSrcID())->removeOutgoingAddrEdge(edge);
getConstraintNode(edge->getDstID())->removeIncomingAddrEdge(edge);
Size_t num = AddrCGEdgeSet.erase(edge);
delete edge;
assert(num && "edge not in the set, can not remove!!!");
}
/*!
* Remove load edge from their src and dst edge sets
*/
void ConstraintGraph::removeLoadEdge(LoadCGEdge* edge)
{
getConstraintNode(edge->getSrcID())->removeOutgoingLoadEdge(edge);
getConstraintNode(edge->getDstID())->removeIncomingLoadEdge(edge);
Size_t num = LoadCGEdgeSet.erase(edge);
delete edge;
assert(num && "edge not in the set, can not remove!!!");
}
/*!
* Remove store edge from their src and dst edge sets
*/
void ConstraintGraph::removeStoreEdge(StoreCGEdge* edge)
{
getConstraintNode(edge->getSrcID())->removeOutgoingStoreEdge(edge);
getConstraintNode(edge->getDstID())->removeIncomingStoreEdge(edge);
Size_t num = StoreCGEdgeSet.erase(edge);
delete edge;
assert(num && "edge not in the set, can not remove!!!");
}
/*!
* Remove edges from their src and dst edge sets
*/
void ConstraintGraph::removeDirectEdge(ConstraintEdge* edge)
{
getConstraintNode(edge->getSrcID())->removeOutgoingDirectEdge(edge);
getConstraintNode(edge->getDstID())->removeIncomingDirectEdge(edge);
Size_t num = directEdgeSet.erase(edge);
assert(num && "edge not in the set, can not remove!!!");
delete edge;
}
/*!
* Move incoming direct edges of a sub node which is outside SCC to its rep node
* Remove incoming direct edges of a sub node which is inside SCC from its rep node
*/
bool ConstraintGraph::moveInEdgesToRepNode(ConstraintNode* node, ConstraintNode* rep )
{
std::vector<ConstraintEdge*> sccEdges;
std::vector<ConstraintEdge*> nonSccEdges;
for (ConstraintNode::const_iterator it = node->InEdgeBegin(), eit = node->InEdgeEnd(); it != eit;
++it)
{
ConstraintEdge* subInEdge = *it;
if(sccRepNode(subInEdge->getSrcID()) != rep->getId())
nonSccEdges.push_back(subInEdge);
else
{
sccEdges.push_back(subInEdge);
}
}
// if this edge is outside scc, then re-target edge dst to rep
while(!nonSccEdges.empty())
{
ConstraintEdge* edge = nonSccEdges.back();
nonSccEdges.pop_back();
reTargetDstOfEdge(edge,rep);
}
bool criticalGepInsideSCC = false;
// if this edge is inside scc, then remove this edge and two end nodes
while(!sccEdges.empty())
{
ConstraintEdge* edge = sccEdges.back();
sccEdges.pop_back();
/// only copy and gep edge can be removed
if(SVFUtil::isa<CopyCGEdge>(edge))
removeDirectEdge(edge);
else if (SVFUtil::isa<GepCGEdge>(edge))
{
// If the GEP is critical (i.e. may have a non-zero offset),
// then it brings impact on field-sensitivity.
if (!isZeroOffsettedGepCGEdge(edge))
{
criticalGepInsideSCC = true;
}
removeDirectEdge(edge);
}
else if(SVFUtil::isa<LoadCGEdge>(edge) || SVFUtil::isa<StoreCGEdge>(edge))
reTargetDstOfEdge(edge,rep);
else if(AddrCGEdge* addr = SVFUtil::dyn_cast<AddrCGEdge>(edge))
{
removeAddrEdge(addr);
}
else
assert(false && "no such edge");
}
return criticalGepInsideSCC;
}
/*!
* Move outgoing direct edges of a sub node which is outside SCC to its rep node
* Remove outgoing direct edges of a sub node which is inside SCC from its rep node
*/
bool ConstraintGraph::moveOutEdgesToRepNode(ConstraintNode*node, ConstraintNode* rep )
{
std::vector<ConstraintEdge*> sccEdges;
std::vector<ConstraintEdge*> nonSccEdges;
for (ConstraintNode::const_iterator it = node->OutEdgeBegin(), eit = node->OutEdgeEnd(); it != eit;
++it)
{
ConstraintEdge* subOutEdge = *it;
if(sccRepNode(subOutEdge->getDstID()) != rep->getId())
nonSccEdges.push_back(subOutEdge);
else
{
sccEdges.push_back(subOutEdge);
}
}
// if this edge is outside scc, then re-target edge src to rep
while(!nonSccEdges.empty())
{
ConstraintEdge* edge = nonSccEdges.back();
nonSccEdges.pop_back();
reTargetSrcOfEdge(edge,rep);
}
bool criticalGepInsideSCC = false;
// if this edge is inside scc, then remove this edge and two end nodes
while(!sccEdges.empty())
{
ConstraintEdge* edge = sccEdges.back();
sccEdges.pop_back();
/// only copy and gep edge can be removed
if(SVFUtil::isa<CopyCGEdge>(edge))
removeDirectEdge(edge);
else if (SVFUtil::isa<GepCGEdge>(edge))
{
// If the GEP is critical (i.e. may have a non-zero offset),
// then it brings impact on field-sensitivity.
if (!isZeroOffsettedGepCGEdge(edge))
{
criticalGepInsideSCC = true;
}
removeDirectEdge(edge);
}
else if(SVFUtil::isa<LoadCGEdge>(edge) || SVFUtil::isa<StoreCGEdge>(edge))
reTargetSrcOfEdge(edge,rep);
else if(AddrCGEdge* addr = SVFUtil::dyn_cast<AddrCGEdge>(edge))
{
removeAddrEdge(addr);
}
else
assert(false && "no such edge");
}
return criticalGepInsideSCC;
}
/*!
* Dump constraint graph
*/
void ConstraintGraph::dump(std::string name)
{
GraphPrinter::WriteGraphToFile(outs(), name, this);
}
/*!
* Print this constraint graph including its nodes and edges
*/
void ConstraintGraph::print()
{
outs() << "-----------------ConstraintGraph--------------------------------------\n";
ConstraintEdge::ConstraintEdgeSetTy& addrs = this->getAddrCGEdges();
for (ConstraintEdge::ConstraintEdgeSetTy::iterator iter = addrs.begin(),
eiter = addrs.end(); iter != eiter; ++iter)
{
outs() << (*iter)->getSrcID() << " -- Addr --> " << (*iter)->getDstID()
<< "\n";
}
ConstraintEdge::ConstraintEdgeSetTy& directs = this->getDirectCGEdges();
for (ConstraintEdge::ConstraintEdgeSetTy::iterator iter = directs.begin(),
eiter = directs.end(); iter != eiter; ++iter)
{
if (CopyCGEdge* copy = SVFUtil::dyn_cast<CopyCGEdge>(*iter))
{
outs() << copy->getSrcID() << " -- Copy --> " << copy->getDstID()
<< "\n";
}
else if (NormalGepCGEdge* ngep = SVFUtil::dyn_cast<NormalGepCGEdge>(*iter))
{
outs() << ngep->getSrcID() << " -- NormalGep (" << ngep->getOffset()
<< ") --> " << ngep->getDstID() << "\n";
}
else if (VariantGepCGEdge* vgep = SVFUtil::dyn_cast<VariantGepCGEdge>(*iter))
{
outs() << vgep->getSrcID() << " -- VarintGep --> "
<< vgep->getDstID() << "\n";
}
else
assert(false && "wrong constraint edge kind!");
}
ConstraintEdge::ConstraintEdgeSetTy& loads = this->getLoadCGEdges();
for (ConstraintEdge::ConstraintEdgeSetTy::iterator iter = loads.begin(),
eiter = loads.end(); iter != eiter; ++iter)
{
outs() << (*iter)->getSrcID() << " -- Load --> " << (*iter)->getDstID()
<< "\n";
}
ConstraintEdge::ConstraintEdgeSetTy& stores = this->getStoreCGEdges();
for (ConstraintEdge::ConstraintEdgeSetTy::iterator iter = stores.begin(),
eiter = stores.end(); iter != eiter; ++iter)
{
outs() << (*iter)->getSrcID() << " -- Store --> " << (*iter)->getDstID()
<< "\n";
}
outs()
<< "--------------------------------------------------------------\n";
}
/*!
* View dot graph of Constraint graph from debugger.
*/
void ConstraintGraph::view() {
llvm::ViewGraph(this, "Constraint Graph");
}
/*!
* GraphTraits specialization for constraint graph
*/
namespace llvm
{
template<>
struct DOTGraphTraits<ConstraintGraph*> : public DOTGraphTraits<PAG*>
{
typedef ConstraintNode NodeType;
DOTGraphTraits(bool isSimple = false) :
DOTGraphTraits<PAG*>(isSimple)
{
}
/// Return name of the graph
static std::string getGraphName(ConstraintGraph*)
{
return "ConstraintG";
}
#if LLVM_VERSION_MAJOR >= 12
static bool isNodeHidden(NodeType *n, ConstraintGraph*) {
#else
static bool isNodeHidden(NodeType *n) {
#endif
PAGNode* node = PAG::getPAG()->getPAGNode(n->getId());
return node->isIsolatedNode();
}
/// Return label of a VFG node with two display mode
/// Either you can choose to display the name of the value or the whole instruction
static std::string getNodeLabel(NodeType *n, ConstraintGraph*)
{
PAGNode* node = PAG::getPAG()->getPAGNode(n->getId());
bool briefDisplay = Options::BriefConsCGDotGraph;
bool nameDisplay = true;
std::string str;
raw_string_ostream rawstr(str);
if (briefDisplay)
{
if (SVFUtil::isa<ValPN>(node))
{
if (nameDisplay)
rawstr << node->getId() << ":" << node->getValueName();
else
rawstr << node->getId();
}
else
rawstr << node->getId();
}
else
{
// print the whole value
if (!SVFUtil::isa<DummyValPN>(node) && !SVFUtil::isa<DummyObjPN>(node))
rawstr << node->getId() << ":" << value2String(node->getValue());
else
rawstr << node->getId() << ":";
}
return rawstr.str();
}
static std::string getNodeAttributes(NodeType *n, ConstraintGraph*)
{
PAGNode* node = PAG::getPAG()->getPAGNode(n->getId());
return node->getNodeAttrForDotDisplay();
}
template<class EdgeIter>
static std::string getEdgeAttributes(NodeType*, EdgeIter EI, ConstraintGraph*)
{
ConstraintEdge* edge = *(EI.getCurrent());
assert(edge && "No edge found!!");
if (edge->getEdgeKind() == ConstraintEdge::Addr)
{
return "color=green";
}
else if (edge->getEdgeKind() == ConstraintEdge::Copy)
{
return "color=black";
}
else if (edge->getEdgeKind() == ConstraintEdge::NormalGep
|| edge->getEdgeKind() == ConstraintEdge::VariantGep)
{
return "color=purple";
}
else if (edge->getEdgeKind() == ConstraintEdge::Store)
{
return "color=blue";
}
else if (edge->getEdgeKind() == ConstraintEdge::Load)
{
return "color=red";
}
else
{
assert(0 && "No such kind edge!!");
}
return "";
}
template<class EdgeIter>
static std::string getEdgeSourceLabel(NodeType*, EdgeIter)
{
return "";
}
};
} // End namespace llvm
|
#include <QApplication>
#include "guiutil.h"
#include "Flashpaychainaddressvalidator.h"
#include "walletmodel.h"
#include "Flashpaychainunits.h"
#include "util.h"
#include "init.h"
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#else
#include <QUrl>
#endif
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont FlashpaychainAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(FlashpaychainAddressValidator::MaxAddressLength);
widget->setValidator(new FlashpaychainAddressValidator(parent));
widget->setFont(FlashpaychainAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseFlashpaychainURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no Flashpaychain URI
if(!uri.isValid() || (uri.scheme() != QString("Flashpaychain") && uri.scheme() != QString("ppcoin")))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!FlashpaychainUnits::parse(FlashpaychainUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseFlashpaychainURI(QString uri, SendCoinsRecipient *out)
{
// Convert Flashpaychain:// to Flashpaychain:
//
// Cannot handle this later, because Flashpaychain:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("Flashpaychain://"))
{
uri.replace(0, 11, "Flashpaychain:");
}
if(uri.startsWith("ppcoin://"))
{
uri.replace(0, 9, "ppcoin:");
}
QUrl uriInstance(uri);
return parseFlashpaychainURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item (global clipboard)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard);
// Copy first item (global mouse selection for e.g. X11 - NOP on Windows)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection);
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Flashpaychain.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Flashpaychain.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "Flashpaychain.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a Flashpaychain.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Flashpaychain\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("Flashpaychain-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" Flashpaychain-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("Flashpaychain-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
|
/*===========================================================================
_____ _____ _____ _____
___| _|__ __|_ |__ __|__ |__ __| __ |__ ______
| \ / | || \ || | || |/ / ||___ |
| \/ | || \ || \ || \ ||___ |
|__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______|
|_____| |_____| |_____| |_____|
--[Mark3 Realtime Platform]--------------------------------------------------
Copyright (c) 2012-2016 Funkenstein Software Consulting, all rights reserved.
See license.txt for more information
=========================================================================== */
/*!
\file autoalloc.cpp
\brief Automatic memory allocation for kernel objects.
*/
#include "mark3cfg.h"
#include "mark3.h"
#include "autoalloc.h"
#include "threadport.h"
#include "kernel.h"
#if KERNEL_USE_AUTO_ALLOC
// Align to nearest word boundary
#define ALLOC_ALIGN(x) ( ((x) + (sizeof(K_ADDR)-1)) & (sizeof(K_ADDR) - 1) )
//---------------------------------------------------------------------------
uint8_t AutoAlloc::m_au8AutoHeap[ AUTO_ALLOC_SIZE ];
K_ADDR AutoAlloc::m_aHeapTop;
//---------------------------------------------------------------------------
void AutoAlloc::Init(void)
{
m_aHeapTop = (K_ADDR)(m_au8AutoHeap);
}
//---------------------------------------------------------------------------
void *AutoAlloc::Allocate( uint16_t u16Size_ )
{
void *pvRet = 0;
CS_ENTER();
uint16_t u16AllocSize = ALLOC_ALIGN(u16Size_);
if ((((K_ADDR)m_aHeapTop - (K_ADDR)&m_au8AutoHeap[0]) + u16AllocSize) < AUTO_ALLOC_SIZE)
{
pvRet = (void*)m_aHeapTop;
m_aHeapTop += u16AllocSize;
}
CS_EXIT();
if (!pvRet)
{
Kernel::Panic(PANIC_AUTO_HEAP_EXHUSTED);
}
return pvRet;
}
#if KERNEL_USE_SEMAPHORE
//---------------------------------------------------------------------------
Semaphore *AutoAlloc::NewSemaphore(void)
{
void *pvObj = Allocate(sizeof(Semaphore));
if (pvObj)
{
return new(pvObj) Semaphore();
}
return 0;
}
#endif
#if KERNEL_USE_MUTEX
//---------------------------------------------------------------------------
Mutex *AutoAlloc::NewMutex(void)
{
void *pvObj = Allocate(sizeof(Mutex));
if (pvObj)
{
return new(pvObj) Mutex();
}
return 0;
}
#endif
#if KERNEL_USE_EVENTFLAG
//---------------------------------------------------------------------------
EventFlag *AutoAlloc::NewEventFlag(void)
{
void *pvObj = Allocate(sizeof(EventFlag));
if (pvObj)
{
return new(pvObj) EventFlag();
}
return 0;
}
#endif
#if KERNEL_USE_MESSAGE
//---------------------------------------------------------------------------
Message *AutoAlloc::NewMessage(void)
{
void *pvObj = Allocate(sizeof(Message));
if (pvObj)
{
return new(pvObj) Message();
}
return 0;
}
//---------------------------------------------------------------------------
MessageQueue *AutoAlloc::NewMessageQueue(void)
{
void *pvObj = Allocate(sizeof(MessageQueue));
if (pvObj)
{
return new(pvObj) MessageQueue();
}
return 0;
}
#endif
#if KERNEL_USE_NOTIFY
//---------------------------------------------------------------------------
Notify *AutoAlloc::NewNotify(void)
{
void *pvObj = Allocate(sizeof(Notify));
if (pvObj)
{
return new(pvObj) Notify();
}
return 0;
}
#endif
#if KERNEL_USE_MAILBOX
//---------------------------------------------------------------------------
Mailbox *AutoAlloc::NewMailbox(void)
{
void *pvObj = Allocate(sizeof(Mailbox));
if (pvObj)
{
return new(pvObj) Mailbox();
}
return 0;
}
#endif
//---------------------------------------------------------------------------
Thread *AutoAlloc::NewThread(void)
{
void *pvObj = Allocate(sizeof(Thread));
if (pvObj)
{
return new(pvObj) Thread();
}
return 0;
}
#if KERNEL_USE_TIMERS
//---------------------------------------------------------------------------
Timer *AutoAlloc::NewTimer(void)
{
void *pvObj = Allocate(sizeof(Timer));
if (pvObj)
{
return new(pvObj) Timer();
}
return 0;
}
#endif
#endif
|
int minSpan(int N,vector<vector<int>>adj[])
{
int key[N+1];
bool mstSet[N+1];
for (int i = 0; i <= N; i++)
key[i] = INT_MAX, mstSet[i] = false;
priority_queue< pair<int,int>, vector <pair<int,int>> , greater<pair<int,int>> > pq;
key[0] = 0;
pq.push({0, 0});
while(!pq.empty())
{
int u = pq.top().second;
pq.pop();
mstSet[u] = true;
for (auto it : adj[u]) {
int v = it[0];
int weight = it[1];
if (mstSet[v] == false && weight < key[v]) {
key[v] = weight;
pq.push({key[v], v});
}
}
}
int sum = 0;
for(int i = 1;i<=N;i++) {
if(key[i] != INT_MAX)
sum += key[i];
}
return sum;
}
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/eager/eager_executor.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
namespace tensorflow {
EagerExecutor::EagerExecutor(bool async)
: next_node_id_(0),
thread_(async ? tensorflow::Env::Default()->StartThread(
tensorflow::ThreadOptions(), "eager_async_executor",
std::bind(&EagerExecutor::Run, this))
: nullptr) {}
EagerExecutor::~EagerExecutor() {
tensorflow::mutex_lock l(node_queue_mutex_);
state_ = ExecutorState::kShutDown;
nodes_pending_.notify_all();
}
Status EagerExecutor::ShutDown() {
{
std::vector<core::RefCountPtr<NodeItem>> items_to_destroy;
bool has_thread;
Status status;
{
tensorflow::mutex_lock l(node_queue_mutex_);
if (state_ != ExecutorState::kShutDown) {
// if the state is kShutDown, we don't return here because we want to
// make sure the executor thread has ended (if there is one).
// So, we fall through to
// thread_exited_notification_.WaitForNotification() below.
state_ = ExecutorState::kShuttingDown;
}
// It is OK to ignore the returned status here because it will be saved
// as the final status_.
WaitForAllPendingNodesLocked(&l).IgnoreError();
state_ = ExecutorState::kShutDown;
has_thread = thread_ != nullptr;
status = status_;
if (has_thread) {
nodes_pending_.notify_all();
}
}
for (auto& item : items_to_destroy) {
item->node->Abort(status);
}
if (!has_thread) {
return status;
}
}
thread_exited_notification_.WaitForNotification();
tensorflow::mutex_lock l(node_queue_mutex_);
return status_;
}
bool EagerExecutor::Async() const {
return thread_ != nullptr;
}
const char* EagerExecutor::StateStringLocked() {
switch (state_) {
case ExecutorState::kActive:
return "Active";
case ExecutorState::kShuttingDown:
return "ShuttingDown";
case ExecutorState::kShutDown:
return "ShutDown";
}
}
Status EagerExecutor::AddOrExecute(std::unique_ptr<EagerNode> node) {
Status status;
core::RefCountPtr<NodeItem> item(new NodeItem);
item->id = next_node_id_++;
item->node = std::move(node);
item->state = NodeState::kPENDING;
// If we are unable to add the node to the queue, we must call Abort. However,
// we want to do that outside of the scope of the lock since the Abort may
// try to call EagerExecutor::Add()
{
tensorflow::mutex_lock l(node_queue_mutex_);
VLOG(3) << "Add node [id " << item->id << "]" << item->node->DebugString()
<< " with status: " << status_.ToString();
if (state_ != ExecutorState::kActive) {
status = errors::FailedPrecondition(
"EagerExecutor accepts new EagerNodes to run only in Active state. "
"Current state is '",
StateStringLocked(), "'");
} else {
status = status_;
if (status.ok() && Async()) {
node_queue_.push(std::move(item));
// If there were no previous nodes pending, wake the run thread to
// start processing requests again.
if (node_queue_.size() == 1) {
nodes_pending_.notify_all();
}
return Status::OK();
}
}
}
if (status.ok()) {
// Inline execution in sync mode.
DCHECK(!Async());
RunItem(std::move(item));
status = this->status();
return status;
} else {
// Node needs to be aborted since it was not added to the queue
item->node->Abort(status);
return status;
}
}
tensorflow::Status EagerExecutor::WaitForAllPendingNodes() {
tensorflow::mutex_lock l(node_queue_mutex_);
return WaitForAllPendingNodesLocked(&l);
}
tensorflow::Status EagerExecutor::WaitForAllPendingNodesLocked(
mutex_lock* lock) {
tensorflow::condition_variable cond;
// Don't wait if an error is already set.
if (!status_.ok()) return status_;
if (node_queue_.empty() && unfinished_nodes_.empty())
return tensorflow::Status::OK();
// node_queue_ must be empty in sync mode.
DCHECK(Async() || node_queue_.empty());
auto last_id = next_node_id_ - 1;
VLOG(3) << "Wait for Node: [id " << last_id << "] ";
node_done_notifications_.insert(std::make_pair(last_id, &cond));
cond.wait(*lock);
// Note that we could be woken up if an error occurs, even though the node has
// not actually executed.
return status_;
}
void EagerExecutor::ClearError() {
tensorflow::mutex_lock l(node_queue_mutex_);
// TODO(iga): Check state_ and return an error if it is not kActive.
if (status_.ok()) return;
// If an error was set, node_done_notifications_ and node_queue_ should have
// been cleared, and no new entries should have been added since.
DCHECK(node_done_notifications_.empty());
DCHECK(node_queue_.empty());
status_ = tensorflow::Status::OK();
nodes_pending_.notify_all();
}
tensorflow::Status EagerExecutor::status() const {
tf_shared_lock l(node_queue_mutex_);
return status_;
}
void EagerExecutor::NodeDone(core::RefCountPtr<NodeItem> item,
const Status& status) {
VLOG(3) << "Node Done: [id " << item->id << "] " << item->node->DebugString()
<< " with status: " << status.ToString();
DCHECK(item->state != NodeState::kDONE);
std::vector<core::RefCountPtr<NodeItem>> items_to_destroy;
{
mutex_lock l(node_queue_mutex_);
auto previous_state = item->state;
item->state = NodeState::kDONE;
if (!status_.ok()) return;
bool need_notification = false;
if (previous_state == NodeState::kPENDING) {
if (Async()) {
DCHECK(!node_queue_.empty() && item.get() == node_queue_.front().get());
need_notification = unfinished_nodes_.empty();
node_queue_.pop();
} else {
need_notification = unfinished_nodes_.empty();
}
} else {
need_notification = item->id == unfinished_nodes_.begin()->first;
auto result = unfinished_nodes_.erase(item->id);
DCHECK_GT(result, 0);
}
if (!status.ok()) {
need_notification = true;
status_ = status;
// We remove any pending ops so that we don't try to execute them if
// ClearError is called.
errors::AppendToMessage(&status_,
"Encountered when executing an operation using "
"EagerExecutor. This error cancels all future "
"operations and poisons their output tensors.");
while (!node_queue_.empty()) {
items_to_destroy.push_back(std::move(node_queue_.front()));
node_queue_.pop();
}
for (auto& it : unfinished_nodes_) {
items_to_destroy.push_back(std::move(it.second));
}
unfinished_nodes_.clear();
}
if (!node_done_notifications_.empty() && need_notification) {
uint64 upperbound_id = 0;
if (!unfinished_nodes_.empty()) {
upperbound_id = unfinished_nodes_.begin()->first - 1;
} else if (!node_queue_.empty()) {
upperbound_id = node_queue_.front()->id - 1;
} else {
upperbound_id = next_node_id_ - 1;
}
VLOG(3) << "Notify node done: [id " << item->id << " to " << upperbound_id
<< "] ";
// Note that we notify all waiting threads in case an error has
// occurred. These calling threads are responsible for checking status_
// before proceeding.
const auto range =
status_.ok()
? make_pair(node_done_notifications_.lower_bound(item->id),
node_done_notifications_.upper_bound(upperbound_id))
: make_pair(node_done_notifications_.begin(),
node_done_notifications_.end());
for (auto it = range.first; it != range.second; ++it) {
it->second->notify_all();
}
node_done_notifications_.erase(range.first, range.second);
}
}
for (auto& item : items_to_destroy) {
item->node->Abort(status);
}
// nodes_to_destroy will be destructed here, while not holding
// node_queue_mutex_. This is important because, unfortunately, some nodes'
// destructors can enqueue more operations onto this executor and cause
// a deadlock.
}
void EagerExecutor::Run() {
auto thread_exited_notifier =
gtl::MakeCleanup([this] { thread_exited_notification_.Notify(); });
while (true) {
core::RefCountPtr<NodeItem> curr_item;
{
tensorflow::mutex_lock l(node_queue_mutex_);
while (node_queue_.empty() || !status_.ok()) {
if (state_ == ExecutorState::kShutDown) return;
nodes_pending_.wait(l);
}
// Obtain raw pointer since we don't want to remove from the queue until
// the node has been run. Otherwise, WaitForAllPendingNodes can return
// too early.
// Note, we don't std::move from the here because the front of the queue
// will then contain a nullptr. This can be a problem in
// WaitForAllPendingNodes where we get the top EagerNode pointer
// and register a notification for its completion.
curr_item.reset(node_queue_.front().get());
curr_item->Ref();
}
RunItem(std::move(curr_item));
}
}
void EagerExecutor::RunItem(core::RefCountPtr<NodeItem> item) {
VLOG(3) << "Running Node: [id " << item->id << "] "
<< item->node->DebugString();
AsyncEagerNode* async_node = item->node->AsAsync();
if (async_node == nullptr) {
core::RefCountPtr<NodeItem> new_ref(item.get());
new_ref->Ref();
tensorflow::Status status = item->node->Run();
NodeDone(std::move(new_ref), status);
} else {
auto* new_ref = item.get();
new_ref->Ref();
async_node->RunAsync([this, new_ref](const Status& status) {
core::RefCountPtr<NodeItem> new_item(new_ref);
NodeDone(std::move(new_item), status);
});
}
tensorflow::mutex_lock l(node_queue_mutex_);
if (item->state == NodeState::kPENDING) {
item->state = NodeState::kSCHEDULED;
if (!node_queue_.empty() && item.get() == node_queue_.front().get()) {
node_queue_.pop();
}
VLOG(3) << "Add Node: [id " << item->id << "] to unfinished map.";
unfinished_nodes_.emplace_hint(unfinished_nodes_.end(), item->id,
std::move(item));
}
}
} // namespace tensorflow
|
// MethodProps.cpp
#include "StdAfx.h"
#include "../../Common/StringToInt.h"
#include "MethodProps.h"
using namespace NWindows;
bool StringToBool(const UString &s, bool &res)
{
if (s.IsEmpty() || s == L"+" || StringsAreEqualNoCase_Ascii(s, "ON"))
{
res = true;
return true;
}
if (s == L"-" || StringsAreEqualNoCase_Ascii(s, "OFF"))
{
res = false;
return true;
}
return false;
}
HRESULT PROPVARIANT_to_bool(const PROPVARIANT &prop, bool &dest)
{
switch (prop.vt)
{
case VT_EMPTY: dest = true; return S_OK;
case VT_BOOL: dest = (prop.boolVal != VARIANT_FALSE); return S_OK;
case VT_BSTR: return StringToBool(prop.bstrVal, dest) ? S_OK : E_INVALIDARG;
}
return E_INVALIDARG;
}
unsigned ParseStringToUInt32(const UString &srcString, UInt32 &number)
{
const wchar_t *start = srcString;
const wchar_t *end;
number = ConvertStringToUInt32(start, &end);
return (unsigned)(end - start);
}
HRESULT ParsePropToUInt32(const UString &name, const PROPVARIANT &prop, UInt32 &resValue)
{
// =VT_UI4
// =VT_EMPTY
// {stringUInt32}=VT_EMPTY
if (prop.vt == VT_UI4)
{
if (!name.IsEmpty())
return E_INVALIDARG;
resValue = prop.ulVal;
return S_OK;
}
if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
if (name.IsEmpty())
return S_OK;
UInt32 v;
if (ParseStringToUInt32(name, v) != name.Len())
return E_INVALIDARG;
resValue = v;
return S_OK;
}
HRESULT ParseMtProp(const UString &name, const PROPVARIANT &prop, UInt32 defaultNumThreads, UInt32 &numThreads)
{
if (name.IsEmpty())
{
switch (prop.vt)
{
case VT_UI4:
numThreads = prop.ulVal;
break;
default:
{
bool val;
RINOK(PROPVARIANT_to_bool(prop, val));
numThreads = (val ? defaultNumThreads : 1);
break;
}
}
return S_OK;
}
if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
return ParsePropToUInt32(name, prop, numThreads);
}
static HRESULT StringToDictSize(const UString &s, UInt32 &dicSize)
{
const wchar_t *end;
UInt32 number = ConvertStringToUInt32(s, &end);
unsigned numDigits = (unsigned)(end - s);
if (numDigits == 0 || s.Len() > numDigits + 1)
return E_INVALIDARG;
const unsigned kLogDictSizeLimit = 32;
if (s.Len() == numDigits)
{
if (number >= kLogDictSizeLimit)
return E_INVALIDARG;
dicSize = (UInt32)1 << (unsigned)number;
return S_OK;
}
unsigned numBits;
switch (MyCharLower_Ascii(s[numDigits]))
{
case 'b': dicSize = number; return S_OK;
case 'k': numBits = 10; break;
case 'm': numBits = 20; break;
case 'g': numBits = 30; break;
default: return E_INVALIDARG;
}
if (number >= ((UInt32)1 << (kLogDictSizeLimit - numBits)))
return E_INVALIDARG;
dicSize = number << numBits;
return S_OK;
}
static HRESULT PROPVARIANT_to_DictSize(const PROPVARIANT &prop, UInt32 &resValue)
{
if (prop.vt == VT_UI4)
{
UInt32 v = prop.ulVal;
if (v >= 32)
return E_INVALIDARG;
resValue = (UInt32)1 << v;
return S_OK;
}
if (prop.vt == VT_BSTR)
return StringToDictSize(prop.bstrVal, resValue);
return E_INVALIDARG;
}
void CProps::AddProp32(PROPID propid, UInt32 level)
{
CProp prop;
prop.IsOptional = true;
prop.Id = propid;
prop.Value = (UInt32)level;
Props.Add(prop);
}
class CCoderProps
{
PROPID *_propIDs;
NCOM::CPropVariant *_props;
unsigned _numProps;
unsigned _numPropsMax;
public:
CCoderProps(unsigned numPropsMax)
{
_numPropsMax = numPropsMax;
_numProps = 0;
_propIDs = new PROPID[numPropsMax];
_props = new NCOM::CPropVariant[numPropsMax];
}
~CCoderProps()
{
delete []_propIDs;
delete []_props;
}
void AddProp(const CProp &prop);
HRESULT SetProps(ICompressSetCoderProperties *setCoderProperties)
{
return setCoderProperties->SetCoderProperties(_propIDs, _props, _numProps);
}
};
void CCoderProps::AddProp(const CProp &prop)
{
if (_numProps >= _numPropsMax)
throw 1;
_propIDs[_numProps] = prop.Id;
_props[_numProps] = prop.Value;
_numProps++;
}
HRESULT CProps::SetCoderProps(ICompressSetCoderProperties *scp, const UInt64 *dataSizeReduce) const
{
CCoderProps coderProps(Props.Size() + (dataSizeReduce ? 1 : 0));
FOR_VECTOR (i, Props)
coderProps.AddProp(Props[i]);
if (dataSizeReduce)
{
CProp prop;
prop.Id = NCoderPropID::kReduceSize;
prop.Value = *dataSizeReduce;
coderProps.AddProp(prop);
}
return coderProps.SetProps(scp);
}
int CMethodProps::FindProp(PROPID id) const
{
for (int i = Props.Size() - 1; i >= 0; i--)
if (Props[i].Id == id)
return i;
return -1;
}
int CMethodProps::GetLevel() const
{
int i = FindProp(NCoderPropID::kLevel);
if (i < 0)
return 5;
if (Props[i].Value.vt != VT_UI4)
return 9;
UInt32 level = Props[i].Value.ulVal;
return level > 9 ? 9 : (int)level;
}
struct CNameToPropID
{
VARTYPE VarType;
const char *Name;
};
static const CNameToPropID g_NameToPropID[] =
{
{ VT_UI4, "" },
{ VT_UI4, "d" },
{ VT_UI4, "mem" },
{ VT_UI4, "o" },
{ VT_UI4, "c" },
{ VT_UI4, "pb" },
{ VT_UI4, "lc" },
{ VT_UI4, "lp" },
{ VT_UI4, "fb" },
{ VT_BSTR, "mf" },
{ VT_UI4, "mc" },
{ VT_UI4, "pass" },
{ VT_UI4, "a" },
{ VT_UI4, "mt" },
{ VT_BOOL, "eos" },
{ VT_UI4, "x" },
{ VT_UI4, "reduceSize" }
};
static int FindPropIdExact(const UString &name)
{
for (unsigned i = 0; i < ARRAY_SIZE(g_NameToPropID); i++)
if (StringsAreEqualNoCase_Ascii(name, g_NameToPropID[i].Name))
return i;
return -1;
}
static bool ConvertProperty(const PROPVARIANT &srcProp, VARTYPE varType, NCOM::CPropVariant &destProp)
{
if (varType == srcProp.vt)
{
destProp = srcProp;
return true;
}
if (varType == VT_BOOL)
{
bool res;
if (PROPVARIANT_to_bool(srcProp, res) != S_OK)
return false;
destProp = res;
return true;
}
if (srcProp.vt == VT_EMPTY)
{
destProp = srcProp;
return true;
}
return false;
}
static void SplitParams(const UString &srcString, UStringVector &subStrings)
{
subStrings.Clear();
UString s;
int len = srcString.Len();
if (len == 0)
return;
for (int i = 0; i < len; i++)
{
wchar_t c = srcString[i];
if (c == L':')
{
subStrings.Add(s);
s.Empty();
}
else
s += c;
}
subStrings.Add(s);
}
static void SplitParam(const UString ¶m, UString &name, UString &value)
{
int eqPos = param.Find(L'=');
if (eqPos >= 0)
{
name.SetFrom(param, eqPos);
value = param.Ptr(eqPos + 1);
return;
}
unsigned i;
for (i = 0; i < param.Len(); i++)
{
wchar_t c = param[i];
if (c >= L'0' && c <= L'9')
break;
}
name.SetFrom(param, i);
value = param.Ptr(i);
}
static bool IsLogSizeProp(PROPID propid)
{
switch (propid)
{
case NCoderPropID::kDictionarySize:
case NCoderPropID::kUsedMemorySize:
case NCoderPropID::kBlockSize:
case NCoderPropID::kReduceSize:
return true;
}
return false;
}
HRESULT CMethodProps::SetParam(const UString &name, const UString &value)
{
int index = FindPropIdExact(name);
if (index < 0)
return E_INVALIDARG;
const CNameToPropID &nameToPropID = g_NameToPropID[index];
CProp prop;
prop.Id = index;
if (IsLogSizeProp(prop.Id))
{
UInt32 dicSize;
RINOK(StringToDictSize(value, dicSize));
prop.Value = dicSize;
}
else
{
NCOM::CPropVariant propValue;
if (nameToPropID.VarType == VT_BSTR)
propValue = value;
else if (nameToPropID.VarType == VT_BOOL)
{
bool res;
if (!StringToBool(value, res))
return E_INVALIDARG;
propValue = res;
}
else if (!value.IsEmpty())
{
UInt32 number;
if (ParseStringToUInt32(value, number) == value.Len())
propValue = number;
else
propValue = value;
}
if (!ConvertProperty(propValue, nameToPropID.VarType, prop.Value))
return E_INVALIDARG;
}
Props.Add(prop);
return S_OK;
}
HRESULT CMethodProps::ParseParamsFromString(const UString &srcString)
{
UStringVector params;
SplitParams(srcString, params);
FOR_VECTOR (i, params)
{
const UString ¶m = params[i];
UString name, value;
SplitParam(param, name, value);
RINOK(SetParam(name, value));
}
return S_OK;
}
HRESULT CMethodProps::ParseParamsFromPROPVARIANT(const UString &realName, const PROPVARIANT &value)
{
if (realName.Len() == 0)
{
// [empty]=method
return E_INVALIDARG;
}
if (value.vt == VT_EMPTY)
{
// {realName}=[empty]
UString name, value;
SplitParam(realName, name, value);
return SetParam(name, value);
}
// {realName}=value
int index = FindPropIdExact(realName);
if (index < 0)
return E_INVALIDARG;
const CNameToPropID &nameToPropID = g_NameToPropID[index];
CProp prop;
prop.Id = index;
if (IsLogSizeProp(prop.Id))
{
UInt32 dicSize;
RINOK(PROPVARIANT_to_DictSize(value, dicSize));
prop.Value = dicSize;
}
else
{
if (!ConvertProperty(value, nameToPropID.VarType, prop.Value))
return E_INVALIDARG;
}
Props.Add(prop);
return S_OK;
}
HRESULT COneMethodInfo::ParseMethodFromString(const UString &s)
{
int splitPos = s.Find(':');
MethodName = s;
if (splitPos < 0)
return S_OK;
MethodName.DeleteFrom(splitPos);
return ParseParamsFromString(s.Ptr(splitPos + 1));
}
HRESULT COneMethodInfo::ParseMethodFromPROPVARIANT(const UString &realName, const PROPVARIANT &value)
{
if (!realName.IsEmpty() && !StringsAreEqualNoCase_Ascii(realName, "m"))
return ParseParamsFromPROPVARIANT(realName, value);
// -m{N}=method
if (value.vt != VT_BSTR)
return E_INVALIDARG;
return ParseMethodFromString(value.bstrVal);
}
|
// // Copyright (c) 2014-2017 The Dash Core developers
// // Copyright (c) 2017-2017 The FOL Core developers
// // Distributed under the MIT/X11 software license, see the accompanying
// // file COPYING or http://www.opensource.org/licenses/mit-license.php.
// #ifndef GOVERNANCE_KEYS_H
// #define GOVERNANCE_KEYS_H
// #include <string>
// #include <vector>
// #include <map>
// #include <univalue.h>
// #include "support/allocators/secure.h"
// #include ""
// vector<CGovernanceKey> vGovernanceKeys;
// CCriticalSection cs_vGovernanceKeys;
// bool CGovernanceKeyManager::InitGovernanceKeys(std::string strError)
// {
// {
// LOCK(cs_vGovernanceKeys);
// vGovernanceKeys = mapMultiArgs["-addgovkey"];
// }
// BOOST_FOREACH(SecureString& strSecure, vGovernanceKeys)
// {
// std::vector<std::string> vecTokenized = SplitBy(strSubCommand, ":");
// if(vecTokenized.size() == 2) continue;
// CBitcoinSecret vchSecret;
// bool fGood = vchSecret.SetString(vecTokenized[0]);
// if(!fGood) {
// strError = "Invalid Governance Key : " + vecTokenized[0];
// return false;
// }
// CGovernanceKey key(vecTokenized[0], vecTokenized[1]);
// vGovernanceKeys.push_back(key);
// }
// }
|
// template <typename T>
// void f(ParamType parameter);
//
// f(expr)
// ParamType is neither a pointer nor a reference
// (so we are dealing with pass-by-value:
//
// Type deduction works like this:
// 1. If expr's type is a reference, ignore the reference part.
// 2. If, after ignoring expr's reference-ness, expr is const, ignore that too.
// If it's volatile, also ignore that.
#include <iostream>
using namespace std;
template <typename T>
void f(T parameter) {
cout << parameter << endl;
}
int main()
{
int x = 27;
const int cx = x;
const int& rx = x;
// "T" is "int"
// "ParamType" is "int"
f(x);
// "T" is "int"
// "ParamType" is "int"
f(cx);
// "T" is "int"
// "ParamType" is "int"
f(rx);
// "T" is "const char*" (?)
// "ParamType" is const char*
const char* const ptr = "Fun with pointers";
f(ptr);
return 0;
}
|
#ifndef GAME_SCRIPT_ANIMATIONEXTENSIONS_H
#define GAME_SCRIPT_ANIMATIONEXTENSIONS_H
namespace Compiler
{
class Extensions;
}
namespace Interpreter
{
class Interpreter;
}
namespace MWScript
{
namespace Animation
{
void registerExtensions (Compiler::Extensions& extensions);
void installOpcodes (Interpreter::Interpreter& interpreter);
}
}
#endif
|
#pragma once
#include "Engine/Core/DataUtils.hpp"
#include <memory>
#include <vector>
class Actor;
class Map;
class Renderer;
class Adventure {
public:
Adventure() noexcept = delete;
Adventure(const Adventure& other) noexcept = default;
Adventure(Adventure&& other) noexcept = default;
Adventure& operator=(const Adventure& other) noexcept = default;
Adventure& operator=(Adventure&& other) noexcept = default;
~Adventure() noexcept = default;
explicit Adventure(const XMLElement& elem) noexcept;
Actor* player{};
Map* currentMap{};
void NextMap() noexcept;
void PreviousMap() noexcept;
protected:
private:
bool LoadFromXml(const XMLElement& elem) noexcept;
void PlacePlayerNearEntrance() noexcept;
void PlacePlayerNearExit() noexcept;
std::string _name{"UNKNOWN ADVENTURE"};
std::vector<std::unique_ptr<class Map>> _maps{};
decltype(_maps)::iterator _current_map_iter{};
};
|
#ifndef TIN_NETWORK_BSDSOCKET_WRAPPER_EVENT_HPP
#define TIN_NETWORK_BSDSOCKET_WRAPPER_EVENT_HPP
#include "../../../utils/Event.hpp"
namespace tin { namespace network { namespace bsdsocket { namespace wrapper
{
class ClientVisitor;
struct Event:
public tin::utils::Event<tin::network::bsdsocket::wrapper::ClientVisitor>
{
virtual void accept(tin::network::bsdsocket::wrapper::ClientVisitor& i) = 0;
};
}}}}
#endif /* TIN_NETWORK_BSDSOCKET_WRAPPER_EVENT_HPP */
|
#include <torch/torch.h>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
struct Net : torch::nn::Module {
Net()
: conv1(torch::nn::Conv2dOptions(1, 10, /*kernel_size=*/5)),
conv2(torch::nn::Conv2dOptions(10, 20, /*kernel_size=*/5)),
fc1(320, 50),
fc2(50, 10) {
register_module("conv1", conv1);
register_module("conv2", conv2);
register_module("conv2_drop", conv2_drop);
register_module("fc1", fc1);
register_module("fc2", fc2);
}
torch::Tensor forward(torch::Tensor x) {
x = torch::relu(torch::max_pool2d(conv1->forward(x), 2));
x = torch::relu(
torch::max_pool2d(conv2_drop->forward(conv2->forward(x)), 2));
x = x.view({-1, 320});
x = torch::relu(fc1->forward(x));
x = torch::dropout(x, /*p=*/0.5, /*training=*/is_training());
x = fc2->forward(x);
return torch::log_softmax(x, /*dim=*/1);
}
torch::nn::Conv2d conv1;
torch::nn::Conv2d conv2;
torch::nn::FeatureDropout conv2_drop;
torch::nn::Linear fc1;
torch::nn::Linear fc2;
};
struct Options {
std::string data_root{"data"};
int32_t batch_size{64};
int32_t epochs{10};
double lr{0.01};
double momentum{0.5};
bool no_cuda{false};
int32_t seed{1};
int32_t test_batch_size{1000};
int32_t log_interval{10};
};
template <typename DataLoader>
void train(int32_t epoch, const Options& options, Net& model, torch::Device device, DataLoader& data_loader, torch::optim::SGD& optimizer, size_t dataset_size) {
model.train();
size_t batch_idx = 0;
for (auto& batch : data_loader) {
auto data = batch.data.to(device), targets = batch.target.to(device);
optimizer.zero_grad();
auto output = model.forward(data);
auto loss = torch::nll_loss(output, targets);
loss.backward();
optimizer.step();
if (batch_idx++ % options.log_interval == 0) {
std::cout << "Train Epoch: " << epoch << " ["
<< batch_idx * batch.data.size(0) << "/" << dataset_size
<< "]\tLoss: " << loss.template item<float>() << std::endl;
}
}
}
template <typename DataLoader>
void test(Net& model, torch::Device device, DataLoader& data_loader, size_t dataset_size) {
torch::NoGradGuard no_grad;
model.eval();
double test_loss = 0;
int32_t correct = 0;
for (const auto& batch : data_loader) {
auto data = batch.data.to(device), targets = batch.target.to(device);
auto output = model.forward(data);
test_loss += torch::nll_loss(
output,
targets,
/*weight=*/{},
Reduction::Sum)
.template item<float>();
auto pred = output.argmax(1);
correct += pred.eq(targets).sum().template item<int64_t>();
}
test_loss /= dataset_size;
std::cout << "Test set: Average loss: " << test_loss
<< ", Accuracy: " << correct << "/" << dataset_size << std::endl;
}
struct Normalize : public torch::data::transforms::TensorTransform<> {
Normalize(float mean, float stddev)
: mean_(torch::tensor(mean)), stddev_(torch::tensor(stddev)) {}
torch::Tensor operator()(torch::Tensor input) {
return input.sub_(mean_).div_(stddev_);
}
torch::Tensor mean_, stddev_;
};
auto main(int argc, const char* argv[]) -> int {
torch::manual_seed(0);
Options options;
torch::DeviceType device_type;
if (torch::cuda::is_available() && !options.no_cuda) {
std::cout << "CUDA available! Training on GPU" << std::endl;
device_type = torch::kCUDA;
} else {
std::cout << "Training on CPU" << std::endl;
device_type = torch::kCPU;
}
torch::Device device(device_type);
Net model;
model.to(device);
auto train_dataset =
torch::data::datasets::MNIST(
options.data_root, torch::data::datasets::MNIST::Mode::kTrain)
.map(Normalize(0.1307, 0.3081))
.map(torch::data::transforms::Stack<>());
const auto dataset_size = train_dataset.size();
auto train_loader = torch::data::make_data_loader(
std::move(train_dataset), options.batch_size);
auto test_loader = torch::data::make_data_loader(
torch::data::datasets::MNIST(
options.data_root, torch::data::datasets::MNIST::Mode::kTest)
.map(Normalize(0.1307, 0.3081))
.map(torch::data::transforms::Stack<>()),
options.batch_size);
torch::optim::SGD optimizer(
model.parameters(),
torch::optim::SGDOptions(options.lr).momentum(options.momentum));
for (size_t epoch = 1; epoch <= options.epochs; ++epoch) {
train(epoch, options, model, device, *train_loader, optimizer, dataset_size.value());
test(model, device, *test_loader, dataset_size.value());
}
}
|
#pragma once
#include <cstdint>
#include <cassert>
#include <ostream>
namespace GoBoard
{
using std::uint8_t;
enum ERule : uint8_t
{
AllowSuicide = 1,
};
enum EGridValue : uint8_t
{
Empty = 0,
Black = 1,
White = 2,
Gray = 3, // Boundary
};
template <size_t MAX_WIDTH, size_t MAX_HEIGHT = MAX_WIDTH, uint8_t RULES = AllowSuicide>
class TBoard
{
public:
inline TBoard(size_t width = MAX_WIDTH, size_t height = MAX_HEIGHT) noexcept : _width(width), _height(height)
{
assert(width <= MAX_WIDTH && height <= MAX_HEIGHT);
gridClear();
}
void undo();
void play();
bool isMoveLegal() const;
inline EGridValue grid(size_t pos) const noexcept
{
assert(pos < NUM_GRID_VALUES);
return _grid[pos];
}
inline EGridValue grid(int x, int y) const noexcept
{
return grid(positionToIndex(x, y));
}
protected:
static constexpr size_t NUM_GRID_VALUES = (MAX_WIDTH + 2) * (MAX_HEIGHT + 2);
static constexpr inline size_t positionToIndex(int x, int y)
{
assert(x + 1 < MAX_WIDTH + 2 && y + 1 < MAX_HEIGHT + 2);
return (y + 1) * (MAX_WIDTH + 2) + (x + 1);
}
static constexpr inline int indexToPositionX(size_t pos)
{
assert(pos < NUM_GRID_VALUES);
return pos % (MAX_WIDTH + 2) - 1;
}
static constexpr inline int indexToPositionY(size_t pos)
{
assert(pos < NUM_GRID_VALUES);
return pos / (MAX_WIDTH + 2) - 1;
}
static inline EGridValue gridValueOtherColor(EGridValue color)
{
return static_cast<EGridValue>(static_cast<std::uint8_t>(EGridValue::Black) + static_cast<std::uint8_t>(EGridValue::White) - static_cast<std::uint8_t>(color));
}
static inline bool girdValueIsStone(EGridValue color)
{
return color == EGridValue::Black || color == EGridValue::White;
}
template <typename charT, typename Traits = std::char_traits<charT>>
friend std::basic_ostream<charT, Traits> &operator<<(std::basic_ostream<charT, Traits> &out, const TBoard &board)
{
for (int j = -1; j < static_cast<int>(MAX_HEIGHT) + 1; ++j)
{
for (int i = -1; i < static_cast<int>(MAX_WIDTH) + 1; ++i)
{
switch (board.grid(i, j))
{
case EGridValue::Empty:
out << charT(' ');
break;
case EGridValue::Black:
out << charT('x');
break;
case EGridValue::White:
out << charT('o');
break;
case EGridValue::Gray:
out << charT('*');
break;
default:
out<< charT('?');
}
}
out<<charT('\n');
}
return out;
}
private:
void gridClear() noexcept
{
size_t pos = 0;
size_t counter;
#define REAPET_SET(count, value) \
counter = 0; \
do \
{ \
_grid[pos++] = value; \
} while (++counter < count)
REAPET_SET(MAX_WIDTH + 2, EGridValue::Gray);
for (size_t j = 0; j < _height; ++j)
{
_grid[pos++] = EGridValue::Gray;
REAPET_SET(_width, EGridValue::Empty);
REAPET_SET(MAX_WIDTH + 1 - _width, EGridValue::Gray);
}
for (size_t j = 0; j < MAX_HEIGHT + 1 - _height; ++j)
{
REAPET_SET(MAX_WIDTH + 2, EGridValue::Gray);
}
assert(pos == NUM_GRID_VALUES);
#undef REAPET_SET
}
private:
EGridValue _grid[NUM_GRID_VALUES];
std::uint32_t _width, _height;
};
}
|
/*
* This file is part of Kintinuous.
*
* Copyright (C) 2015 The National University of Ireland Maynooth and
* Massachusetts Institute of Technology
*
* The use of the code within this file and all code within files that
* make up the software that is Kintinuous is permitted for
* non-commercial purposes only. The full terms and conditions that
* apply to the code within this file are detailed within the LICENSE.txt
* file and at <http://www.cs.nuim.ie/research/vision/data/kintinuous/code.php>
* unless explicitly stated. By downloading this file you agree to
* comply with these terms.
*
* If you wish to use any of this code for commercial purposes then
* please email commercialisation@nuim.ie.
*/
//This includes "PangoVis.h" already
#include "MainController.h"
PangoVis::PangoVis(cv::Mat * depthIntrinsics)
: ThreadObject("VisualisationThread"),
liveTSDF(0),
incMesh(0),
complete("ui.Complete", false, false),
pause("ui.Pause", false, true),
save("ui.Save", false, false),
resetAll("ui.Reset", false, false),
volumeShifting("ui.Volume Shifting", !ConfigArgs::get().staticMode, true),
limitFrontend("ui.Limit Frontend", threadPack.limit.getValue(), true),
followPose("ui.Follow Pose", true, true),
drawTSDF("ui.Draw TSDF", false, true),
drawCloud("ui.Draw Cloud", true, true),
drawMesh("ui.Draw Mesh", ConfigArgs::get().enableMeshGenerator || ConfigArgs::get().incrementalMesh, true),
drawMeshNormals("ui.Draw Mesh Normals", false, true),
totalPoints("ui.Points:", "0"),
totalTriangles("ui.Triangles:", "0"),
frame("ui.Frame:", "0"),
frontendFps("ui.Frontend:", ""),
backendLag("ui.Backend Lag:", ""),
status("ui.Status:", ""),
depthBuffer(new unsigned short[Resolution::get().numPixels()])
{
pangolin::CreateWindowAndBind("Kintinuous", 1280 + 180, 960);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
rgbTex.Reinitialise(Resolution::get().width(), Resolution::get().height()),
depthTex.Reinitialise(Resolution::get().width(), Resolution::get().height()),
tsdfRgbTex.Reinitialise(Resolution::get().width(), Resolution::get().height()),
tsdfTex.Reinitialise(Resolution::get().width(), Resolution::get().height()),
rgbImg.Alloc(Resolution::get().width(), Resolution::get().height(), pangolin::VideoFormatFromString("RGB24"));
tsdfImg.Alloc(Resolution::get().width(), Resolution::get().height(), pangolin::VideoFormatFromString("RGB24"));
tsdfImgColor.Alloc(Resolution::get().width(), Resolution::get().height(), pangolin::VideoFormatFromString("RGB24"));
depthImg.Alloc(Resolution::get().width(), Resolution::get().height(), pangolin::VideoFormatFromString("RGB24"));
glEnable(GL_DEPTH_TEST);
s_cam = pangolin::OpenGlRenderState(pangolin::ProjectionMatrix(640, 480, 420, 420, 320, 240, 0.1, 1000),
pangolin::ModelViewLookAt(-0.35, -2.3, -6.4, 0, 0, 0, 0, -1, 0));
pangolin::Display("cam").SetBounds(0, 1.0f, 0, 1.0f, -640 / 480.0)
.SetHandler(new pangolin::Handler3D(s_cam));
pangolin::Display("Img").SetAspect(640.0f / 480.0f);
pangolin::Display("Depth").SetAspect(640.0f / 480.0f);
pangolin::Display("ModelImg").SetAspect(640.0f / 480.0f);
pangolin::Display("Model").SetAspect(640.0f / 480.0f);
pangolin::CreatePanel("ui").SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(180));
pangolin::Display("multi").SetBounds(pangolin::Attach::Pix(0), 1 / 4.0f, pangolin::Attach::Pix(180), 1.0)
.SetLayout(pangolin::LayoutEqualHorizontal)
.AddDisplay(pangolin::Display("Img"))
.AddDisplay(pangolin::Display("Depth"))
.AddDisplay(pangolin::Display("ModelImg"))
.AddDisplay(pangolin::Display("Model"));
K = Eigen::Matrix3f::Identity();
K(0, 0) = depthIntrinsics->at<double>(0,0);
K(1, 1) = depthIntrinsics->at<double>(1,1);
K(0, 2) = depthIntrinsics->at<double>(0,2);
K(1, 2) = depthIntrinsics->at<double>(1,2);
Kinv = K.inverse();
depthBuffer = new unsigned short[Resolution::get().numPixels()];
reset();
}
PangoVis::~PangoVis()
{
reset();
delete [] depthBuffer;
pangolin::FreeImage(rgbImg);
pangolin::FreeImage(tsdfImg);
pangolin::FreeImage(tsdfImgColor);
pangolin::FreeImage(depthImg);
}
void PangoVis::removeAllClouds()
{
for(size_t i = 0; i < clouds.size(); i++)
{
delete clouds.at(i);
}
clouds.clear();
}
void PangoVis::removeAllShapes()
{
lines.clear();
poses.clear();
}
void PangoVis::removeAllMeshes()
{
for(size_t i = 0; i < meshes.size(); i++)
{
delete meshes.at(i);
}
meshes.clear();
}
void PangoVis::reset()
{
latestDrawnMeshId = 0;
numPoints = 0;
numTriangles = 0;
numTrianglePoints = 0;
latestDrawnPoseCloudId = 0;
removeAllClouds();
removeAllShapes();
removeAllMeshes();
if(liveTSDF)
{
delete liveTSDF;
liveTSDF = 0;
}
if(incMesh)
{
delete incMesh;
incMesh = 0;
}
}
void PangoVis::preCall()
{
glClearColor(0.25, 0.25, 0.25, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
pangolin::Display("cam").Activate(s_cam);
}
bool inline PangoVis::process()
{
TICK(threadIdentifier);
if(pangolin::ShouldQuit())
{
MainController::controller->shutdown();
return false;
}
preCall();
processTsdf();
processClouds();
processMeshes();
processImages();
render();
postCall();
handleInput();
TOCK(threadIdentifier);
usleep(std::max(1, int(33000 - (Stopwatch::get().getTimings().at(threadIdentifier) * 1000))));
return true;
}
void PangoVis::processClouds()
{
int latestDensePoseIdCopy = threadPack.tracker->latestDensePoseId.getValue();
if(latestDensePoseIdCopy > 0)
{
const float3 & voxelSizeMeters = Volume::get().getVoxelSizeMeters();
pose = threadPack.isamOffset.getValue() * threadPack.loopOffset.getValue() * threadPack.tracker->densePoseGraph.at(latestDensePoseIdCopy - 1).pose;
Eigen::Vector3f translation = pose.topRightCorner(3, 1);
Eigen::Vector3f initialTrans = Eigen::Vector3f::Constant(Volume::get().getVolumeSize() * 0.5) - threadPack.tracker->getVolumeOffset();
Eigen::Vector3f currentCubeTranslation = initialTrans;
currentCubeTranslation(0) += std::floor(translation(0) / voxelSizeMeters.x) * voxelSizeMeters.x;
currentCubeTranslation(1) += std::floor(translation(1) / voxelSizeMeters.y) * voxelSizeMeters.y;
currentCubeTranslation(2) += std::floor(translation(2) / voxelSizeMeters.z) * voxelSizeMeters.z;
//Kinda hacky
if(volumeShifting)
{
tsdfCube.setEmpty();
tsdfCube.extend(currentCubeTranslation + Eigen::Vector3f::Constant(Volume::get().getVolumeSize() / 2.0f));
tsdfCube.extend(currentCubeTranslation - Eigen::Vector3f::Constant(Volume::get().getVolumeSize() / 2.0f));
}
pangolin::glDrawAlignedBox(tsdfCube);
glColor3f(0, 1, 0);
pangolin::glDrawFrustrum(Kinv, Resolution::get().width(), Resolution::get().height(), pose, 0.1f);
glColor3f(1, 1, 1);
}
int latestPoseIdCopy = threadPack.latestPoseId.getValue();
if(ConfigArgs::get().onlineDeformation)
{
boost::mutex::scoped_lock lock(threadPack.poolMutex, boost::try_to_lock);
if(lock)
{
if(threadPack.poolLooped.getValue())
{
removeAllClouds();
numPoints = 0;
threadPack.poolLooped.assignValue(false);
}
if((int)threadPack.pointPool->size() != numPoints)
{
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr tempCloud(new pcl::PointCloud<pcl::PointXYZRGBNormal>);
tempCloud->points.insert(tempCloud->end(), threadPack.pointPool->begin() + numPoints, threadPack.pointPool->end());
lock.unlock();
numPoints = threadPack.pointPool->size();
static int i = 0;
std::stringstream strs;
strs << "pool" << i++;
clouds.push_back(new PangoCloud(tempCloud.get()));
}
else
{
lock.unlock();
}
}
removeAllShapes();
for(int i = 2; i < latestPoseIdCopy; i++)
{
if(ConfigArgs::get().dynamicCube && !threadPack.cloudSlices.at(i)->poseIsam.getValue())
break;
Eigen::Matrix4f pose = Eigen::Matrix4f::Identity();
pose.topLeftCorner(3, 3) = threadPack.cloudSlices.at(i)->cameraRotation;
pose.topRightCorner(3, 1) = threadPack.cloudSlices.at(i)->cameraTranslation;
poses.push_back(pose);
if(i > 2)
{
lines.push_back(std::pair<Eigen::Vector3f, Eigen::Vector3f>(threadPack.cloudSlices.at(i)->cameraTranslation,
threadPack.cloudSlices.at(i - 1)->cameraTranslation));
}
}
}
else
{
while(latestDrawnPoseCloudId < latestPoseIdCopy)
{
clouds.push_back(new PangoCloud(threadPack.cloudSlices.at(latestDrawnPoseCloudId)->processedCloud));
numPoints += threadPack.cloudSlices.at(latestDrawnPoseCloudId)->processedCloud->size();
if(latestDrawnPoseCloudId > 1)
{
Eigen::Matrix4f pose = Eigen::Matrix4f::Identity();
pose.topLeftCorner(3, 3) = threadPack.cloudSlices.at(latestDrawnPoseCloudId)->cameraRotation;
pose.topRightCorner(3, 1) = threadPack.cloudSlices.at(latestDrawnPoseCloudId)->cameraTranslation;
poses.push_back(pose);
if(latestDrawnPoseCloudId > 2)
{
lines.push_back(std::pair<Eigen::Vector3f, Eigen::Vector3f>(threadPack.cloudSlices.at(latestDrawnPoseCloudId)->cameraTranslation,
threadPack.cloudSlices.at(latestDrawnPoseCloudId - 1)->cameraTranslation));
}
}
latestDrawnPoseCloudId++;
}
}
}
void PangoVis::processTsdf()
{
if(threadPack.finalised.getValue())
{
if(liveTSDF)
{
delete liveTSDF;
liveTSDF = 0;
}
}
else if(drawTSDF)
{
boost::mutex::scoped_lock tsdfLock(threadPack.tracker->tsdfMutex);
if(threadPack.tracker->tsdfAvailable)
{
if(liveTSDF)
{
delete liveTSDF;
liveTSDF = 0;
}
if(ConfigArgs::get().dynamicCube)
{
pcl::transformPointCloud(*threadPack.tracker->getLiveTsdf()->cloud, *threadPack.tracker->getLiveTsdf()->cloud, threadPack.isamOffset.getValue());
}
liveTSDF = new PangoCloud(threadPack.tracker->getLiveTsdf()->cloud);
threadPack.tracker->tsdfAvailable = false;
}
}
}
void PangoVis::processMeshes()
{
int latestMeshIdCopy = threadPack.latestMeshId.getValue();
if(ConfigArgs::get().incrementalMesh)
{
boost::mutex::scoped_lock lock(threadPack.incMeshMutex, boost::try_to_lock);
if(lock)
{
int numIncPoints = threadPack.incrementalMesh->mesh->cloud.width * threadPack.incrementalMesh->mesh->cloud.height;
bool looped = threadPack.incMeshLooped.getValue();
if((int)threadPack.incrementalMesh->mesh->polygons.size() != numTriangles || numIncPoints != numTrianglePoints || looped)
{
removeAllMeshes();
numTriangles = threadPack.incrementalMesh->mesh->polygons.size();
numTrianglePoints = numIncPoints;
if(incMesh)
{
delete incMesh;
incMesh = 0;
}
incMesh = new PangoMesh(threadPack.incrementalMesh->mesh.get());
if(looped)
{
threadPack.incMeshLooped.assignValue(false);
}
}
}
}
else
{
while(latestDrawnMeshId < latestMeshIdCopy)
{
if(threadPack.triangles.at(latestDrawnMeshId)->polygons.size() > 0)
{
meshes.push_back(new PangoMesh(threadPack.triangles.at(latestDrawnMeshId)));
numTriangles += threadPack.triangles.at(latestDrawnMeshId)->polygons.size();
}
latestDrawnMeshId++;
}
}
}
void PangoVis::render()
{
if((ConfigArgs::get().incrementalMesh || ConfigArgs::get().enableMeshGenerator) && drawMesh)
{
for(size_t i = 0; i < meshes.size(); i++)
{
meshes.at(i)->drawTriangles(drawMeshNormals);
}
if(incMesh)
{
incMesh->drawTriangles(drawMeshNormals);
}
}
else if(drawCloud)
{
for(size_t i = 0; i < clouds.size(); i++)
{
clouds.at(i)->drawPoints();
}
}
if(liveTSDF)
{
liveTSDF->drawPoints();
}
glColor3f(1, 0, 1);
for(size_t i = 0; i < lines.size(); i++)
{
pangolin::glDrawLine(lines.at(i).first(0),
lines.at(i).first(1),
lines.at(i).first(2),
lines.at(i).second(0),
lines.at(i).second(1),
lines.at(i).second(2));
}
glColor3f(1, 1, 1);
for(size_t i = 0; i < poses.size(); i++)
{
pangolin::glDrawFrustrum(Kinv, Resolution::get().width(), Resolution::get().height(), poses.at(i), 0.05f);
}
glDisable(GL_DEPTH_TEST);
pangolin::Display("Img").Activate();
rgbTex.RenderToViewport(true);
pangolin::Display("Depth").Activate();
depthTex.RenderToViewport(true);
pangolin::Display("ModelImg").Activate();
tsdfRgbTex.RenderToViewport(true);
pangolin::Display("Model").Activate();
tsdfTex.RenderToViewport(true);
glEnable(GL_DEPTH_TEST);
}
void PangoVis::processImages()
{
boost::mutex::scoped_lock imageLock(threadPack.tracker->imageMutex, boost::try_to_lock);
if(imageLock && threadPack.tracker->imageAvailable)
{
threadPack.tracker->imageAvailable = false;
memcpy(tsdfImg.ptr, threadPack.tracker->getLiveImage()->tsdfImage, Resolution::get().numPixels() * 3);
memcpy(tsdfImgColor.ptr, threadPack.tracker->getLiveImage()->tsdfImageColor, Resolution::get().numPixels() * 3);
memcpy(rgbImg.ptr, threadPack.tracker->getLiveImage()->rgbImage, Resolution::get().numPixels() * 3);
memcpy(&depthBuffer[0], threadPack.tracker->getLiveImage()->depthData, Resolution::get().numPixels() * 2);
imageLock.unlock();
float max = 0;
for(int i = 0; i < Resolution::get().numPixels(); i++)
{
if(depthBuffer[i] > max)
{
max = depthBuffer[i];
}
}
int innerPtr = 0;
for(int i = 0; i < Resolution::get().numPixels(); i++, innerPtr+=3)
{
depthImg.ptr[innerPtr + 0] = ((float)depthBuffer[i] / max) * 255.0f;
depthImg.ptr[innerPtr + 1] = ((float)depthBuffer[i] / max) * 255.0f;
depthImg.ptr[innerPtr + 2] = ((float)depthBuffer[i] / max) * 255.0f;
}
rgbTex.Upload(rgbImg.ptr, GL_RGB, GL_UNSIGNED_BYTE);
depthTex.Upload(depthImg.ptr, GL_RGB, GL_UNSIGNED_BYTE);
tsdfRgbTex.Upload(tsdfImgColor.ptr, GL_RGB, GL_UNSIGNED_BYTE);
tsdfTex.Upload(tsdfImg.ptr, GL_BGR, GL_UNSIGNED_BYTE);
//For a minimal "TSDF" visualisation
if(!drawTSDF)
{
if(liveTSDF)
{
delete liveTSDF;
liveTSDF = 0;
}
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud <pcl::PointXYZRGB>);
for(int i = 0; i < Resolution::get().width(); i++)
{
for(int j = 0; j < Resolution::get().height(); j++)
{
if(depthBuffer[j * Resolution::get().width() + i])
{
pcl::PointXYZRGB pt;
pt.z = depthBuffer[j * Resolution::get().width() + i] * 0.001f;
pt.x = (static_cast<float>(i) - K(0, 2)) * pt.z * (1.0f / K(0, 0));
pt.y = (static_cast<float>(j) - K(1, 2)) * pt.z * (1.0f / K(1, 1));
pt.b = rgbImg.ptr[3 * (j * Resolution::get().width() + i) + 0];
pt.g = rgbImg.ptr[3 * (j * Resolution::get().width() + i) + 1];
pt.r = rgbImg.ptr[3 * (j * Resolution::get().width() + i) + 2];
cloud->push_back(pt);
}
}
}
pcl::transformPointCloud(*cloud, *cloud, pose);
liveTSDF = new PangoCloud(cloud.get());
}
}
else if(imageLock)
{
imageLock.unlock();
}
}
void PangoVis::handleInput()
{
//So this is some hilarious access/control!
if(pangolin::Pushed(complete))
{
MainController::controller->complete();
followPose = false;
}
if(pause.GuiChanged())
{
threadPack.pauseCapture.assignValue(pause);
}
if(pangolin::Pushed(save))
{
MainController::controller->save();
}
if(pangolin::Pushed(resetAll))
{
MainController::controller->reset();
MainController::controller->setPark(!volumeShifting);
threadPack.pauseCapture.assignValue(pause);
}
if(volumeShifting.GuiChanged())
{
MainController::controller->setPark(!volumeShifting);
}
if(drawTSDF.GuiChanged())
{
threadPack.tracker->tsdfRequest.assignValue(drawTSDF);
}
if(limitFrontend.GuiChanged())
{
threadPack.limit.assignValue(limitFrontend);
}
if(pause)
{
status = "Paused";
}
else if(threadPack.cloudSliceProcessorFinished.getValue() &&
threadPack.meshGeneratorFinished.getValue() &&
threadPack.placeRecognitionFinished.getValue() &&
threadPack.deformationFinished.getValue())
{
status = "Finished";
}
else
{
status = "Running";
}
if(followPose)
{
pangolin::OpenGlMatrix mv;
Eigen::Matrix4f currPose = pose;
Eigen::Matrix3f currRot = currPose.topLeftCorner(3, 3);
Eigen::Quaternionf currQuat(currRot);
Eigen::Vector3f forwardVector(0, 0, 1);
Eigen::Vector3f upVector(0, -1, 0);
Eigen::Vector3f forward = (currQuat * forwardVector).normalized();
Eigen::Vector3f up = (currQuat * upVector).normalized();
Eigen::Vector3f eye(currPose(0, 3), currPose(1, 3), currPose(2, 3));
eye -= forward * 20;
Eigen::Vector3f at = eye + forward;
Eigen::Vector3f z = (eye - at).normalized(); // Forward
Eigen::Vector3f x = up.cross(z).normalized(); // Right
Eigen::Vector3f y = z.cross(x);
Eigen::Matrix4d m;
m << x(0), x(1), x(2), -(x.dot(eye)),
y(0), y(1), y(2), -(y.dot(eye)),
z(0), z(1), z(2), -(z.dot(eye)),
0, 0, 0, 1;
memcpy(&mv.m[0], m.data(), sizeof(Eigen::Matrix4d));
s_cam.SetModelViewMatrix(mv);
}
std::stringstream strs;
strs << numPoints;
totalPoints = strs.str();
std::stringstream strst;
strst << numTriangles;
totalTriangles = strst.str();
std::stringstream strsf;
strsf << int(std::ceil(1.0f / (Stopwatch::get().getTimings().at("TrackerInterfaceThread") / 1000.0f))) << "Hz";
frontendFps = strsf.str();
std::stringstream strsb;
strsb << int(float(MainController::controller->getMaxLag()) / 1000.0f) << "ms";
backendLag = strsb.str();
std::stringstream strsfr;
strsfr << threadPack.trackerFrame.getValue();
frame = strsfr.str();
}
void PangoVis::postCall()
{
pangolin::FinishFrame();
}
|
// Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
#include <ie_core.hpp>
#include <ngraph_functions/builders.hpp>
#include "functional_test_utils/blob_utils.hpp"
#include "functional_test_utils/precision_utils.hpp"
#include "common_test_utils/common_utils.hpp"
#include "single_layer_tests/space_to_depth.hpp"
using namespace ngraph::opset3;
namespace LayerTestsDefinitions {
static inline std::string SpaceToDepthModeToString(const SpaceToDepth::SpaceToDepthMode& mode) {
static std::map<SpaceToDepth::SpaceToDepthMode, std::string> names = {
{SpaceToDepth::SpaceToDepthMode::BLOCKS_FIRST, "BLOCKS_FIRST"},
{SpaceToDepth::SpaceToDepthMode::DEPTH_FIRST, "DEPTH_FIRST"},
};
auto i = names.find(mode);
if (i != names.end())
return i->second;
else
throw std::runtime_error("Unsupported SpaceToDepthMode");
}
std::string SpaceToDepthLayerTest::getTestCaseName(const testing::TestParamInfo<spaceToDepthParamsTuple> &obj) {
std::vector<size_t> inShape;
SpaceToDepth::SpaceToDepthMode mode;
std::size_t blockSize;
InferenceEngine::Precision inputPrecision;
std::string targetName;
std::tie(inShape, inputPrecision, mode, blockSize, targetName) = obj.param;
std::ostringstream result;
result << "IS=" << CommonTestUtils::vec2str(inShape) << "_";
result << "inPrc=" << inputPrecision.name() << "_";
result << "M=" << SpaceToDepthModeToString(mode) << "_";
result << "BS=" << blockSize << "_";
result << "targetDevice=" << targetName << "_";
return result.str();
}
void SpaceToDepthLayerTest::SetUp() {
std::vector<size_t> inShape;
SpaceToDepth::SpaceToDepthMode mode;
std::size_t blockSize;
InferenceEngine::Precision inputPrecision;
std::tie(inShape, inputPrecision, mode, blockSize, targetDevice) = this->GetParam();
auto inPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(inputPrecision);
auto params = ngraph::builder::makeParams(inPrc, {inShape});
auto paramOuts = ngraph::helpers::convert2OutputVector(ngraph::helpers::castOps2Nodes<ngraph::op::Parameter>(params));
auto s2d = ngraph::builder::makeSpaceToDepth(paramOuts[0], mode, blockSize);
ngraph::ResultVector results{std::make_shared<ngraph::opset1::Result>(s2d)};
function = std::make_shared<ngraph::Function>(results, params, "SpaceToDepth");
}
TEST_P(SpaceToDepthLayerTest, CompareWithRefs) {
Run();
};
} // namespace LayerTestsDefinitions
|
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main(void){
string input;
while(getline(cin, input), !cin.eof()){
int H, W;
sscanf(input.c_str(), "%d %d\n", &H, &W);
if((H | W) == 0) break;
for(int i = 0; i < H; i++){
for(int j = 0; j < W; j++){
if(j == 0 || j == (W - 1) || i == 0 || i == (H - 1)){
printf("#");
}
else{
printf(".");
}
}
printf("\n");
}
printf("\n");
}
return(0);
}
|
/****************************************************************************
** Meta object code from reading C++ file 'userdatarequest.h'
**
** Created: Fri Mar 9 15:57:11 2018
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "userdatarequest.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'userdatarequest.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.3. 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
static const uint qt_meta_data_UserDataRequest[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
17, 16, 16, 16, 0x0a,
29, 16, 16, 16, 0x09,
0 // eod
};
static const char qt_meta_stringdata_UserDataRequest[] = {
"UserDataRequest\0\0sendReply()\0"
"languageChange()\0"
};
const QMetaObject UserDataRequest::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_UserDataRequest,
qt_meta_data_UserDataRequest, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &UserDataRequest::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *UserDataRequest::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *UserDataRequest::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_UserDataRequest))
return static_cast<void*>(const_cast< UserDataRequest*>(this));
if (!strcmp(_clname, "Ui::UserDataRequest"))
return static_cast< Ui::UserDataRequest*>(const_cast< UserDataRequest*>(this));
return QDialog::qt_metacast(_clname);
}
int UserDataRequest::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: sendReply(); break;
case 1: languageChange(); break;
default: ;
}
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
|
#include "engine/input.h"
#include "core/assert.h"
#include "core/cint.h"
#include "core/sol.h"
namespace euphoria::engine
{
BoundVar::BoundVar(const std::string& n, const core::Key& k)
: name(n), state(0), last_state(0), key(k)
{
}
void
bind_bound_var(LuaState* duk)
{
duk->state.new_usertype<BoundVar>
(
"bound_var",
"state",
sol::property
(
[](const BoundVar& v) -> double { return core::c_float_to_double(v.state); }
),
"last_state",
sol::property
(
[](const BoundVar& v) -> double { return core::c_float_to_double(v.last_state); }
)
);
}
void
InputSystem::bind(LuaState* duk)
{
bind_bound_var(duk);
}
void
InputSystem::add(std::shared_ptr<BoundVar> bind)
{
binds.push_back(bind);
}
void
InputSystem::set_key_state(core::Key key, float state)
{
// todo(Gustav): move state to another class, and fix this loop
for(const auto& bind: binds)
{
if(bind->key == key)
{
bind->state = state;
}
}
}
void
InputSystem::set(sol::table* container) const
{
for(const auto& bind : binds)
{
(*container)[bind->name] = bind;
}
}
void
InputSystem::update_state()
{
for(auto& bind: binds)
{
bind->last_state = bind->state;
}
}
}
|
/*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : mehrab.24csedu.001@gmail.com
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[10000],b[10000],n,i,j,ans=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d %d",&a[i],&b[i]);
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(b[i]==a[j] && i!=j) a[j]=-1;
}
}
ans=0;
for(j=0;j<n;j++){
if(a[j]!=-1) ans++;
}
printf("%d\n",ans);
return 0;
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/core/quic_client_session_base.h"
#include "net/quic/core/quic_client_promised_info.h"
#include "net/quic/core/quic_flags.h"
#include "net/quic/core/spdy_utils.h"
using base::StringPiece;
using std::string;
namespace net {
QuicClientSessionBase::QuicClientSessionBase(
QuicConnection* connection,
QuicClientPushPromiseIndex* push_promise_index,
const QuicConfig& config)
: QuicSpdySession(connection, nullptr, config),
push_promise_index_(push_promise_index),
largest_promised_stream_id_(kInvalidStreamId) {}
QuicClientSessionBase::~QuicClientSessionBase() {
// all promised streams for this session
for (auto& it : promised_by_id_) {
DVLOG(1) << "erase stream " << it.first << " url " << it.second->url();
push_promise_index_->promised_by_url()->erase(it.second->url());
}
delete connection();
}
void QuicClientSessionBase::OnConfigNegotiated() {
QuicSpdySession::OnConfigNegotiated();
}
void QuicClientSessionBase::OnCryptoHandshakeEvent(CryptoHandshakeEvent event) {
QuicSession::OnCryptoHandshakeEvent(event);
}
void QuicClientSessionBase::OnInitialHeadersComplete(
QuicStreamId stream_id,
const SpdyHeaderBlock& response_headers) {
// Note that the strong ordering of the headers stream means that
// QuicSpdyClientStream::OnPromiseHeadersComplete must have already
// been called (on the associated stream) if this is a promised
// stream. However, this stream may not have existed at this time,
// hence the need to query the session.
QuicClientPromisedInfo* promised = GetPromisedById(stream_id);
if (!promised)
return;
promised->OnResponseHeaders(response_headers);
}
void QuicClientSessionBase::OnPromiseHeaderList(
QuicStreamId stream_id,
QuicStreamId promised_stream_id,
size_t frame_len,
const QuicHeaderList& header_list) {
if (promised_stream_id != kInvalidStreamId &&
promised_stream_id <= largest_promised_stream_id_) {
connection()->CloseConnection(
QUIC_INVALID_STREAM_ID,
"Received push stream id lesser or equal to the"
" last accepted before",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
largest_promised_stream_id_ = promised_stream_id;
QuicSpdyStream* stream = GetSpdyDataStream(stream_id);
if (!stream) {
// It's quite possible to receive headers after a stream has been reset.
return;
}
stream->OnPromiseHeaderList(promised_stream_id, frame_len, header_list);
}
bool QuicClientSessionBase::HandlePromised(QuicStreamId /* associated_id */,
QuicStreamId id,
const SpdyHeaderBlock& headers) {
// Due to pathalogical packet re-ordering, it is possible that
// frames for the promised stream have already arrived, and the
// promised stream could be active or closed.
if (IsClosedStream(id)) {
// There was a RST on the data stream already, perhaps
// QUIC_REFUSED_STREAM?
DVLOG(1) << "Promise ignored for stream " << id
<< " that is already closed";
return false;
}
if (push_promise_index_->promised_by_url()->size() >= get_max_promises()) {
DVLOG(1) << "Too many promises, rejecting promise for stream " << id;
ResetPromised(id, QUIC_REFUSED_STREAM);
return false;
}
const string url = SpdyUtils::GetUrlFromHeaderBlock(headers);
QuicClientPromisedInfo* old_promised = GetPromisedByUrl(url);
if (old_promised) {
DVLOG(1) << "Promise for stream " << id << " is duplicate URL " << url
<< " of previous promise for stream " << old_promised->id();
ResetPromised(id, QUIC_DUPLICATE_PROMISE_URL);
return false;
}
if (GetPromisedById(id)) {
// OnPromiseHeadersComplete() would have closed the connection if
// promised id is a duplicate.
QUIC_BUG << "Duplicate promise for id " << id;
return false;
}
QuicClientPromisedInfo* promised = new QuicClientPromisedInfo(this, id, url);
std::unique_ptr<QuicClientPromisedInfo> promised_owner(promised);
promised->Init();
DVLOG(1) << "stream " << id << " emplace url " << url;
(*push_promise_index_->promised_by_url())[url] = promised;
promised_by_id_[id] = std::move(promised_owner);
promised->OnPromiseHeaders(headers);
return true;
}
QuicClientPromisedInfo* QuicClientSessionBase::GetPromisedByUrl(
const string& url) {
QuicPromisedByUrlMap::iterator it =
push_promise_index_->promised_by_url()->find(url);
if (it != push_promise_index_->promised_by_url()->end()) {
return it->second;
}
return nullptr;
}
QuicClientPromisedInfo* QuicClientSessionBase::GetPromisedById(
const QuicStreamId id) {
QuicPromisedByIdMap::iterator it = promised_by_id_.find(id);
if (it != promised_by_id_.end()) {
return it->second.get();
}
return nullptr;
}
QuicSpdyStream* QuicClientSessionBase::GetPromisedStream(
const QuicStreamId id) {
DynamicStreamMap::iterator it = dynamic_streams().find(id);
if (it != dynamic_streams().end()) {
return static_cast<QuicSpdyStream*>(it->second.get());
}
return nullptr;
}
void QuicClientSessionBase::DeletePromised(QuicClientPromisedInfo* promised) {
push_promise_index_->promised_by_url()->erase(promised->url());
// Since promised_by_id_ contains the unique_ptr, this will destroy
// promised.
promised_by_id_.erase(promised->id());
headers_stream()->MaybeReleaseSequencerBuffer();
}
void QuicClientSessionBase::OnPushStreamTimedOut(QuicStreamId stream_id) {}
void QuicClientSessionBase::ResetPromised(QuicStreamId id,
QuicRstStreamErrorCode error_code) {
SendRstStream(id, error_code, 0);
if (!IsOpenStream(id)) {
MaybeIncreaseLargestPeerStreamId(id);
if (!FLAGS_quic_bugfix_reset_promised) {
InsertLocallyClosedStreamsHighestOffset(id, 0);
}
}
}
void QuicClientSessionBase::CloseStreamInner(QuicStreamId stream_id,
bool locally_reset) {
QuicSpdySession::CloseStreamInner(stream_id, locally_reset);
headers_stream()->MaybeReleaseSequencerBuffer();
}
bool QuicClientSessionBase::ShouldReleaseHeadersStreamSequencerBuffer() {
return num_active_requests() == 0 && promised_by_id_.empty();
}
} // namespace net
|
// Copyright (c) 2016 Mirants Lu. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "voyager/core/tcp_connection.h"
#include <errno.h>
#include <unistd.h>
#include "voyager/core/dispatch.h"
#include "voyager/core/eventloop.h"
#include "voyager/util/logging.h"
#include "voyager/util/slice.h"
namespace voyager {
TcpConnection::TcpConnection(const std::string& name, EventLoop* ev, int fd,
const SockAddr& local, const SockAddr& peer)
: name_(name),
eventloop_(CHECK_NOTNULL(ev)),
socket_(fd),
local_addr_(local),
peer_addr_(peer),
state_(kConnecting),
dispatch_(new Dispatch(ev, fd)),
context_(nullptr),
high_water_mark_(64 * 1024 * 1024) {
dispatch_->SetReadCallback(std::bind(&TcpConnection::HandleRead, this));
dispatch_->SetWriteCallback(std::bind(&TcpConnection::HandleWrite, this));
dispatch_->SetCloseCallback(std::bind(&TcpConnection::HandleClose, this));
dispatch_->SetErrorCallback(std::bind(&TcpConnection::HandleError, this));
socket_.SetNonBlockAndCloseOnExec(true);
socket_.SetKeepAlive(true);
socket_.SetTcpNoDelay(true);
VOYAGER_LOG(DEBUG) << "TcpConnection::TcpConnection [" << name_ << "] at "
<< this << " fd=" << fd;
}
TcpConnection::~TcpConnection() {
VOYAGER_LOG(DEBUG) << "TcpConnection::~TcpConnection [" << name_ << "] at "
<< this << " fd=" << dispatch_->Fd()
<< " ConnectState=" << StateToString();
}
void TcpConnection::StartWorking() {
eventloop_->AssertInMyLoop();
assert(state_ == kConnecting);
state_ = kConnected;
TcpConnectionPtr ptr(shared_from_this());
dispatch_->Tie(ptr);
dispatch_->EnableRead();
eventloop_->AddConnection(ptr);
if (connection_cb_) {
connection_cb_(ptr);
}
}
void TcpConnection::StartRead() {
TcpConnectionPtr ptr(shared_from_this());
eventloop_->RunInLoop([ptr]() {
if (!ptr->dispatch_->IsReading()) {
ptr->dispatch_->EnableRead();
}
});
}
void TcpConnection::StopRead() {
TcpConnectionPtr ptr(shared_from_this());
eventloop_->RunInLoop([ptr]() {
if (ptr->dispatch_->IsReading()) {
ptr->dispatch_->DisableRead();
}
});
}
void TcpConnection::ShutDown() {
ConnectState expected = kConnected;
if (state_.compare_exchange_weak(expected, kDisconnecting)) {
TcpConnectionPtr ptr(shared_from_this());
eventloop_->RunInLoop([ptr]() {
if (!ptr->dispatch_->IsWriting()) {
ptr->socket_.ShutDownWrite();
}
});
}
}
void TcpConnection::ForceClose() {
ConnectState expected = kConnected;
if (state_.compare_exchange_weak(expected, kDisconnecting) ||
state_ == kDisconnecting) {
TcpConnectionPtr ptr(shared_from_this());
eventloop_->QueueInLoop([ptr]() {
if (ptr->state_ == kConnected || ptr->state_ == kDisconnecting) {
ptr->HandleClose();
}
});
}
}
void TcpConnection::HandleRead() {
eventloop_->AssertInMyLoop();
ssize_t n = readbuf_.ReadV(dispatch_->Fd());
if (n > 0) {
if (message_cb_) {
message_cb_(shared_from_this(), &readbuf_);
}
} else if (n == 0) {
HandleClose();
} else {
if (errno == EPIPE || errno == ECONNRESET) {
HandleClose();
}
if (errno != EWOULDBLOCK && errno != EAGAIN) {
VOYAGER_LOG(ERROR) << "TcpConnection::HandleRead [" << name_
<< "] - readv: " << strerror(errno);
}
}
}
void TcpConnection::HandleWrite() {
eventloop_->AssertInMyLoop();
if (dispatch_->IsWriting()) {
ssize_t n =
::write(dispatch_->Fd(), writebuf_.Peek(), writebuf_.ReadableSize());
if (n >= 0) {
writebuf_.Retrieve(static_cast<size_t>(n));
if (writebuf_.ReadableSize() == 0) {
dispatch_->DisableWrite();
if (writecomplete_cb_) {
writecomplete_cb_(shared_from_this());
}
if (state_ == kDisconnecting) {
HandleClose();
}
}
} else {
if (errno == EPIPE || errno == ECONNRESET) {
HandleClose();
}
if (errno != EWOULDBLOCK && errno != EAGAIN) {
VOYAGER_LOG(ERROR) << "TcpConnection::HandleWrite [" << name_
<< "] - write: " << strerror(errno);
}
}
} else {
VOYAGER_LOG(INFO) << "TcpConnection::HandleWrite [" << name_
<< "] - fd=" << dispatch_->Fd()
<< " is down, no more writing";
}
}
void TcpConnection::HandleClose() {
eventloop_->AssertInMyLoop();
assert(state_ == kConnected || state_ == kDisconnecting);
state_ = kDisconnected;
dispatch_->DisableAll();
dispatch_->RemoveEvents();
eventloop_->RemoveConnection(shared_from_this());
if (close_cb_) {
close_cb_(shared_from_this());
}
}
void TcpConnection::HandleError() {
int result = socket_.CheckSocketError();
if (result != 0) {
VOYAGER_LOG(ERROR) << "TcpConnection::HandleError [" << name_ << "] - "
<< strerror(result);
}
}
void TcpConnection::SendMessage(std::string&& message) {
if (state_ == kConnected) {
if (eventloop_->IsInMyLoop()) {
SendInLoop(message.data(), message.size());
} else {
eventloop_->RunInLoop(std::bind(&TcpConnection::Send, shared_from_this(),
std::move(message)));
}
}
}
void TcpConnection::SendMessage(const Slice& message) {
if (state_ == kConnected) {
if (eventloop_->IsInMyLoop()) {
SendInLoop(message.data(), message.size());
} else {
eventloop_->RunInLoop(std::bind(&TcpConnection::Send, shared_from_this(),
message.ToString()));
}
}
}
void TcpConnection::SendMessage(Buffer&& message) {
if (state_ == kConnected) {
if (eventloop_->IsInMyLoop()) {
SendInLoop(message.Peek(), message.ReadableSize());
} else {
eventloop_->RunInLoop(std::bind(&TcpConnection::SendBuffer,
shared_from_this(), std::move(message)));
}
}
}
void TcpConnection::SendMessage(Buffer* message) {
CHECK_NOTNULL(message);
if (state_ == kConnected) {
if (eventloop_->IsInMyLoop()) {
SendInLoop(message->Peek(), message->ReadableSize());
message->RetrieveAll();
} else {
eventloop_->RunInLoop(std::bind(&TcpConnection::Send, shared_from_this(),
message->RetrieveAllAsString()));
}
}
}
void TcpConnection::SendBuffer(const Buffer& message) {
SendInLoop(message.Peek(), message.ReadableSize());
}
void TcpConnection::Send(const std::string& s) {
SendInLoop(s.data(), s.size());
}
void TcpConnection::SendInLoop(const void* data, size_t size) {
eventloop_->AssertInMyLoop();
if (state_ == kDisconnected) {
VOYAGER_LOG(WARN) << "TcpConnection::SendInLoop[" << name_ << "]"
<< "has disconnected, give up writing.";
return;
}
ssize_t nwrote = 0;
size_t remaining = size;
bool fault = false;
if (!dispatch_->IsWriting() && writebuf_.ReadableSize() == 0) {
nwrote = ::write(dispatch_->Fd(), data, size);
if (nwrote >= 0) {
remaining = size - static_cast<size_t>(nwrote);
if (remaining == 0 && writecomplete_cb_) {
writecomplete_cb_(shared_from_this());
}
} else {
nwrote = 0;
if (errno == EPIPE || errno == ECONNRESET) {
HandleClose();
fault = true;
}
if (errno != EWOULDBLOCK && errno != EAGAIN) {
VOYAGER_LOG(ERROR) << "TcpConnection::SendInLoop [" << name_
<< "] - write: " << strerror(errno);
}
}
}
assert(remaining <= size);
if (!fault && remaining > 0) {
size_t old = writebuf_.ReadableSize();
if (high_water_mark_cb_ && old < high_water_mark_ &&
(old + remaining) >= high_water_mark_) {
eventloop_->QueueInLoop(
std::bind(high_water_mark_cb_, shared_from_this(), old + remaining));
}
writebuf_.Append(static_cast<const char*>(data) + nwrote, remaining);
if (!dispatch_->IsWriting()) {
dispatch_->EnableWrite();
}
}
}
std::string TcpConnection::StateToString() const {
const char* type;
switch (state_.load(std::memory_order_relaxed)) {
case kDisconnected:
type = "Disconnected";
break;
case kDisconnecting:
type = "Disconnecting";
break;
case kConnected:
type = "Connected";
break;
case kConnecting:
type = "Connecting";
break;
default:
type = "Unknown State";
break;
}
std::string result(type);
return result;
}
} // namespace voyager
|
// Copyright 2014 the V8 project 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 "src/compiler/int64-lowering.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/diamond.h"
#include "src/compiler/graph.h"
#include "src/compiler/linkage.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/node.h"
#include "src/wasm/wasm-module.h"
#include "src/zone/zone.h"
namespace v8 {
namespace internal {
namespace compiler {
Int64Lowering::Int64Lowering(Graph* graph, MachineOperatorBuilder* machine,
CommonOperatorBuilder* common, Zone* zone,
Signature<MachineRepresentation>* signature)
: zone_(zone),
graph_(graph),
machine_(machine),
common_(common),
state_(graph, 3),
stack_(zone),
replacements_(nullptr),
signature_(signature),
placeholder_(graph->NewNode(common->Parameter(-2, "placeholder"),
graph->start())) {
DCHECK_NOT_NULL(graph);
DCHECK_NOT_NULL(graph->end());
replacements_ = zone->NewArray<Replacement>(graph->NodeCount());
memset(replacements_, 0, sizeof(Replacement) * graph->NodeCount());
}
void Int64Lowering::LowerGraph() {
if (!machine()->Is32()) {
return;
}
stack_.push_back({graph()->end(), 0});
state_.Set(graph()->end(), State::kOnStack);
while (!stack_.empty()) {
NodeState& top = stack_.back();
if (top.input_index == top.node->InputCount()) {
// All inputs of top have already been lowered, now lower top.
stack_.pop_back();
state_.Set(top.node, State::kVisited);
LowerNode(top.node);
} else {
// Push the next input onto the stack.
Node* input = top.node->InputAt(top.input_index++);
if (state_.Get(input) == State::kUnvisited) {
if (input->opcode() == IrOpcode::kPhi) {
// To break cycles with phi nodes we push phis on a separate stack so
// that they are processed after all other nodes.
PreparePhiReplacement(input);
stack_.push_front({input, 0});
} else if (input->opcode() == IrOpcode::kEffectPhi ||
input->opcode() == IrOpcode::kLoop) {
stack_.push_front({input, 0});
} else {
stack_.push_back({input, 0});
}
state_.Set(input, State::kOnStack);
}
}
}
}
static int GetParameterIndexAfterLowering(
Signature<MachineRepresentation>* signature, int old_index) {
int result = old_index;
for (int i = 0; i < old_index; i++) {
if (signature->GetParam(i) == MachineRepresentation::kWord64) {
result++;
}
}
return result;
}
int Int64Lowering::GetParameterCountAfterLowering(
Signature<MachineRepresentation>* signature) {
// GetParameterIndexAfterLowering(parameter_count) returns the parameter count
// after lowering.
return GetParameterIndexAfterLowering(
signature, static_cast<int>(signature->parameter_count()));
}
static int GetReturnCountAfterLowering(
Signature<MachineRepresentation>* signature) {
int result = static_cast<int>(signature->return_count());
for (int i = 0; i < static_cast<int>(signature->return_count()); i++) {
if (signature->GetReturn(i) == MachineRepresentation::kWord64) {
result++;
}
}
return result;
}
void Int64Lowering::GetIndexNodes(Node* index, Node*& index_low,
Node*& index_high) {
if (HasReplacementLow(index)) {
index = GetReplacementLow(index);
}
#if defined(V8_TARGET_LITTLE_ENDIAN)
index_low = index;
index_high = graph()->NewNode(machine()->Int32Add(), index,
graph()->NewNode(common()->Int32Constant(4)));
#elif defined(V8_TARGET_BIG_ENDIAN)
index_low = graph()->NewNode(machine()->Int32Add(), index,
graph()->NewNode(common()->Int32Constant(4)));
index_high = index;
#endif
}
#if defined(V8_TARGET_LITTLE_ENDIAN)
const int Int64Lowering::kLowerWordOffset = 0;
const int Int64Lowering::kHigherWordOffset = 4;
#elif defined(V8_TARGET_BIG_ENDIAN)
const int Int64Lowering::kLowerWordOffset = 4;
const int Int64Lowering::kHigherWordOffset = 0;
#endif
void Int64Lowering::LowerNode(Node* node) {
switch (node->opcode()) {
case IrOpcode::kInt64Constant: {
int64_t value = OpParameter<int64_t>(node);
Node* low_node = graph()->NewNode(
common()->Int32Constant(static_cast<int32_t>(value & 0xFFFFFFFF)));
Node* high_node = graph()->NewNode(
common()->Int32Constant(static_cast<int32_t>(value >> 32)));
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kLoad:
case IrOpcode::kUnalignedLoad: {
MachineRepresentation rep;
if (node->opcode() == IrOpcode::kLoad) {
rep = LoadRepresentationOf(node->op()).representation();
} else {
DCHECK(node->opcode() == IrOpcode::kUnalignedLoad);
rep = UnalignedLoadRepresentationOf(node->op()).representation();
}
if (rep == MachineRepresentation::kWord64) {
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* index_low;
Node* index_high;
GetIndexNodes(index, index_low, index_high);
const Operator* load_op;
if (node->opcode() == IrOpcode::kLoad) {
load_op = machine()->Load(MachineType::Int32());
} else {
DCHECK(node->opcode() == IrOpcode::kUnalignedLoad);
load_op = machine()->UnalignedLoad(MachineType::Int32());
}
Node* high_node;
if (node->InputCount() > 2) {
Node* effect_high = node->InputAt(2);
Node* control_high = node->InputAt(3);
high_node = graph()->NewNode(load_op, base, index_high, effect_high,
control_high);
// change the effect change from old_node --> old_effect to
// old_node --> high_node --> old_effect.
node->ReplaceInput(2, high_node);
} else {
high_node = graph()->NewNode(load_op, base, index_high);
}
node->ReplaceInput(1, index_low);
NodeProperties::ChangeOp(node, load_op);
ReplaceNode(node, node, high_node);
} else {
DefaultLowering(node);
}
break;
}
case IrOpcode::kStore:
case IrOpcode::kUnalignedStore: {
MachineRepresentation rep;
if (node->opcode() == IrOpcode::kStore) {
rep = StoreRepresentationOf(node->op()).representation();
} else {
DCHECK(node->opcode() == IrOpcode::kUnalignedStore);
rep = UnalignedStoreRepresentationOf(node->op());
}
if (rep == MachineRepresentation::kWord64) {
// We change the original store node to store the low word, and create
// a new store node to store the high word. The effect and control edges
// are copied from the original store to the new store node, the effect
// edge of the original store is redirected to the new store.
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* index_low;
Node* index_high;
GetIndexNodes(index, index_low, index_high);
Node* value = node->InputAt(2);
DCHECK(HasReplacementLow(value));
DCHECK(HasReplacementHigh(value));
const Operator* store_op;
if (node->opcode() == IrOpcode::kStore) {
WriteBarrierKind write_barrier_kind =
StoreRepresentationOf(node->op()).write_barrier_kind();
store_op = machine()->Store(StoreRepresentation(
MachineRepresentation::kWord32, write_barrier_kind));
} else {
DCHECK(node->opcode() == IrOpcode::kUnalignedStore);
store_op = machine()->UnalignedStore(MachineRepresentation::kWord32);
}
Node* high_node;
if (node->InputCount() > 3) {
Node* effect_high = node->InputAt(3);
Node* control_high = node->InputAt(4);
high_node = graph()->NewNode(store_op, base, index_high,
GetReplacementHigh(value), effect_high,
control_high);
node->ReplaceInput(3, high_node);
} else {
high_node = graph()->NewNode(store_op, base, index_high,
GetReplacementHigh(value));
}
node->ReplaceInput(1, index_low);
node->ReplaceInput(2, GetReplacementLow(value));
NodeProperties::ChangeOp(node, store_op);
ReplaceNode(node, node, high_node);
} else {
DefaultLowering(node);
}
break;
}
case IrOpcode::kStart: {
int parameter_count = GetParameterCountAfterLowering(signature());
// Only exchange the node if the parameter count actually changed.
if (parameter_count != static_cast<int>(signature()->parameter_count())) {
int delta =
parameter_count - static_cast<int>(signature()->parameter_count());
int new_output_count = node->op()->ValueOutputCount() + delta;
NodeProperties::ChangeOp(node, common()->Start(new_output_count));
}
break;
}
case IrOpcode::kParameter: {
DCHECK(node->InputCount() == 1);
// Only exchange the node if the parameter count actually changed. We do
// not even have to do the default lowering because the the start node,
// the only input of a parameter node, only changes if the parameter count
// changes.
if (GetParameterCountAfterLowering(signature()) !=
static_cast<int>(signature()->parameter_count())) {
int old_index = ParameterIndexOf(node->op());
int new_index = GetParameterIndexAfterLowering(signature(), old_index);
NodeProperties::ChangeOp(node, common()->Parameter(new_index));
Node* high_node = nullptr;
if (signature()->GetParam(old_index) ==
MachineRepresentation::kWord64) {
high_node = graph()->NewNode(common()->Parameter(new_index + 1),
graph()->start());
}
ReplaceNode(node, node, high_node);
}
break;
}
case IrOpcode::kReturn: {
DefaultLowering(node);
int new_return_count = GetReturnCountAfterLowering(signature());
if (static_cast<int>(signature()->return_count()) != new_return_count) {
NodeProperties::ChangeOp(node, common()->Return(new_return_count));
}
break;
}
case IrOpcode::kCall: {
// TODO(turbofan): Make WASM code const-correct wrt. CallDescriptor.
CallDescriptor* descriptor =
const_cast<CallDescriptor*>(CallDescriptorOf(node->op()));
if (DefaultLowering(node) ||
(descriptor->ReturnCount() == 1 &&
descriptor->GetReturnType(0) == MachineType::Int64())) {
// We have to adjust the call descriptor.
const Operator* op = common()->Call(
wasm::ModuleEnv::GetI32WasmCallDescriptor(zone(), descriptor));
NodeProperties::ChangeOp(node, op);
}
if (descriptor->ReturnCount() == 1 &&
descriptor->GetReturnType(0) == MachineType::Int64()) {
// We access the additional return values through projections.
Node* low_node =
graph()->NewNode(common()->Projection(0), node, graph()->start());
Node* high_node =
graph()->NewNode(common()->Projection(1), node, graph()->start());
ReplaceNode(node, low_node, high_node);
}
break;
}
case IrOpcode::kWord64And: {
DCHECK(node->InputCount() == 2);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
Node* low_node =
graph()->NewNode(machine()->Word32And(), GetReplacementLow(left),
GetReplacementLow(right));
Node* high_node =
graph()->NewNode(machine()->Word32And(), GetReplacementHigh(left),
GetReplacementHigh(right));
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kTruncateInt64ToInt32: {
DCHECK(node->InputCount() == 1);
Node* input = node->InputAt(0);
ReplaceNode(node, GetReplacementLow(input), nullptr);
node->NullAllInputs();
break;
}
case IrOpcode::kInt64Add: {
DCHECK(node->InputCount() == 2);
Node* right = node->InputAt(1);
node->ReplaceInput(1, GetReplacementLow(right));
node->AppendInput(zone(), GetReplacementHigh(right));
Node* left = node->InputAt(0);
node->ReplaceInput(0, GetReplacementLow(left));
node->InsertInput(zone(), 1, GetReplacementHigh(left));
NodeProperties::ChangeOp(node, machine()->Int32PairAdd());
// We access the additional return values through projections.
Node* low_node =
graph()->NewNode(common()->Projection(0), node, graph()->start());
Node* high_node =
graph()->NewNode(common()->Projection(1), node, graph()->start());
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kInt64Sub: {
DCHECK(node->InputCount() == 2);
Node* right = node->InputAt(1);
node->ReplaceInput(1, GetReplacementLow(right));
node->AppendInput(zone(), GetReplacementHigh(right));
Node* left = node->InputAt(0);
node->ReplaceInput(0, GetReplacementLow(left));
node->InsertInput(zone(), 1, GetReplacementHigh(left));
NodeProperties::ChangeOp(node, machine()->Int32PairSub());
// We access the additional return values through projections.
Node* low_node =
graph()->NewNode(common()->Projection(0), node, graph()->start());
Node* high_node =
graph()->NewNode(common()->Projection(1), node, graph()->start());
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kInt64Mul: {
DCHECK(node->InputCount() == 2);
Node* right = node->InputAt(1);
node->ReplaceInput(1, GetReplacementLow(right));
node->AppendInput(zone(), GetReplacementHigh(right));
Node* left = node->InputAt(0);
node->ReplaceInput(0, GetReplacementLow(left));
node->InsertInput(zone(), 1, GetReplacementHigh(left));
NodeProperties::ChangeOp(node, machine()->Int32PairMul());
// We access the additional return values through projections.
Node* low_node =
graph()->NewNode(common()->Projection(0), node, graph()->start());
Node* high_node =
graph()->NewNode(common()->Projection(1), node, graph()->start());
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kWord64Or: {
DCHECK(node->InputCount() == 2);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
Node* low_node =
graph()->NewNode(machine()->Word32Or(), GetReplacementLow(left),
GetReplacementLow(right));
Node* high_node =
graph()->NewNode(machine()->Word32Or(), GetReplacementHigh(left),
GetReplacementHigh(right));
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kWord64Xor: {
DCHECK(node->InputCount() == 2);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
Node* low_node =
graph()->NewNode(machine()->Word32Xor(), GetReplacementLow(left),
GetReplacementLow(right));
Node* high_node =
graph()->NewNode(machine()->Word32Xor(), GetReplacementHigh(left),
GetReplacementHigh(right));
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kWord64Shl: {
// TODO(turbofan): if the shift count >= 32, then we can set the low word
// of the output to 0 and just calculate the high word.
DCHECK(node->InputCount() == 2);
Node* shift = node->InputAt(1);
if (HasReplacementLow(shift)) {
// We do not have to care about the high word replacement, because
// the shift can only be between 0 and 63 anyways.
node->ReplaceInput(1, GetReplacementLow(shift));
}
Node* value = node->InputAt(0);
node->ReplaceInput(0, GetReplacementLow(value));
node->InsertInput(zone(), 1, GetReplacementHigh(value));
NodeProperties::ChangeOp(node, machine()->Word32PairShl());
// We access the additional return values through projections.
Node* low_node =
graph()->NewNode(common()->Projection(0), node, graph()->start());
Node* high_node =
graph()->NewNode(common()->Projection(1), node, graph()->start());
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kWord64Shr: {
// TODO(turbofan): if the shift count >= 32, then we can set the low word
// of the output to 0 and just calculate the high word.
DCHECK(node->InputCount() == 2);
Node* shift = node->InputAt(1);
if (HasReplacementLow(shift)) {
// We do not have to care about the high word replacement, because
// the shift can only be between 0 and 63 anyways.
node->ReplaceInput(1, GetReplacementLow(shift));
}
Node* value = node->InputAt(0);
node->ReplaceInput(0, GetReplacementLow(value));
node->InsertInput(zone(), 1, GetReplacementHigh(value));
NodeProperties::ChangeOp(node, machine()->Word32PairShr());
// We access the additional return values through projections.
Node* low_node =
graph()->NewNode(common()->Projection(0), node, graph()->start());
Node* high_node =
graph()->NewNode(common()->Projection(1), node, graph()->start());
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kWord64Sar: {
// TODO(turbofan): if the shift count >= 32, then we can set the low word
// of the output to 0 and just calculate the high word.
DCHECK(node->InputCount() == 2);
Node* shift = node->InputAt(1);
if (HasReplacementLow(shift)) {
// We do not have to care about the high word replacement, because
// the shift can only be between 0 and 63 anyways.
node->ReplaceInput(1, GetReplacementLow(shift));
}
Node* value = node->InputAt(0);
node->ReplaceInput(0, GetReplacementLow(value));
node->InsertInput(zone(), 1, GetReplacementHigh(value));
NodeProperties::ChangeOp(node, machine()->Word32PairSar());
// We access the additional return values through projections.
Node* low_node =
graph()->NewNode(common()->Projection(0), node, graph()->start());
Node* high_node =
graph()->NewNode(common()->Projection(1), node, graph()->start());
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kWord64Equal: {
DCHECK(node->InputCount() == 2);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
// TODO(wasm): Use explicit comparisons and && here?
Node* replacement = graph()->NewNode(
machine()->Word32Equal(),
graph()->NewNode(
machine()->Word32Or(),
graph()->NewNode(machine()->Word32Xor(), GetReplacementLow(left),
GetReplacementLow(right)),
graph()->NewNode(machine()->Word32Xor(), GetReplacementHigh(left),
GetReplacementHigh(right))),
graph()->NewNode(common()->Int32Constant(0)));
ReplaceNode(node, replacement, nullptr);
break;
}
case IrOpcode::kInt64LessThan: {
LowerComparison(node, machine()->Int32LessThan(),
machine()->Uint32LessThan());
break;
}
case IrOpcode::kInt64LessThanOrEqual: {
LowerComparison(node, machine()->Int32LessThan(),
machine()->Uint32LessThanOrEqual());
break;
}
case IrOpcode::kUint64LessThan: {
LowerComparison(node, machine()->Uint32LessThan(),
machine()->Uint32LessThan());
break;
}
case IrOpcode::kUint64LessThanOrEqual: {
LowerComparison(node, machine()->Uint32LessThan(),
machine()->Uint32LessThanOrEqual());
break;
}
case IrOpcode::kChangeInt32ToInt64: {
DCHECK(node->InputCount() == 1);
Node* input = node->InputAt(0);
if (HasReplacementLow(input)) {
input = GetReplacementLow(input);
}
// We use SAR to preserve the sign in the high word.
ReplaceNode(
node, input,
graph()->NewNode(machine()->Word32Sar(), input,
graph()->NewNode(common()->Int32Constant(31))));
node->NullAllInputs();
break;
}
case IrOpcode::kChangeUint32ToUint64: {
DCHECK(node->InputCount() == 1);
Node* input = node->InputAt(0);
if (HasReplacementLow(input)) {
input = GetReplacementLow(input);
}
ReplaceNode(node, input, graph()->NewNode(common()->Int32Constant(0)));
node->NullAllInputs();
break;
}
case IrOpcode::kBitcastInt64ToFloat64: {
DCHECK(node->InputCount() == 1);
Node* input = node->InputAt(0);
Node* stack_slot = graph()->NewNode(
machine()->StackSlot(MachineRepresentation::kWord64));
Node* store_high_word = graph()->NewNode(
machine()->Store(
StoreRepresentation(MachineRepresentation::kWord32,
WriteBarrierKind::kNoWriteBarrier)),
stack_slot,
graph()->NewNode(common()->Int32Constant(kHigherWordOffset)),
GetReplacementHigh(input), graph()->start(), graph()->start());
Node* store_low_word = graph()->NewNode(
machine()->Store(
StoreRepresentation(MachineRepresentation::kWord32,
WriteBarrierKind::kNoWriteBarrier)),
stack_slot,
graph()->NewNode(common()->Int32Constant(kLowerWordOffset)),
GetReplacementLow(input), store_high_word, graph()->start());
Node* load =
graph()->NewNode(machine()->Load(MachineType::Float64()), stack_slot,
graph()->NewNode(common()->Int32Constant(0)),
store_low_word, graph()->start());
ReplaceNode(node, load, nullptr);
break;
}
case IrOpcode::kBitcastFloat64ToInt64: {
DCHECK(node->InputCount() == 1);
Node* input = node->InputAt(0);
if (HasReplacementLow(input)) {
input = GetReplacementLow(input);
}
Node* stack_slot = graph()->NewNode(
machine()->StackSlot(MachineRepresentation::kWord64));
Node* store = graph()->NewNode(
machine()->Store(
StoreRepresentation(MachineRepresentation::kFloat64,
WriteBarrierKind::kNoWriteBarrier)),
stack_slot, graph()->NewNode(common()->Int32Constant(0)), input,
graph()->start(), graph()->start());
Node* high_node = graph()->NewNode(
machine()->Load(MachineType::Int32()), stack_slot,
graph()->NewNode(common()->Int32Constant(kHigherWordOffset)), store,
graph()->start());
Node* low_node = graph()->NewNode(
machine()->Load(MachineType::Int32()), stack_slot,
graph()->NewNode(common()->Int32Constant(kLowerWordOffset)), store,
graph()->start());
ReplaceNode(node, low_node, high_node);
break;
}
case IrOpcode::kWord64Ror: {
DCHECK(node->InputCount() == 2);
Node* input = node->InputAt(0);
Node* shift = HasReplacementLow(node->InputAt(1))
? GetReplacementLow(node->InputAt(1))
: node->InputAt(1);
Int32Matcher m(shift);
if (m.HasValue()) {
// Precondition: 0 <= shift < 64.
int32_t shift_value = m.Value() & 0x3f;
if (shift_value == 0) {
ReplaceNode(node, GetReplacementLow(input),
GetReplacementHigh(input));
} else if (shift_value == 32) {
ReplaceNode(node, GetReplacementHigh(input),
GetReplacementLow(input));
} else {
Node* low_input;
Node* high_input;
if (shift_value < 32) {
low_input = GetReplacementLow(input);
high_input = GetReplacementHigh(input);
} else {
low_input = GetReplacementHigh(input);
high_input = GetReplacementLow(input);
}
int32_t masked_shift_value = shift_value & 0x1f;
Node* masked_shift =
graph()->NewNode(common()->Int32Constant(masked_shift_value));
Node* inv_shift = graph()->NewNode(
common()->Int32Constant(32 - masked_shift_value));
Node* low_node = graph()->NewNode(
machine()->Word32Or(),
graph()->NewNode(machine()->Word32Shr(), low_input, masked_shift),
graph()->NewNode(machine()->Word32Shl(), high_input, inv_shift));
Node* high_node = graph()->NewNode(
machine()->Word32Or(), graph()->NewNode(machine()->Word32Shr(),
high_input, masked_shift),
graph()->NewNode(machine()->Word32Shl(), low_input, inv_shift));
ReplaceNode(node, low_node, high_node);
}
} else {
Node* safe_shift = shift;
if (!machine()->Word32ShiftIsSafe()) {
safe_shift =
graph()->NewNode(machine()->Word32And(), shift,
graph()->NewNode(common()->Int32Constant(0x1f)));
}
// By creating this bit-mask with SAR and SHL we do not have to deal
// with shift == 0 as a special case.
Node* inv_mask = graph()->NewNode(
machine()->Word32Shl(),
graph()->NewNode(machine()->Word32Sar(),
graph()->NewNode(common()->Int32Constant(
std::numeric_limits<int32_t>::min())),
safe_shift),
graph()->NewNode(common()->Int32Constant(1)));
Node* bit_mask =
graph()->NewNode(machine()->Word32Xor(), inv_mask,
graph()->NewNode(common()->Int32Constant(-1)));
// We have to mask the shift value for this comparison. If
// !machine()->Word32ShiftIsSafe() then the masking should already be
// part of the graph.
Node* masked_shift6 = shift;
if (machine()->Word32ShiftIsSafe()) {
masked_shift6 =
graph()->NewNode(machine()->Word32And(), shift,
graph()->NewNode(common()->Int32Constant(0x3f)));
}
Diamond lt32(
graph(), common(),
graph()->NewNode(machine()->Int32LessThan(), masked_shift6,
graph()->NewNode(common()->Int32Constant(32))));
// The low word and the high word can be swapped either at the input or
// at the output. We swap the inputs so that shift does not have to be
// kept for so long in a register.
Node* input_low =
lt32.Phi(MachineRepresentation::kWord32, GetReplacementLow(input),
GetReplacementHigh(input));
Node* input_high =
lt32.Phi(MachineRepresentation::kWord32, GetReplacementHigh(input),
GetReplacementLow(input));
Node* rotate_low =
graph()->NewNode(machine()->Word32Ror(), input_low, safe_shift);
Node* rotate_high =
graph()->NewNode(machine()->Word32Ror(), input_high, safe_shift);
Node* low_node = graph()->NewNode(
machine()->Word32Or(),
graph()->NewNode(machine()->Word32And(), rotate_low, bit_mask),
graph()->NewNode(machine()->Word32And(), rotate_high, inv_mask));
Node* high_node = graph()->NewNode(
machine()->Word32Or(),
graph()->NewNode(machine()->Word32And(), rotate_high, bit_mask),
graph()->NewNode(machine()->Word32And(), rotate_low, inv_mask));
ReplaceNode(node, low_node, high_node);
}
break;
}
case IrOpcode::kWord64Clz: {
DCHECK(node->InputCount() == 1);
Node* input = node->InputAt(0);
Diamond d(
graph(), common(),
graph()->NewNode(machine()->Word32Equal(), GetReplacementHigh(input),
graph()->NewNode(common()->Int32Constant(0))));
Node* low_node = d.Phi(
MachineRepresentation::kWord32,
graph()->NewNode(machine()->Int32Add(),
graph()->NewNode(machine()->Word32Clz(),
GetReplacementLow(input)),
graph()->NewNode(common()->Int32Constant(32))),
graph()->NewNode(machine()->Word32Clz(), GetReplacementHigh(input)));
ReplaceNode(node, low_node, graph()->NewNode(common()->Int32Constant(0)));
break;
}
case IrOpcode::kWord64Ctz: {
DCHECK(node->InputCount() == 1);
DCHECK(machine()->Word32Ctz().IsSupported());
Node* input = node->InputAt(0);
Diamond d(
graph(), common(),
graph()->NewNode(machine()->Word32Equal(), GetReplacementLow(input),
graph()->NewNode(common()->Int32Constant(0))));
Node* low_node =
d.Phi(MachineRepresentation::kWord32,
graph()->NewNode(machine()->Int32Add(),
graph()->NewNode(machine()->Word32Ctz().op(),
GetReplacementHigh(input)),
graph()->NewNode(common()->Int32Constant(32))),
graph()->NewNode(machine()->Word32Ctz().op(),
GetReplacementLow(input)));
ReplaceNode(node, low_node, graph()->NewNode(common()->Int32Constant(0)));
break;
}
case IrOpcode::kWord64Popcnt: {
DCHECK(node->InputCount() == 1);
Node* input = node->InputAt(0);
// We assume that a Word64Popcnt node only has been created if
// Word32Popcnt is actually supported.
DCHECK(machine()->Word32Popcnt().IsSupported());
ReplaceNode(node, graph()->NewNode(
machine()->Int32Add(),
graph()->NewNode(machine()->Word32Popcnt().op(),
GetReplacementLow(input)),
graph()->NewNode(machine()->Word32Popcnt().op(),
GetReplacementHigh(input))),
graph()->NewNode(common()->Int32Constant(0)));
break;
}
case IrOpcode::kPhi: {
MachineRepresentation rep = PhiRepresentationOf(node->op());
if (rep == MachineRepresentation::kWord64) {
// The replacement nodes have already been created, we only have to
// replace placeholder nodes.
Node* low_node = GetReplacementLow(node);
Node* high_node = GetReplacementHigh(node);
for (int i = 0; i < node->op()->ValueInputCount(); i++) {
low_node->ReplaceInput(i, GetReplacementLow(node->InputAt(i)));
high_node->ReplaceInput(i, GetReplacementHigh(node->InputAt(i)));
}
} else {
DefaultLowering(node);
}
break;
}
case IrOpcode::kProjection: {
Node* call = node->InputAt(0);
DCHECK_EQ(IrOpcode::kCall, call->opcode());
CallDescriptor* descriptor =
const_cast<CallDescriptor*>(CallDescriptorOf(call->op()));
for (size_t i = 0; i < descriptor->ReturnCount(); i++) {
if (descriptor->GetReturnType(i) == MachineType::Int64()) {
UNREACHABLE(); // TODO(titzer): implement multiple i64 returns.
}
}
break;
}
case IrOpcode::kWord64ReverseBytes: {
Node* input = node->InputAt(0);
ReplaceNode(node, graph()->NewNode(machine()->Word32ReverseBytes().op(),
GetReplacementHigh(input)),
graph()->NewNode(machine()->Word32ReverseBytes().op(),
GetReplacementLow(input)));
break;
}
default: { DefaultLowering(node); }
}
} // NOLINT(readability/fn_size)
void Int64Lowering::LowerComparison(Node* node, const Operator* high_word_op,
const Operator* low_word_op) {
DCHECK(node->InputCount() == 2);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
Node* replacement = graph()->NewNode(
machine()->Word32Or(),
graph()->NewNode(high_word_op, GetReplacementHigh(left),
GetReplacementHigh(right)),
graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Word32Equal(), GetReplacementHigh(left),
GetReplacementHigh(right)),
graph()->NewNode(low_word_op, GetReplacementLow(left),
GetReplacementLow(right))));
ReplaceNode(node, replacement, nullptr);
}
bool Int64Lowering::DefaultLowering(Node* node) {
bool something_changed = false;
for (int i = NodeProperties::PastValueIndex(node) - 1; i >= 0; i--) {
Node* input = node->InputAt(i);
if (HasReplacementLow(input)) {
something_changed = true;
node->ReplaceInput(i, GetReplacementLow(input));
}
if (HasReplacementHigh(input)) {
something_changed = true;
node->InsertInput(zone(), i + 1, GetReplacementHigh(input));
}
}
return something_changed;
}
void Int64Lowering::ReplaceNode(Node* old, Node* new_low, Node* new_high) {
// if new_low == nullptr, then also new_high == nullptr.
DCHECK(new_low != nullptr || new_high == nullptr);
replacements_[old->id()].low = new_low;
replacements_[old->id()].high = new_high;
}
bool Int64Lowering::HasReplacementLow(Node* node) {
return replacements_[node->id()].low != nullptr;
}
Node* Int64Lowering::GetReplacementLow(Node* node) {
Node* result = replacements_[node->id()].low;
DCHECK(result);
return result;
}
bool Int64Lowering::HasReplacementHigh(Node* node) {
return replacements_[node->id()].high != nullptr;
}
Node* Int64Lowering::GetReplacementHigh(Node* node) {
Node* result = replacements_[node->id()].high;
DCHECK(result);
return result;
}
void Int64Lowering::PreparePhiReplacement(Node* phi) {
MachineRepresentation rep = PhiRepresentationOf(phi->op());
if (rep == MachineRepresentation::kWord64) {
// We have to create the replacements for a phi node before we actually
// lower the phi to break potential cycles in the graph. The replacements of
// input nodes do not exist yet, so we use a placeholder node to pass the
// graph verifier.
int value_count = phi->op()->ValueInputCount();
Node** inputs_low = zone()->NewArray<Node*>(value_count + 1);
Node** inputs_high = zone()->NewArray<Node*>(value_count + 1);
for (int i = 0; i < value_count; i++) {
inputs_low[i] = placeholder_;
inputs_high[i] = placeholder_;
}
inputs_low[value_count] = NodeProperties::GetControlInput(phi, 0);
inputs_high[value_count] = NodeProperties::GetControlInput(phi, 0);
ReplaceNode(phi,
graph()->NewNode(
common()->Phi(MachineRepresentation::kWord32, value_count),
value_count + 1, inputs_low, false),
graph()->NewNode(
common()->Phi(MachineRepresentation::kWord32, value_count),
value_count + 1, inputs_high, false));
}
}
} // namespace compiler
} // namespace internal
} // namespace v8
|
#include <cstdio>
#include <iostream>
using namespace std;
//barrel sort
//assume no duplicat.
//NO WA please🙏
bool barrel[4000010] = {0};
// int barrelblock[4001] = {0};
int main() {
int n, proc;
scanf("%d", &n);
while (n--) {
scanf("%d", &proc);
barrel[2000005 + proc] = 1;
/* ++barrelblock[(2000005 + proc) / 1000]; */
}
scanf("%d", &n);
while (n--) {
scanf("%d", &proc);
if (proc) {
scanf("%d", &proc);
barrel[2000005 + proc] = 1;
// ++barrelblock[(2000005 + proc) / 1000];
} else {
scanf("%d", &proc);
barrel[2000005 + proc] = 0;
// --barrelblock[(2000005 + proc) / 1000];
}
}
// for (int blk = 0; blk < 4000; blk++) {
for (int i = 1 /* blk * 1000 */; /* barrelblock[blk] && */ i < 4000010; i++) {
if (barrel[i]) {
printf("%d ", (i - 2000005));
// barrelblock[blk]--;
}
}
/* } */
return 0;
}
|
#if defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
#include "imgui.h"
#include "imgui_impl_dx11.h"
#include "imgui_impl_win32.h"
#include "ScopeGuard.h"
#include "Application.h"
struct IUnknown;
#include <d3d11.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>
#include <string>
// Data
static ID3D11Device* g_pd3dDevice = nullptr;
static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr;
static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr;
static void CreateRenderTarget()
{
DXGI_SWAP_CHAIN_DESC sd;
g_pSwapChain->GetDesc(&sd);
// Create the render target
ID3D11Texture2D* pBackBuffer;
D3D11_RENDER_TARGET_VIEW_DESC render_target_view_desc;
ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc));
render_target_view_desc.Format = sd.BufferDesc.Format;
render_target_view_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr);
pBackBuffer->Release();
}
static void CleanupRenderTarget()
{
if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; }
}
static HRESULT CreateDeviceD3D(HWND hWnd)
{
// Setup swap chain
DXGI_SWAP_CHAIN_DESC sd;
{
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
}
UINT createDeviceFlags = 0;
//createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
D3D_FEATURE_LEVEL featureLevel;
const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_0, };
if (D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 1, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
return E_FAIL;
CreateRenderTarget();
return S_OK;
}
static void CleanupDeviceD3D()
{
CleanupRenderTarget();
if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = nullptr; }
if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = nullptr; }
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; }
}
IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI ImGui_WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (g_pd3dDevice != nullptr && wParam != SIZE_MINIMIZED)
{
ImGui_ImplDX11_InvalidateDeviceObjects();
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
CreateRenderTarget();
ImGui_ImplDX11_CreateDeviceObjects();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
static ImFont* ImGui_LoadFont(ImFontAtlas& atlas, const char* name, float size, const ImVec2& displayOffset = ImVec2(0, 0))
{
char* windir = nullptr;
if (_dupenv_s(&windir, nullptr, "WINDIR") || windir == nullptr)
return nullptr;
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x0104, 0x017C, // Polish characters and more
0,
};
ImFontConfig config;
config.OversampleH = 4;
config.OversampleV = 4;
config.PixelSnapH = false;
auto path = std::string(windir) + "\\Fonts\\" + name;
auto font = atlas.AddFontFromFileTTF(path.c_str(), size, &config, ranges);
if (font)
font->DisplayOffset = displayOffset;
free(windir);
return font;
}
ImTextureID Application_LoadTexture(const char* path)
{
return ImGui_LoadTexture(path);
}
ImTextureID Application_CreateTexture(const void* data, int width, int height)
{
return ImGui_CreateTexture(data, width, height);
}
void Application_DestroyTexture(ImTextureID texture)
{
ImGui_DestroyTexture(texture);
}
int Application_GetTextureWidth(ImTextureID texture)
{
return ImGui_GetTextureWidth(texture);
}
int Application_GetTextureHeight(ImTextureID texture)
{
return ImGui_GetTextureHeight(texture);
}
# if defined(_UNICODE)
std::wstring widen(const std::string& str)
{
int size = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), nullptr, 0);
std::wstring result(size, 0);
MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), (wchar_t*)result.data(), size);
return result;
}
# endif
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd)
{
const auto c_ClassName = _T("Node Editor Class");
# if defined(_UNICODE)
const std::wstring c_WindowName = widen(Application_GetName());
# else
const std::string c_WindowName = Application_GetName();
# endif
# if defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
# endif
// Create application window
const auto wc = WNDCLASSEX{ sizeof(WNDCLASSEX), CS_CLASSDC, ImGui_WinProc, 0L, 0L, GetModuleHandle(nullptr), LoadIcon(GetModuleHandle(nullptr), IDI_APPLICATION),
LoadCursor(nullptr, IDC_ARROW), nullptr, nullptr, c_ClassName, LoadIcon(GetModuleHandle(nullptr), IDI_APPLICATION) };
RegisterClassEx(&wc); AX_SCOPE_EXIT { UnregisterClass(c_ClassName, wc.hInstance) ; };
auto hwnd = CreateWindow(c_ClassName, c_WindowName.c_str(), WS_OVERLAPPEDWINDOW, 1920 + 100, 100, 1440, 800, nullptr, nullptr, wc.hInstance, nullptr);
// Initialize Direct3D
AX_SCOPE_EXIT{ CleanupDeviceD3D(); };
if (CreateDeviceD3D(hwnd) < 0)
return 1;
ImFontAtlas fontAtlas;
auto defaultFont = ImGui_LoadFont(fontAtlas, "segoeui.ttf", 22.0f);//16.0f * 96.0f / 72.0f);
fontAtlas.Build();
//ImGuiFreeType::BuildFontAtlas(&fontAtlas);
// Setup ImGui binding
ImGui::CreateContext(&fontAtlas);
AX_SCOPE_EXIT{ ImGui::DestroyContext(); };
ImGuiIO& io = ImGui::GetIO();
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.IniFilename = nullptr;
io.LogFilename = nullptr;
// Setup ImGui binding
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
AX_SCOPE_EXIT
{
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
};
ImGui::StyleColorsDark();
//ImGuiStyle& style = ImGui::GetStyle();
//style.FrameRounding = 2.0f;
//style.WindowRounding = 0.0f;
//style.ScrollbarRounding = 0.0f;
ImVec4 backgroundColor = ImColor(32, 32, 32, 255);//style.Colors[ImGuiCol_TitleBg];
Application_Initialize();
AX_SCOPE_EXIT { Application_Finalize(); };
auto frame = [&]()
{
ImGui_ImplWin32_NewFrame();
ImGui_ImplDX11_NewFrame();
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(io.DisplaySize);
ImGui::Begin("Content", nullptr,
ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoBringToFrontOnFocus);
Application_Frame();
ImGui::End();
// Rendering
g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&backgroundColor);
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
};
frame();
ShowWindow(hwnd, SW_SHOWMAXIMIZED);
//ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
// Main loop
MSG msg = {};
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
{
if (msg.message == WM_KEYDOWN && (msg.wParam == VK_ESCAPE))
PostQuitMessage(0);
TranslateMessage(&msg);
DispatchMessage(&msg);
continue;
}
if (!IsIconic(hwnd))
frame();
}
return 0;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/fileapi/file_system_file_stream_reader.h"
#include "base/file_util_proxy.h"
#include "base/platform_file.h"
#include "base/single_thread_task_runner.h"
#include "net/base/file_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "webkit/blob/local_file_stream_reader.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_operation.h"
#include "webkit/fileapi/file_system_task_runners.h"
using webkit_blob::LocalFileStreamReader;
namespace fileapi {
namespace {
void ReadAdapter(base::WeakPtr<FileSystemFileStreamReader> reader,
net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
if (!reader.get())
return;
int rv = reader->Read(buf, buf_len, callback);
if (rv != net::ERR_IO_PENDING)
callback.Run(rv);
}
void GetLengthAdapter(base::WeakPtr<FileSystemFileStreamReader> reader,
const net::Int64CompletionCallback& callback) {
if (!reader.get())
return;
int rv = reader->GetLength(callback);
if (rv != net::ERR_IO_PENDING)
callback.Run(rv);
}
void Int64CallbackAdapter(const net::Int64CompletionCallback& callback,
int value) {
callback.Run(value);
}
} // namespace
FileSystemFileStreamReader::FileSystemFileStreamReader(
FileSystemContext* file_system_context,
const FileSystemURL& url,
int64 initial_offset,
const base::Time& expected_modification_time)
: file_system_context_(file_system_context),
url_(url),
initial_offset_(initial_offset),
expected_modification_time_(expected_modification_time),
has_pending_create_snapshot_(false),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
FileSystemFileStreamReader::~FileSystemFileStreamReader() {
}
int FileSystemFileStreamReader::Read(
net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
if (local_file_reader_.get())
return local_file_reader_->Read(buf, buf_len, callback);
return CreateSnapshot(
base::Bind(&ReadAdapter, weak_factory_.GetWeakPtr(),
make_scoped_refptr(buf), buf_len, callback),
callback);
}
int FileSystemFileStreamReader::GetLength(
const net::Int64CompletionCallback& callback) {
if (local_file_reader_.get())
return local_file_reader_->GetLength(callback);
return CreateSnapshot(
base::Bind(&GetLengthAdapter, weak_factory_.GetWeakPtr(), callback),
base::Bind(&Int64CallbackAdapter, callback));
}
int FileSystemFileStreamReader::CreateSnapshot(
const base::Closure& callback,
const net::CompletionCallback& error_callback) {
DCHECK(!has_pending_create_snapshot_);
base::PlatformFileError error_code;
FileSystemOperation* operation =
file_system_context_->CreateFileSystemOperation(url_, &error_code);
if (error_code != base::PLATFORM_FILE_OK)
return net::PlatformFileErrorToNetError(error_code);
has_pending_create_snapshot_ = true;
operation->CreateSnapshotFile(
url_,
base::Bind(&FileSystemFileStreamReader::DidCreateSnapshot,
weak_factory_.GetWeakPtr(),
callback,
error_callback));
return net::ERR_IO_PENDING;
}
void FileSystemFileStreamReader::DidCreateSnapshot(
const base::Closure& callback,
const net::CompletionCallback& error_callback,
base::PlatformFileError file_error,
const base::PlatformFileInfo& file_info,
const FilePath& platform_path,
const scoped_refptr<webkit_blob::ShareableFileReference>& file_ref) {
DCHECK(has_pending_create_snapshot_);
DCHECK(!local_file_reader_.get());
has_pending_create_snapshot_ = false;
if (file_error != base::PLATFORM_FILE_OK) {
error_callback.Run(net::PlatformFileErrorToNetError(file_error));
return;
}
// Keep the reference (if it's non-null) so that the file won't go away.
snapshot_ref_ = file_ref;
local_file_reader_.reset(
new LocalFileStreamReader(
file_system_context_->task_runners()->file_task_runner(),
platform_path, initial_offset_, expected_modification_time_));
callback.Run();
}
} // namespace fileapi
|
/*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FEBondRelaxation.h"
#include "FEElasticMaterial.h"
#include <FECore/log.h>
#include <FECore/expint_Ei.h>
///////////////////////////////////////////////////////////////////////////////
//
// FEBondRelaxationExponential
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// define the material parameters
BEGIN_FECORE_CLASS(FEBondRelaxationExponential, FEBondRelaxation)
ADD_PARAMETER(m_tau, FE_RANGE_GREATER(0.0), "tau");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! Constructor.
FEBondRelaxationExponential::FEBondRelaxationExponential(FEModel* pfem) : FEBondRelaxation(pfem)
{
m_tau = 0;
}
//-----------------------------------------------------------------------------
//! Relaxation function
double FEBondRelaxationExponential::Relaxation(FEMaterialPoint& mp, const double t, const mat3ds D)
{
// --- constant relaxation times ---
double g = exp(-t/m_tau);
return g;
}
///////////////////////////////////////////////////////////////////////////////
//
// FEBondRelaxationExpDistortion
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// define the material parameters
BEGIN_FECORE_CLASS(FEBondRelaxationExpDistortion, FEBondRelaxation)
ADD_PARAMETER(m_tau0 , FE_RANGE_GREATER (0.0), "tau0" );
ADD_PARAMETER(m_tau1 , FE_RANGE_GREATER_OR_EQUAL(0.0), "tau1" );
ADD_PARAMETER(m_alpha, FE_RANGE_GREATER_OR_EQUAL(0.0), "alpha");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! Constructor.
FEBondRelaxationExpDistortion::FEBondRelaxationExpDistortion(FEModel* pfem) : FEBondRelaxation(pfem)
{
m_tau0 = 0;
m_tau1 = 0;
m_alpha = 1;
}
//-----------------------------------------------------------------------------
//! Relaxation function
double FEBondRelaxationExpDistortion::Relaxation(FEMaterialPoint& mp, const double t, const mat3ds D)
{
// get the elastic material point data
FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>();
// evaluate spatial Hencky (logarithmic) strain
mat3ds B = pt.LeftCauchyGreen();
double d[3];
vec3d v[3];
B.eigen2(d,v);
mat3ds h = (dyad(v[0])*log(d[0]) + dyad(v[1])*log(d[1]) + dyad(v[2])*log(d[2]))/2;
// evaluate distortion magnitude (always positive)
double K2 = (h.dev()).norm();
double K2a = pow(K2,m_alpha);
double tau = m_tau0 + m_tau1*K2a;
double g = exp(-t/tau);
return g;
}
///////////////////////////////////////////////////////////////////////////////
//
// FEBondRelaxationFung
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// define the material parameters
BEGIN_FECORE_CLASS(FEBondRelaxationFung, FEBondRelaxation)
ADD_PARAMETER(m_tau1, FE_RANGE_GREATER(0.0), "tau1");
ADD_PARAMETER(m_tau2, FE_RANGE_GREATER(0.0), "tau2");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! Constructor.
FEBondRelaxationFung::FEBondRelaxationFung(FEModel* pfem) : FEBondRelaxation(pfem)
{
}
//-----------------------------------------------------------------------------
//! Initialization.
bool FEBondRelaxationFung::Validate()
{
if (FEBondRelaxation::Validate() == false) return false;
if (m_tau2 <= m_tau1) { feLogError("tau2 must be > tau1"); return false; }
return true;
}
//-----------------------------------------------------------------------------
//! Relaxation function
double FEBondRelaxationFung::Relaxation(FEMaterialPoint& mp, const double t, const mat3ds D)
{
double g = 0;
if (t > 0) {
g = (m_tau2*exp(-t/m_tau2) - m_tau1*exp(-t/m_tau1)
+ t*(expint_Ei(-t/m_tau2) - expint_Ei(-t/m_tau1)))
/(m_tau2 - m_tau1);
}
else
g = 1;
return g;
}
///////////////////////////////////////////////////////////////////////////////
//
// FEBondRelaxationPark
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// define the material parameters
BEGIN_FECORE_CLASS(FEBondRelaxationPark, FEBondRelaxation)
ADD_PARAMETER(m_tau , FE_RANGE_GREATER(0.0), "tau");
ADD_PARAMETER(m_beta, FE_RANGE_GREATER(0.0), "beta");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! Constructor.
FEBondRelaxationPark::FEBondRelaxationPark(FEModel* pfem) : FEBondRelaxation(pfem)
{
}
//-----------------------------------------------------------------------------
//! Relaxation function
double FEBondRelaxationPark::Relaxation(FEMaterialPoint& mp, const double t, const mat3ds D)
{
double g = 1./(1+pow(t/m_tau,m_beta));
return g;
}
///////////////////////////////////////////////////////////////////////////////
//
// FEBondRelaxationParkDistortion
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// define the material parameters
BEGIN_FECORE_CLASS(FEBondRelaxationParkDistortion, FEBondRelaxation)
ADD_PARAMETER(m_tau0 , FE_RANGE_GREATER (0.0), "tau0" );
ADD_PARAMETER(m_tau1 , FE_RANGE_GREATER_OR_EQUAL(0.0), "tau1" );
ADD_PARAMETER(m_beta0, FE_RANGE_GREATER (0.0), "beta0");
ADD_PARAMETER(m_beta1, FE_RANGE_GREATER_OR_EQUAL(0.0), "beta1");
ADD_PARAMETER(m_alpha, FE_RANGE_GREATER_OR_EQUAL(0.0), "alpha");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! Constructor.
FEBondRelaxationParkDistortion::FEBondRelaxationParkDistortion(FEModel* pfem) : FEBondRelaxation(pfem)
{
m_tau0 = 0;
m_beta0 = 0;
m_tau1 = 0;
m_beta1 = 0;
m_alpha = 1;
}
//-----------------------------------------------------------------------------
//! Relaxation function
double FEBondRelaxationParkDistortion::Relaxation(FEMaterialPoint& mp, const double t, const mat3ds D)
{
double g;
// get the elastic material point data
FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>();
// evaluate spatial Hencky (logarithmic) strain
mat3ds B = pt.LeftCauchyGreen();
double d[3];
vec3d v[3];
B.eigen2(d,v);
mat3ds h = (dyad(v[0])*log(d[0]) + dyad(v[1])*log(d[1]) + dyad(v[2])*log(d[2]))/2;
// evaluate distortion magnitude (always positive)
double K2 = (h.dev()).norm();
double K2a = pow(K2,m_alpha);
double tau = m_tau0 + m_tau1*K2a;
double beta = m_beta0 + m_beta1*K2a;
g = 1./(1+pow(t/tau,beta));
return g;
}
///////////////////////////////////////////////////////////////////////////////
//
// FEBondRelaxationPower
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// define the material parameters
BEGIN_FECORE_CLASS(FEBondRelaxationPower, FEBondRelaxation)
ADD_PARAMETER(m_tau , FE_RANGE_GREATER(0.0), "tau");
ADD_PARAMETER(m_beta, FE_RANGE_GREATER(0.0), "beta");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! Constructor.
FEBondRelaxationPower::FEBondRelaxationPower(FEModel* pfem) : FEBondRelaxation(pfem)
{
}
//-----------------------------------------------------------------------------
//! Relaxation function
double FEBondRelaxationPower::Relaxation(FEMaterialPoint& mp, const double t, const mat3ds D)
{
double g = pow(1+t/m_tau,-m_beta);
return g;
}
///////////////////////////////////////////////////////////////////////////////
//
// FEBondRelaxationPowerDistortion
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// define the material parameters
BEGIN_FECORE_CLASS(FEBondRelaxationPowerDistortion, FEBondRelaxation)
ADD_PARAMETER(m_tau0 , FE_RANGE_GREATER (0.0), "tau0");
ADD_PARAMETER(m_tau1 , FE_RANGE_GREATER_OR_EQUAL(0.0), "tau1");
ADD_PARAMETER(m_beta0, FE_RANGE_GREATER (0.0), "beta0");
ADD_PARAMETER(m_beta1, FE_RANGE_GREATER_OR_EQUAL(0.0), "beta1");
ADD_PARAMETER(m_alpha, FE_RANGE_GREATER_OR_EQUAL(0.0), "alpha");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! Constructor.
FEBondRelaxationPowerDistortion::FEBondRelaxationPowerDistortion(FEModel* pfem) : FEBondRelaxation(pfem)
{
m_tau1 = 0;
m_alpha = 1;
}
//-----------------------------------------------------------------------------
//! Relaxation function
double FEBondRelaxationPowerDistortion::Relaxation(FEMaterialPoint& mp, const double t, const mat3ds D)
{
double g;
// get the elastic material point data
FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>();
// evaluate spatial Hencky (logarithmic) strain
mat3ds B = pt.LeftCauchyGreen();
double d[3];
vec3d v[3];
B.eigen2(d,v);
mat3ds h = (dyad(v[0])*log(d[0]) + dyad(v[1])*log(d[1]) + dyad(v[2])*log(d[2]))/2;
// evaluate distortion magnitude (always positive)
double K2 = (h.dev()).norm();
double K2a = pow(K2,m_alpha);
double tau = m_tau0 + m_tau1*K2a;
double beta = m_beta0 + m_beta1*K2a;
g = pow(1+t/tau,-beta);
return g;
}
///////////////////////////////////////////////////////////////////////////////
//
// FEBondRelaxationCarreau
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// define the material parameters
BEGIN_FECORE_CLASS(FEBondRelaxationCarreau, FEBondRelaxation)
ADD_PARAMETER(m_tau0 , FE_RANGE_GREATER (0.0), "tau0");
ADD_PARAMETER(m_lam , FE_RANGE_GREATER_OR_EQUAL(0.0), "lambda");
ADD_PARAMETER(m_n , FE_RANGE_GREATER (0.0), "n");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! Constructor.
FEBondRelaxationCarreau::FEBondRelaxationCarreau(FEModel* pfem) : FEBondRelaxation(pfem)
{
m_tau0 = 0;
m_lam = 0;
m_n = 1;
}
//-----------------------------------------------------------------------------
//! Relaxation function
double FEBondRelaxationCarreau::Relaxation(FEMaterialPoint& mp, const double t, const mat3ds D)
{
double g;
// evaluate the engineering shear rate
double gdot = sqrt(2.)*D.norm();
// evaluate the relaxation time
double tau = m_tau0*pow(1+pow(m_lam*gdot,2),(m_n-1)/2.);
g = exp(-t/tau);
return g;
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iotsitewise/model/ListTagsForResourceRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::IoTSiteWise::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws::Http;
ListTagsForResourceRequest::ListTagsForResourceRequest() :
m_resourceArnHasBeenSet(false)
{
}
Aws::String ListTagsForResourceRequest::SerializePayload() const
{
return {};
}
void ListTagsForResourceRequest::AddQueryStringParameters(URI& uri) const
{
Aws::StringStream ss;
if(m_resourceArnHasBeenSet)
{
ss << m_resourceArn;
uri.AddQueryStringParameter("resourceArn", ss.str());
ss.str("");
}
}
|
#include "Lifx.h"
#include "LifxMessageHandler.h"
#include <Arduino.h>
Lifx::Lifx(LifxDevice *device)
{
this->device = device;
}
// TODO: add debug serial prints
void Lifx::begin()
{
this->Udp.begin(LIFX_PORT);
}
void Lifx::handle()
{
int packetSize = this->Udp.parsePacket();
if (packetSize)
{
byte packet[LIFX_PACKET_MAX_LENGTH];
this->Udp.read(packet, LIFX_PACKET_MAX_LENGTH);
LifxMessage message;
LifxMessageHandler::parseMessage(packet, packetSize, message);
this->handleMessage(message);
}
}
void Lifx::handleMessage(LifxMessage message)
{
if (message.tagged == 0 && memcmp(message.target, this->device->getMacAddress(), 8) == 0)
{
return;
}
Serial.println(message.type, HEX);
if (message.type == GET_SERVICE)
{
LifxMessage response;
response.type = STATE_SERVICE;
response.protocol = LIFX_PROTOCOL;
byte stateServiceData[] = {
0x01, //UDP
lowByte(LIFX_PORT),
highByte(LIFX_PORT),
0x00,
0x00};
memcpy(response.payload, stateServiceData, sizeof(stateServiceData));
response.payload_size = sizeof(stateServiceData);
this->sendMessage(response, message.tagged == 1);
}
if (message.type == GET_WIFI_FIRMWARE)
{
LifxMessage response;
response.type = STATE_WIFI_FIRMWARE;
response.protocol = LIFX_PROTOCOL;
byte WifiVersionData[] = {
0x00, 0x70, 0xA6, 0xC7, 0x74, 0xF0, 0xDA, 0x13, //build timestamp
0xc0, 0x0c, 0x07, 0x00, 0x48, 0x46, 0xd9, 0x43, //install timestamp
lowByte(1),
highByte(1),
lowByte(2),
highByte(2)};
memcpy(response.payload, WifiVersionData, sizeof(WifiVersionData));
response.payload_size = sizeof(WifiVersionData);
this->sendMessage(response, message.tagged == 1);
}
if (message.type == GET_HOST_FIRMWARE)
{
LifxMessage response;
response.type = STATE_HOST_FIRMWARE;
response.protocol = LIFX_PROTOCOL;
byte HostFirmwareData[] = {
0x00, 0xA6, 0xD4, 0x73, 0x1A, 0x21, 0xE0, 0x13, //build timestamp
0xe0, 0x25, 0x76, 0x45, 0x69, 0x81, 0x8b, 0x13, //install timestamp
lowByte(1),
highByte(1),
lowByte(2),
highByte(2)};
memcpy(response.payload, HostFirmwareData, sizeof(HostFirmwareData));
response.payload_size = sizeof(HostFirmwareData);
this->sendMessage(response, message.tagged == 1);
}
if (message.type == GET_VERSION)
{
LifxMessage response;
response.type = STATE_VERSION;
response.protocol = LIFX_PROTOCOL;
byte VersionData[] = {
lowByte(1),
highByte(1),
0x00,
0x00,
lowByte(1),
highByte(1),
0x00,
0x00,
lowByte(1),
highByte(1),
0x00,
0x00};
memcpy(response.payload, VersionData, sizeof(VersionData));
response.payload_size = sizeof(VersionData);
this->sendMessage(response, message.tagged == 1);
}
if (message.type == GET)
{
char label[32] = "arduino light";
LifxMessage response;
response.type = STATE;
response.protocol = LIFX_PROTOCOL;
byte StateData[] = {
// HSBK
lowByte(0x00), //hue
highByte(0x00),
lowByte(0x00), //saturation
highByte(0x00),
lowByte(0x00), //brightness
highByte(0x00),
lowByte(0x00), //kelvin
highByte(0x00),
//reserved
lowByte(0x00),
highByte(0x00),
//power
lowByte(0x00),
highByte(0x00),
// label
lowByte(label[0]),
lowByte(label[1]),
lowByte(label[2]),
lowByte(label[3]),
lowByte(label[4]),
lowByte(label[5]),
lowByte(label[6]),
lowByte(label[7]),
lowByte(label[8]),
lowByte(label[9]),
lowByte(label[10]),
lowByte(label[11]),
lowByte(label[12]),
lowByte(label[13]),
lowByte(label[14]),
lowByte(label[15]),
lowByte(label[16]),
lowByte(label[17]),
lowByte(label[18]),
lowByte(label[19]),
lowByte(label[20]),
lowByte(label[21]),
lowByte(label[22]),
lowByte(label[23]),
lowByte(label[24]),
lowByte(label[25]),
lowByte(label[26]),
lowByte(label[27]),
lowByte(label[28]),
lowByte(label[29]),
lowByte(label[30]),
lowByte(label[31]),
//reserved
lowByte(0x00),
lowByte(0x00),
lowByte(0x00),
lowByte(0x00),
lowByte(0x00),
lowByte(0x00),
lowByte(0x00),
lowByte(0x00)};
memcpy(response.payload, StateData, sizeof(StateData));
response.payload_size = sizeof(StateData);
this->sendMessage(response, message.tagged == 1);
}
}
// TODO: refactor
void Lifx::sendMessage(LifxMessage &message, bool broadcast)
{
IPAddress remote_addr(Udp.remoteIP());
if (broadcast)
{
remote_addr[3] = 255;
}
Udp.beginPacket(remote_addr, Udp.remotePort());
// size
Udp.write(lowByte(LIFX_PACKET_HEADER_LENGTH + message.payload_size));
Udp.write(highByte(LIFX_PACKET_HEADER_LENGTH + message.payload_size));
// protocol, addressable, tagged, origin
uint16_t test = (message.protocol + (message.addressable << 12) + (message.tagged << 13) + (message.origin << 14)) >> 8;
Udp.write(lowByte(test));
Udp.write(highByte(test));
// source
unsigned char *source = (unsigned char *)&message.source;
Udp.write(lowByte(source[0]));
Udp.write(lowByte(source[1]));
Udp.write(lowByte(source[2]));
Udp.write(lowByte(source[3]));
// target
Udp.write(this->device->getMacAddress(), 8);
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
// ack and res
Udp.write(lowByte(message.ack_required + message.res_required));
Udp.write(lowByte(message.sequence));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
Udp.write(lowByte(message.type));
Udp.write(highByte(message.type));
Udp.write(lowByte(0x00));
Udp.write(lowByte(0x00));
for (int i = 0; i < message.payload_size; i++)
{
Udp.write(lowByte(message.payload[i]));
}
Udp.endPacket();
}
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h"
#include <stdint.h>
#include <string>
#include "ash/constants/ash_paths.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/numerics/safe_conversions.h"
#include "base/path_service.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/ash/settings/cros_settings.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/policy/device_policy_builder.h"
#include "chrome/common/chrome_paths.h"
#include "chromeos/dbus/constants/dbus_paths.h"
#include "chromeos/dbus/cryptohome/tpm_util.h"
#include "chromeos/dbus/session_manager/fake_session_manager_client.h"
#include "chromeos/settings/cros_settings_names.h"
#include "chromeos/tpm/install_attributes.h"
#include "components/prefs/pref_service.h"
#include "crypto/rsa_private_key.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Return;
namespace em = enterprise_management;
namespace policy {
void DeviceLocalAccountTestHelper::SetupDeviceLocalAccount(
UserPolicyBuilder* policy_builder,
const std::string& kAccountId,
const std::string& kDisplayName) {
policy_builder->policy_data().set_policy_type(
policy::dm_protocol::kChromePublicAccountPolicyType);
policy_builder->policy_data().set_username(kAccountId);
policy_builder->policy_data().set_settings_entity_id(kAccountId);
policy_builder->policy_data().set_public_key_version(1);
policy_builder->payload().mutable_userdisplayname()->set_value(kDisplayName);
policy_builder->payload()
.mutable_devicelocalaccountmanagedsessionenabled()
->set_value(true);
}
void DeviceLocalAccountTestHelper::AddPublicSession(
em::ChromeDeviceSettingsProto* proto,
const std::string& kAccountId) {
proto->mutable_show_user_names()->set_show_user_names(true);
em::DeviceLocalAccountInfoProto* account =
proto->mutable_device_local_accounts()->add_account();
account->set_account_id(kAccountId);
account->set_type(
em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_PUBLIC_SESSION);
}
LocalStateValueWaiter::LocalStateValueWaiter(const std::string& pref,
base::Value expected_value)
: pref_(pref), expected_value_(std::move(expected_value)) {
pref_change_registrar_.Init(g_browser_process->local_state());
}
LocalStateValueWaiter::~LocalStateValueWaiter() {}
bool LocalStateValueWaiter::ExpectedValueFound() {
const base::Value* pref_value =
pref_change_registrar_.prefs()->Get(pref_.c_str());
if (!pref_value) {
// Can't use ASSERT_* in non-void functions so this is the next best
// thing.
ADD_FAILURE() << "Pref " << pref_ << " not found";
return true;
}
return *pref_value == expected_value_;
}
void LocalStateValueWaiter::QuitLoopIfExpectedValueFound() {
if (ExpectedValueFound())
run_loop_.Quit();
}
void LocalStateValueWaiter::Wait() {
pref_change_registrar_.Add(
pref_.c_str(),
base::BindRepeating(&LocalStateValueWaiter::QuitLoopIfExpectedValueFound,
base::Unretained(this)));
// Necessary if the pref value changes before the run loop is run. It is
// safe to call RunLoop::Quit before RunLoop::Run (in which case the call
// to Run will do nothing).
QuitLoopIfExpectedValueFound();
run_loop_.Run();
}
DictionaryLocalStateValueWaiter::DictionaryLocalStateValueWaiter(
const std::string& pref,
const std::string& expected_value,
const std::string& key)
: LocalStateValueWaiter(pref, base::Value(expected_value)), key_(key) {}
DictionaryLocalStateValueWaiter::~DictionaryLocalStateValueWaiter() {}
bool DictionaryLocalStateValueWaiter::ExpectedValueFound() {
const base::DictionaryValue* pref =
pref_change_registrar_.prefs()->GetDictionary(pref_.c_str());
if (!pref) {
// Can't use ASSERT_* in non-void functions so this is the next best
// thing.
ADD_FAILURE() << "Pref " << pref_ << " not found";
return true;
}
std::string actual_value;
return (pref->GetStringWithoutPathExpansion(key_, &actual_value) &&
actual_value == expected_value_.GetString());
}
DevicePolicyCrosTestHelper::DevicePolicyCrosTestHelper() {}
DevicePolicyCrosTestHelper::~DevicePolicyCrosTestHelper() {}
void DevicePolicyCrosTestHelper::InstallOwnerKey() {
OverridePaths();
base::FilePath owner_key_file;
ASSERT_TRUE(base::PathService::Get(chromeos::dbus_paths::FILE_OWNER_KEY,
&owner_key_file));
std::string owner_key_bits = device_policy()->GetPublicSigningKeyAsString();
ASSERT_FALSE(owner_key_bits.empty());
ASSERT_EQ(base::checked_cast<int>(owner_key_bits.length()),
base::WriteFile(owner_key_file, owner_key_bits.data(),
owner_key_bits.length()));
}
// static
void DevicePolicyCrosTestHelper::OverridePaths() {
// This is usually done by ChromeBrowserMainChromeOS, but some tests
// use the overridden paths before ChromeBrowserMain starts. Make sure that
// the paths are overridden before using them.
base::FilePath user_data_dir;
ASSERT_TRUE(base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir));
base::ScopedAllowBlockingForTesting allow_io;
chromeos::RegisterStubPathOverrides(user_data_dir);
chromeos::dbus_paths::RegisterStubPathOverrides(user_data_dir);
}
const std::string DevicePolicyCrosTestHelper::device_policy_blob() {
// Reset the key to its original state.
device_policy()->SetDefaultSigningKey();
device_policy()->Build();
return device_policy()->GetBlob();
}
void DevicePolicyCrosTestHelper::RefreshDevicePolicy() {
chromeos::FakeSessionManagerClient::Get()->set_device_policy(
device_policy_blob());
chromeos::FakeSessionManagerClient::Get()->OnPropertyChangeComplete(true);
}
void DevicePolicyCrosTestHelper::RefreshPolicyAndWaitUntilDeviceSettingsUpdated(
const std::vector<std::string>& settings) {
base::RunLoop run_loop;
// For calls from SetPolicy().
std::vector<base::CallbackListSubscription> subscriptions = {};
for (auto setting_it = settings.cbegin(); setting_it != settings.cend();
setting_it++) {
subscriptions.push_back(chromeos::CrosSettings::Get()->AddSettingsObserver(
*setting_it, run_loop.QuitClosure()));
}
RefreshDevicePolicy();
run_loop.Run();
// Allow tasks posted by CrosSettings observers to complete:
base::RunLoop().RunUntilIdle();
}
void DevicePolicyCrosTestHelper::UnsetPolicy(
const std::vector<std::string>& settings) {
em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
proto.clear_display_rotation_default();
proto.clear_device_display_resolution();
RefreshPolicyAndWaitUntilDeviceSettingsUpdated(settings);
}
DevicePolicyCrosBrowserTest::DevicePolicyCrosBrowserTest() {}
DevicePolicyCrosBrowserTest::~DevicePolicyCrosBrowserTest() = default;
chromeos::FakeSessionManagerClient*
DevicePolicyCrosBrowserTest::session_manager_client() {
return chromeos::FakeSessionManagerClient::Get();
}
} // namespace policy
|
/*
* Copyright 2010, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#include <extended_system_info.h>
#include <extended_system_info_defs.h>
#include <syscalls.h>
#include <AutoDeleter.h>
#include <util/KMessage.h>
namespace BPrivate {
status_t
get_extended_team_info(team_id teamID, uint32 flags, KMessage& info)
{
// initial buffer size
size_t bufferSize = 4096;
// TODO: Pick it depending on the set flags.
while (true) {
// allocate the buffer
void* buffer = malloc(bufferSize);
if (buffer == NULL)
return B_NO_MEMORY;
MemoryDeleter bufferDeleter(buffer);
// get the info
size_t sizeNeeded;
status_t error = _kern_get_extended_team_info(teamID, flags, buffer,
bufferSize, &sizeNeeded);
if (error == B_OK) {
return info.SetTo((const void*)buffer, sizeNeeded,
KMessage::KMESSAGE_CLONE_BUFFER);
// TODO: Just transfer our buffer, if it isn't much larger.
}
if (error != B_BUFFER_OVERFLOW)
return error;
// The buffer was too small. Try again with a larger one.
bufferSize = (sizeNeeded + 1023) / 1024 * 1024;
}
}
} // namespace BPrivate
|
#pragma once
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include "State.hpp"
/**
* @brief A turing machine emulator.
*
*/
class Machine
{
public:
/**
* @brief Construct the machine object.
*
*/
Machine();
/**
* @brief Load the machine states.
*
*/
void loadStates(std::vector<State> states);
/**
* @brief Set the state of the tape.
*
*/
void setTape(std::vector<signed char> new_tape);
/**
* @brief Get a string representing the tape.
*
* @return std::string A string representing the tape.
*/
std::string getTape();
/**
* @brief Set the head position.
*
* @param pos The new head position.
*/
void setPosition(size_t pos);
/**
* @brief Set the machines state.
*
* @param name The name of the state.
*/
void setState(std::string name);
/**
* @brief Step the machine forward one iteration.
*
*/
void step();
/**
* @brief Step until the machine has halted.
*
*/
void run();
/**
* @brief Check if the machine has halted or not.
*
* @return bool whether or not the machine is running.
*/
bool isRunning();
private:
/**
* @brief The machine tape.
*
* @remarks -1 is a blank tape item.
*
*/
std::vector<signed char> mTape;
/**
* @brief The max tape length;
*
*/
const int WRAP = 1000;
/**
* @brief The position we are in in the tape.
*
*/
int mHead;
//Tape read/write functions.
signed char* next();
signed char* prev();
signed char* get();
void set(signed char n);
bool mForward = true;
/**
* @brief Get the State with the given name.
*
* @param state_name The name of the state
* @return State& A reference to that state.
*/
State& getState(std::string state_name);
/**
* @brief The machine states.
*
*/
std::vector<State> mStates;
/**
* @brief The currently running state.
*
*/
std::string mCState;
/**
* @brief Whether or not the machine has halted.
*
*/
bool mRunning = false;
};
|
// Common/ListFileUtils.cpp
#include "StdAfx.h"
#include "MyWindows.h"
#include "../Windows/FileIO.h"
#include "ListFileUtils.h"
#include "StringConvert.h"
#include "UTFConvert.h"
static const char kQuoteChar = '\"';
static void RemoveQuote(UString &s)
{
if (s.Length() >= 2)
if (s[0] == kQuoteChar && s[s.Length() - 1] == kQuoteChar)
s = s.Mid(1, s.Length() - 2);
}
bool ReadNamesFromListFile(LPCWSTR fileName, UStringVector &resultStrings, UINT codePage)
{
NWindows::NFile::NIO::CInFile file;
if (!file.Open(fileName))
return false;
UInt64 length;
if (!file.GetLength(length))
return false;
if (length > ((UInt32)1 << 31))
return false;
AString s;
char *p = s.GetBuffer((int)length + 1);
UInt32 processed;
if (!file.Read(p, (UInt32)length, processed))
return false;
p[(UInt32)length] = 0;
s.ReleaseBuffer();
file.Close();
UString u;
#ifdef CP_UTF8
if (codePage == CP_UTF8)
{
if (!ConvertUTF8ToUnicode(s, u))
return false;
}
else
#endif
u = MultiByteToUnicodeString(s, codePage);
if (!u.IsEmpty())
{
if (u[0] == 0xFEFF)
u.Delete(0);
}
UString t;
for (int i = 0; i < u.Length(); i++)
{
wchar_t c = u[i];
if (c == L'\n' || c == 0xD)
{
t.Trim();
RemoveQuote(t);
if (!t.IsEmpty())
resultStrings.Add(t);
t.Empty();
}
else
t += c;
}
t.Trim();
RemoveQuote(t);
if (!t.IsEmpty())
resultStrings.Add(t);
return true;
}
|
#include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_BaseKvmCPU[] = {
120,156,189,85,219,110,219,70,16,29,82,23,219,242,69,142,
154,164,151,39,54,1,2,186,136,164,38,133,31,130,4,77,
107,195,105,140,86,138,65,57,65,171,23,130,94,142,68,198,
36,151,225,46,85,171,232,91,250,101,253,162,254,65,59,179,
20,107,215,232,75,30,28,82,59,218,153,93,238,156,115,118,
184,20,176,186,26,212,190,115,0,212,152,58,33,253,44,72,
0,78,87,61,171,234,217,144,216,144,218,48,181,193,98,191,
1,73,3,210,6,76,27,228,55,1,109,152,89,16,182,224,
15,128,247,0,191,76,155,16,182,97,226,174,209,146,241,223,
116,185,22,245,52,155,175,170,46,143,28,4,10,15,79,94,
87,129,22,153,31,23,233,155,145,238,172,134,200,163,81,113,
21,231,1,227,252,147,58,8,48,181,24,45,1,34,152,4,
3,155,48,109,1,182,25,43,163,160,224,154,113,27,181,187,
110,220,102,237,110,24,183,85,187,29,227,182,107,119,19,112,
11,222,110,3,238,192,219,46,132,107,240,158,200,239,154,224,
45,192,30,132,235,38,242,201,149,200,134,137,220,54,145,59,
16,118,32,220,52,145,187,38,242,41,132,91,16,110,155,200,
103,224,77,220,29,162,225,49,41,213,37,35,242,114,120,190,
72,135,103,68,124,16,69,194,166,88,221,14,153,53,79,255,
221,98,178,4,143,247,96,226,242,216,88,125,65,246,126,156,
137,164,12,209,185,119,109,157,123,46,75,103,102,106,206,37,
18,165,155,252,47,67,172,134,216,168,99,50,195,52,211,195,
104,62,83,195,73,20,20,56,137,48,27,206,49,221,239,203,
34,158,199,89,95,233,224,44,193,254,227,175,31,237,247,159,
244,191,25,170,66,12,235,108,151,219,53,200,151,154,17,225,
69,46,11,237,167,168,35,25,250,226,226,194,207,11,12,145,
242,63,226,132,12,8,236,15,96,121,155,108,199,49,215,66,
198,161,19,150,105,238,238,61,237,92,242,243,152,151,215,170,
57,221,4,177,157,235,196,212,62,39,105,26,50,13,91,112,
33,215,205,208,225,17,226,178,34,161,111,145,13,180,76,99,
225,103,50,19,129,136,226,108,94,161,181,106,6,55,6,126,
147,86,75,49,149,197,210,79,105,247,159,94,217,134,255,197,
173,89,124,142,140,47,95,208,23,65,162,240,35,96,101,161,
11,124,87,198,5,250,44,19,170,231,31,10,151,99,167,69,
249,49,208,242,182,170,50,55,117,161,131,115,244,229,2,139,
195,75,192,234,62,159,109,111,70,14,253,220,120,128,131,135,
142,226,148,161,83,237,135,19,202,52,136,179,61,245,37,205,
123,173,208,17,50,72,80,9,154,48,26,29,191,114,220,163,
159,79,142,188,227,209,209,248,244,251,159,246,212,112,53,43,
199,98,230,224,2,51,237,112,194,89,34,127,165,39,203,76,
99,161,174,61,99,212,120,252,195,203,223,204,123,244,82,42,
237,136,68,138,115,103,198,42,99,38,150,243,234,144,253,235,
185,234,177,170,75,145,160,163,4,193,112,102,129,208,178,112,
63,103,81,215,201,248,126,22,164,232,251,230,156,246,185,150,
202,132,93,179,9,203,28,77,156,95,248,8,131,16,11,111,
171,126,48,56,83,186,160,197,76,37,138,36,80,170,122,137,
188,54,239,16,127,16,188,13,54,60,236,109,215,37,119,18,
20,65,234,153,3,172,93,185,68,216,156,101,65,182,52,51,
206,205,87,131,211,31,72,153,120,156,94,239,146,41,233,235,
82,11,201,58,234,110,21,60,33,173,94,173,4,51,11,28,
178,20,6,98,68,202,188,32,73,170,98,79,100,160,13,27,
19,174,100,248,183,134,110,160,144,204,215,224,33,47,203,39,
104,219,50,183,221,109,118,219,212,232,190,99,245,172,158,221,
179,198,46,195,211,44,86,186,63,200,89,32,101,224,179,87,
200,139,165,103,106,222,28,138,141,255,224,189,137,234,231,196,
207,170,42,248,246,1,47,207,129,142,213,177,119,173,93,251,
31,226,199,220,33,
};
EmbeddedPython embedded_m5_objects_BaseKvmCPU(
"m5/objects/BaseKvmCPU.py",
"/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/src/cpu/kvm/BaseKvmCPU.py",
"m5.objects.BaseKvmCPU",
data_m5_objects_BaseKvmCPU,
901,
2150);
} // anonymous namespace
|
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "Core/Rtt_Build.h"
#include "Rtt_AndroidStore.h"
#include "Rtt_LuaContext.h"
#include "NativeToJavaBridge.h"
// ----------------------------------------------------------------------------
namespace Rtt
{
// ----------------------------------------------------------------------------
/// Creates a new store accessing object for Android.
/// @param handle The Lua state wrapper needed to create objects in the runtime and raise event in Lua.
AndroidStore::AndroidStore( const ResourceHandle<lua_State>& handle, NativeToJavaBridge *ntjb )
: PlatformStore( handle ), fNativeToJavaBridge(ntjb)
{
}
/// Destructor. Cleans up allocated resources.
AndroidStore::~AndroidStore()
{
}
/// Sets the type of store to be used such as Google Marketplace, Amazon, etc.
/// @param storeName The unique name of the store to be used such as "google".
/// Set to NULL or empty string to have Corona attempt to select a default store.
void AndroidStore::UseStore( const char *storeName )
{
fNativeToJavaBridge->StoreInit(storeName);
}
/// Enables store transaction events to be sent to the Lua listener.
void AndroidStore::StartObservingTransactions()
{
}
/// Disables store transaction events from being sent to the Lua listener.
void AndroidStore::StopObservingTransactions()
{
}
/// Fetches all purchased products from the store.
/// Note: This is not currently supported on Android.
void AndroidStore::LoadProducts( lua_State *L, int index )
{
}
/// Sends a purchase request to the store.
/// @param L The Lua state providing a table or array of unique product names to be purchased. Cannot be NULL.
/// @param index Index to the Lua state where parameters were provided in the store.purchase() function in Lua.
void AndroidStore::Purchase( lua_State *L, int index )
{
// Validate.
if (!L || (index < 0))
{
return;
}
// Make sure that the given Lua state contains an array of products.
if (!lua_istable(L, index))
{
return;
}
// Send a purchase request for every product in the Lua array.
int productCount = lua_objlen(L, index);
for (int productIndex = 0; productIndex < productCount; productIndex++)
{
lua_rawgeti( L, index, productIndex + 1);
if (lua_istable(L, -1))
{
// We've received a table for the product. Fetch the table's product ID.
lua_getfield(L, -1, "productIdentifier");
const char *productName = lua_tostring(L, -1);
if (productName)
{
fNativeToJavaBridge->StorePurchase(productName);
}
lua_pop( L, 1 );
}
else if (lua_isstring(L, -1))
{
// We've received a product ID string.
const char *productName = lua_tostring(L, -1);
if (productName)
{
fNativeToJavaBridge->StorePurchase(productName);
}
}
lua_pop(L, 1);
}
}
/// Determines if the currently selected store can make purchases and the current user is authorized to make purchases.
/// Note: This is currenty locked to true until we can find a nice way to retrieve this value.
/// @return Returns true if store.purchase() requests are allowed. Returns false if not.
bool AndroidStore::CanMakePurchases() const
{
return true;
}
/// Determines if the currently selected store can load previously purchased products.
/// Note: This is currenty locked to false since Google does not support this.
/// Will remain this way until we have an Android in-app purchasing system that supports it.
/// @return Returns true if store.loadProducts() will work with the currently selected store.
/// Returns false if that function will do nothing.
bool AndroidStore::CanLoadProducts() const
{
return false;
}
/// Sends a confirmation to the store to finish a purchase or restore transaction.
/// @param transaction Pointer to the transaction object to be confirmed. Cannot be NULL.
void AndroidStore::FinishTransaction( PlatformStoreTransaction *transaction )
{
// Validate argument.
if (!transaction)
{
return;
}
// Get the transaction's string ID and validate it.
const char *transactionStringId = transaction->GetIdentifier();
if (!transactionStringId || (strlen(transactionStringId) <= 0)) {
return;
}
// Send the "finish transaction" request.
fNativeToJavaBridge->StoreFinishTransaction(transactionStringId);
}
/// Sends a "restore" request to the store for fetching all previously purchased products.
void AndroidStore::RestoreCompletedTransactions()
{
fNativeToJavaBridge->StoreRestoreCompletedTransactions();
}
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
|
#include "phigraph_init.h"
PhiGraphInit::PhiGraphInit(int argc, char *argv[]){
cmd = new command(argc, argv, " [-s] <inFile>");
csrFile = cmd->getArgument(1);
cscFile = cmd->getOptionValue("-c");
bool weighted = cmd->getOption("-w");
printInfor(0);
graphIO = new PhiGraphIO(weighted);
graph = graphIO->loadGraphFromFile(csrFile,cscFile);
printInfor(1);
delete cmd;
}
Graph<Vertex>& PhiGraphInit::getGraph(){
return *graph;
}
void PhiGraphInit::printInfor(int id){
if(id == 0){
printf("system is initing\n");
}else if(id == 1){
printf("Load graph successfully\n");
printf("vertex num:[%ld];edges num:[%ld] \n",graph->vertexNum,graph->edgeNum );
}
}
PhiGraphInit::~PhiGraphInit(){
delete graphIO;
}
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/protocol/PublicKey.h>
#include <ripple/protocol/digest.h>
#include <ripple/protocol/impl/secp256k1.h>
#include <ripple/basics/contract.h>
#include <ripple/basics/strHex.h>
#include <boost/multiprecision/cpp_int.hpp>
#include <type_traits>
namespace ripple {
std::ostream&
operator<<(std::ostream& os, PublicKey const& pk)
{
os << strHex(pk);
return os;
}
template<>
boost::optional<PublicKey>
parseBase58 (TokenType type, std::string const& s)
{
auto const result = decodeBase58Token(s, type);
auto const pks = makeSlice(result);
if (!isPublicKey(pks))
return boost::none;
return PublicKey(pks);
}
//------------------------------------------------------------------------------
// Parse a length-prefixed number
// Format: 0x02 <length-byte> <number>
static
boost::optional<Slice>
sigPart (Slice& buf)
{
if (buf.size() < 3 || buf[0] != 0x02)
return boost::none;
auto const len = buf[1];
buf += 2;
if (len > buf.size() || len < 1 || len > 33)
return boost::none;
// Can't be negative
if ((buf[0] & 0x80) != 0)
return boost::none;
if (buf[0] == 0)
{
// Can't be zero
if (len == 1)
return boost::none;
// Can't be padded
if ((buf[1] & 0x80) == 0)
return boost::none;
}
boost::optional<Slice> number = Slice(buf.data(), len);
buf += len;
return number;
}
static
std::string
sliceToHex (Slice const& slice)
{
std::string s;
if (slice[0] & 0x80)
{
s.reserve(2 * (slice.size() + 2));
s = "0x00";
}
else
{
s.reserve(2 * (slice.size() + 1));
s = "0x";
}
for(int i = 0; i < slice.size(); ++i)
{
s += "0123456789ABCDEF"[((slice[i]&0xf0)>>4)];
s += "0123456789ABCDEF"[((slice[i]&0x0f)>>0)];
}
return s;
}
/** Determine whether a signature is canonical.
Canonical signatures are important to protect against signature morphing
attacks.
@param vSig the signature data
@param sigLen the length of the signature
@param strict_param whether to enforce strictly canonical semantics
@note For more details please see:
https://ripple.com/wiki/Transaction_Malleability
https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
https://github.com/sipa/bitcoin/commit/58bc86e37fda1aec270bccb3df6c20fbd2a6591c
*/
boost::optional<ECDSACanonicality>
ecdsaCanonicality (Slice const& sig)
{
using uint264 = boost::multiprecision::number<
boost::multiprecision::cpp_int_backend<
264, 264, boost::multiprecision::signed_magnitude,
boost::multiprecision::unchecked, void>>;
static uint264 const G(
"0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
// The format of a signature should be:
// <30> <len> [ <02> <lenR> <R> ] [ <02> <lenS> <S> ]
if ((sig.size() < 8) || (sig.size() > 72))
return boost::none;
if ((sig[0] != 0x30) || (sig[1] != (sig.size() - 2)))
return boost::none;
Slice p = sig + 2;
auto r = sigPart(p);
auto s = sigPart(p);
if (! r || ! s || ! p.empty())
return boost::none;
uint264 R(sliceToHex(*r));
if (R >= G)
return boost::none;
uint264 S(sliceToHex(*s));
if (S >= G)
return boost::none;
// (R,S) and (R,G-S) are canonical,
// but is fully canonical when S <= G-S
auto const Sp = G - S;
if (S > Sp)
return ECDSACanonicality::canonical;
return ECDSACanonicality::fullyCanonical;
}
//------------------------------------------------------------------------------
PublicKey::PublicKey (Slice const& slice)
{
if(! isPublicKey(slice))
LogicError("PublicKey::PublicKey invalid type");
size_ = slice.size();
std::memcpy(buf_, slice.data(), size_);
}
PublicKey::PublicKey (PublicKey const& other)
: size_ (other.size_)
{
std::memcpy(buf_, other.buf_, size_);
};
PublicKey&
PublicKey::operator=(PublicKey const& other)
{
size_ = other.size_;
std::memcpy(buf_, other.buf_, size_);
return *this;
}
//------------------------------------------------------------------------------
bool
verifyDigest (PublicKey const& publicKey,
uint256 const& digest,
Slice const& sig,
bool mustBeFullyCanonical)
{
if (!isPublicKey(publicKey))
LogicError("sign: secp256k1 required for digest signing");
auto const canonicality = ecdsaCanonicality(sig);
if (! canonicality)
return false;
if (mustBeFullyCanonical &&
(*canonicality != ECDSACanonicality::fullyCanonical))
return false;
secp256k1_pubkey pubkey_imp;
if(secp256k1_ec_pubkey_parse(
secp256k1Context(),
&pubkey_imp,
reinterpret_cast<unsigned char const*>(
publicKey.data()),
publicKey.size()) != 1)
return false;
secp256k1_ecdsa_signature sig_imp;
if(secp256k1_ecdsa_signature_parse_der(
secp256k1Context(),
&sig_imp,
reinterpret_cast<unsigned char const*>(
sig.data()),
sig.size()) != 1)
return false;
if (*canonicality != ECDSACanonicality::fullyCanonical)
{
secp256k1_ecdsa_signature sig_norm;
if(secp256k1_ecdsa_signature_normalize(
secp256k1Context(),
&sig_norm,
&sig_imp) != 1)
return false;
return secp256k1_ecdsa_verify(
secp256k1Context(),
&sig_norm,
reinterpret_cast<unsigned char const*>(
digest.data()),
&pubkey_imp) == 1;
}
return secp256k1_ecdsa_verify(
secp256k1Context(),
&sig_imp,
reinterpret_cast<unsigned char const*>(
digest.data()),
&pubkey_imp) == 1;
}
bool
verify (PublicKey const& publicKey,
Slice const& m,
Slice const& sig,
bool mustBeFullyCanonical)
{
if (isPublicKey(publicKey))
{
return verifyDigest (publicKey,
sha512Half(m), sig, mustBeFullyCanonical);
}
return false;
}
NodeID
calcNodeID (PublicKey const& pk)
{
ripesha_hasher h;
h(pk.data(), pk.size());
auto const digest = static_cast<
ripesha_hasher::result_type>(h);
static_assert(NodeID::bytes ==
sizeof(ripesha_hasher::result_type), "");
NodeID result;
std::memcpy(result.data(),
digest.data(), digest.size());
return result;
}
} // ripple
|
/*****************************************************************************
TestDiodeClipDAngelo.cpp
Author: Laurent de Soras, 2020
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/Approx.h"
#include "fstb/fnc.h"
#include "fstb/SingleObj.h"
#include "hiir/PolyphaseIir2Designer.h"
#include "mfx/dsp/iir/Downsampler4xSimd.h"
#include "mfx/dsp/iir/Upsampler4xSimd.h"
#include "mfx/dsp/osc/SweepingSin.h"
#include "mfx/dsp/va/DiodeClipDAngelo.h"
#include "mfx/FileOpWav.h"
#include "test/TestDiodeClipDAngelo.h"
#include "test/TimerAccurate.h"
#include <cassert>
#include <cmath>
#include <cstdio>
// 1 or 4
#define TestDiodeClipDAngelo_OVRSPL (4)
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
int TestDiodeClipDAngelo::perform_test ()
{
int ret_val = 0;
printf ("Testing dsp::va::DiodeClipDAngelo...\n");
const double sample_freq = 44100;
const int ssin_len = fstb::round_int (sample_freq * 10);
std::vector <float> src (ssin_len);
// Sweeping sine
mfx::dsp::osc::SweepingSin ssin (sample_freq, 20.0, 20000.0);
ssin.generate (src.data (), ssin_len);
// Sawtooth
const int saw_len = fstb::round_int (sample_freq * 1);
for (int o = -3; o < 7; ++o)
{
const double freq = 220 * pow (2.0, o + 3 / 12.0);
gen_saw (src, sample_freq, freq, saw_len);
}
const int len = int (src.size ());
std::vector <float> dst (len);
const int nbr_coef_42 = 4;
const int nbr_coef_21 = 8;
struct UpDown
{
mfx::dsp::iir::Upsampler4xSimd <nbr_coef_42, nbr_coef_21> _up;
mfx::dsp::iir::Downsampler4xSimd <nbr_coef_42, nbr_coef_21> _dw;
};
fstb::SingleObj <UpDown> updw;
double coef_42 [nbr_coef_42];
double coef_21 [nbr_coef_21];
// Rejection : 103.4 dB
// Bandwidth : 20.0 kHz @ 44.1 kHz
// Total group delay: 5.0 spl @ 1 kHz
hiir::PolyphaseIir2Designer::compute_coefs_spec_order_tbw (
&coef_42 [0], nbr_coef_42, 0.216404
);
hiir::PolyphaseIir2Designer::compute_coefs_spec_order_tbw (
&coef_21 [0], nbr_coef_21, 0.0455352
);
updw->_up.set_coefs (coef_42, coef_21);
updw->_dw.set_coefs (coef_42, coef_21);
mfx::dsp::va::DiodeClipDAngelo dclip;
dclip.set_sample_freq (sample_freq * TestDiodeClipDAngelo_OVRSPL);
float gain = 1;
for (int pos = 0; pos < len; ++pos)
{
float x = src [pos] * gain;
#if (TestDiodeClipDAngelo_OVRSPL == 1) // W/o oversampling
x = dclip.process_sample (x);
#else // With oversampling
float tmp [TestDiodeClipDAngelo_OVRSPL];
updw->_up.process_sample (tmp, x);
for (int k = 0; k < TestDiodeClipDAngelo_OVRSPL; ++k)
{
tmp [k] = dclip.process_sample (tmp [k]);
}
x = updw->_dw.process_sample (tmp);
#endif
dst [pos] = x;
}
mfx::FileOpWav::save ("results/dclipdangelo1.wav", dst, sample_freq, 0.5f);
// Now with variable gain with fixed GBP (gain-bandwidth product)
const double per_spl = 2 * sample_freq;
for (int pos = 0; pos < len; ++pos)
{
double a = fmod (pos / per_spl, 1.0);
a = 1 - fabs (a * 2 - 1);
gain = fstb::Approx::exp2 (float (a * a) * 8 - 1);
dclip.set_capa (gain * 10e-9f);
float x = src [pos] * gain;
#if (TestDiodeClipDAngelo_OVRSPL == 1) // W/o oversampling
x = dclip.process_sample (x);
#else // With oversampling
float tmp [TestDiodeClipDAngelo_OVRSPL];
updw->_up.process_sample (tmp, x);
for (int k = 0; k < TestDiodeClipDAngelo_OVRSPL; ++k)
{
tmp [k] = dclip.process_sample (tmp [k]);
}
x = updw->_dw.process_sample (tmp);
#endif
dst [pos] = x;
}
mfx::FileOpWav::save ("results/dclipdangelo2.wav", dst, sample_freq, 0.5f);
// Speed test
TimerAccurate chrono;
dclip.set_capa (10e-9f);
const int nbr_passes = 10;
for (int g = 1; g <= 100; g *= 100)
{
float acc_dummy = 0;
chrono.reset ();
chrono.start ();
for (int pass_cnt = 0; pass_cnt < nbr_passes; ++pass_cnt)
{
for (int pos = 0; pos < len; ++pos)
{
acc_dummy += dclip.process_sample (src [pos] * g);
}
}
chrono.stop ();
double spl_per_s = chrono.get_best_rate (len * nbr_passes);
spl_per_s += fstb::limit (acc_dummy, -1e-30f, 1e-30f); // Anti-optimizer trick
const double mega_sps = spl_per_s / 1000000.0;
printf ("Speed (gain = %4d):%9.3f Mspl/s\n", g, mega_sps);
}
return ret_val;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
void TestDiodeClipDAngelo::gen_saw (std::vector <float> &data, double sample_freq, double freq, int len)
{
const int per = fstb::round_int (sample_freq / freq);
for (int pos = 0; pos < len; ++pos)
{
const float val = (pos % per) * (2.f / per) - 1.f;
data.push_back (val);
}
}
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2017-2019 The Raven Core developers
// Copyright (c) 2020-2021 The Hive Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "addrman.h"
#include "fs.h"
#include "hash.h"
#include "protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdint.h>
#ifndef WIN32
#include <sys/stat.h>
#endif
#include <boost/thread.hpp>
namespace {
//! Make sure database has a unique fileid within the environment. If it
//! doesn't, throw an error. BDB caches do not work properly when more than one
//! open database has the same fileid (values written to one database may show
//! up in reads to other databases).
//!
//! BerkeleyDB generates unique fileids by default
//! (https://docs.oracle.com/cd/E17275_01/html/programmer_reference/program_copy.html),
//! so hive should never create different databases with the same fileid, but
//! this error can be triggered if users manually copy database files.
void CheckUniqueFileid(const CDBEnv& env, const std::string& filename, Db& db)
{
if (env.IsMock()) return;
u_int8_t fileid[DB_FILE_ID_LEN];
int ret = db.get_mpf()->get_fileid(fileid);
if (ret != 0) {
throw std::runtime_error(strprintf("CDB: Can't open database %s (get_fileid failed with %d)", filename, ret));
}
for (const auto& item : env.mapDb) {
u_int8_t item_fileid[DB_FILE_ID_LEN];
if (item.second && item.second->get_mpf()->get_fileid(item_fileid) == 0 &&
memcmp(fileid, item_fileid, sizeof(fileid)) == 0) {
const char* item_filename = nullptr;
item.second->get_dbname(&item_filename, nullptr);
throw std::runtime_error(strprintf("CDB: Can't open database %s (duplicates fileid %s from %s)", filename,
HexStr(std::begin(item_fileid), std::end(item_fileid)),
item_filename ? item_filename : "(unknown database)"));
}
}
}
} // namespace
//
// CDB
//
CDBEnv bitdb;
void CDBEnv::EnvShutdown()
{
if (!fDbEnvInit)
return;
fDbEnvInit = false;
int ret = dbenv->close(0);
if (ret != 0)
LogPrintf("CDBEnv::EnvShutdown: Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret));
if (!fMockDb)
DbEnv((u_int32_t)0).remove(strPath.c_str(), 0);
}
void CDBEnv::Reset()
{
delete dbenv;
dbenv = new DbEnv(DB_CXX_NO_EXCEPTIONS);
fDbEnvInit = false;
fMockDb = false;
}
CDBEnv::CDBEnv() : dbenv(nullptr)
{
Reset();
}
CDBEnv::~CDBEnv()
{
EnvShutdown();
delete dbenv;
dbenv = nullptr;
}
void CDBEnv::Close()
{
EnvShutdown();
}
bool CDBEnv::Open(const fs::path& pathIn)
{
if (fDbEnvInit)
return true;
boost::this_thread::interruption_point();
strPath = pathIn.string();
fs::path pathLogDir = pathIn / "database";
TryCreateDirectories(pathLogDir);
fs::path pathErrorFile = pathIn / "db.log";
LogPrintf("CDBEnv::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (gArgs.GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB))
nEnvFlags |= DB_PRIVATE;
dbenv->set_lg_dir(pathLogDir.string().c_str());
dbenv->set_cachesize(0, 0x100000, 1); // 1 MiB should be enough for just the wallet
dbenv->set_lg_bsize(0x10000);
dbenv->set_lg_max(1048576);
dbenv->set_lk_max_locks(40000);
dbenv->set_lk_max_objects(40000);
dbenv->set_errfile(fsbridge::fopen(pathErrorFile, "a")); /// debug
dbenv->set_flags(DB_AUTO_COMMIT, 1);
dbenv->set_flags(DB_TXN_WRITE_NOSYNC, 1);
dbenv->log_set_config(DB_LOG_AUTO_REMOVE, 1);
int ret = dbenv->open(strPath.c_str(),
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_RECOVER |
nEnvFlags,
S_IRUSR | S_IWUSR);
if (ret != 0) {
dbenv->close(0);
return error("CDBEnv::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret));
}
fDbEnvInit = true;
fMockDb = false;
return true;
}
void CDBEnv::MakeMock()
{
if (fDbEnvInit)
throw std::runtime_error("CDBEnv::MakeMock: Already initialized");
boost::this_thread::interruption_point();
LogPrint(BCLog::DB, "CDBEnv::MakeMock\n");
dbenv->set_cachesize(1, 0, 1);
dbenv->set_lg_bsize(10485760 * 4);
dbenv->set_lg_max(10485760);
dbenv->set_lk_max_locks(10000);
dbenv->set_lk_max_objects(10000);
dbenv->set_flags(DB_AUTO_COMMIT, 1);
dbenv->log_set_config(DB_LOG_IN_MEMORY, 1);
int ret = dbenv->open(nullptr,
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_PRIVATE,
S_IRUSR | S_IWUSR);
if (ret > 0)
throw std::runtime_error(strprintf("CDBEnv::MakeMock: Error %d opening database environment.", ret));
fDbEnvInit = true;
fMockDb = true;
}
CDBEnv::VerifyResult CDBEnv::Verify(const std::string& strFile, recoverFunc_type recoverFunc, std::string& out_backup_filename)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
Db db(dbenv, 0);
int result = db.verify(strFile.c_str(), nullptr, nullptr, 0);
if (result == 0)
return VERIFY_OK;
else if (recoverFunc == nullptr)
return RECOVER_FAIL;
// Try to recover:
bool fRecovered = (*recoverFunc)(strFile, out_backup_filename);
return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
}
bool CDB::Recover(const std::string& filename, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename)
{
// Recovery procedure:
// move wallet file to walletfilename.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to fresh wallet file
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
newFilename = strprintf("%s.%d.bak", filename, now);
int result = bitdb.dbenv->dbrename(nullptr, filename.c_str(), nullptr,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool fSuccess = bitdb.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
std::unique_ptr<Db> pdbCopy(new Db(bitdb.dbenv, 0));
int ret = pdbCopy->open(nullptr, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("Cannot create database file %s\n", filename);
pdbCopy->close(0);
return false;
}
DbTxn* ptxn = bitdb.TxnBegin();
for (CDBEnv::KeyValPair& row : salvagedData)
{
if (recoverKVcallback)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
if (!(*recoverKVcallback)(callbackDataIn, ssKey, ssValue))
continue;
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
return fSuccess;
}
bool CDB::VerifyEnvironment(const std::string& walletFile, const fs::path& dataDir, std::string& errorStr)
{
LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
LogPrintf("Using wallet %s\n", walletFile);
// Wallet file must be a plain filename without a directory
if (walletFile != fs::basename(walletFile) + fs::extension(walletFile))
{
errorStr = strprintf(_("Wallet %s resides outside data directory %s"), walletFile, dataDir.string());
return false;
}
if (!bitdb.Open(dataDir))
{
// try moving the database env out of the way
fs::path pathDatabase = dataDir / "database";
fs::path pathDatabaseBak = dataDir / strprintf("database.%d.bak", GetTime());
try {
fs::rename(pathDatabase, pathDatabaseBak);
LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
} catch (const fs::filesystem_error&) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(dataDir)) {
// if it still fails, it probably means we can't even create the database env
errorStr = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
return false;
}
}
return true;
}
bool CDB::VerifyDatabaseFile(const std::string& walletFile, const fs::path& dataDir, std::string& warningStr, std::string& errorStr, CDBEnv::recoverFunc_type recoverFunc)
{
if (fs::exists(dataDir / walletFile))
{
std::string backup_filename;
CDBEnv::VerifyResult r = bitdb.Verify(walletFile, recoverFunc, backup_filename);
if (r == CDBEnv::RECOVER_OK)
{
warningStr = strprintf(_("Warning: Wallet file corrupt, data salvaged!"
" Original %s saved as %s in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."),
walletFile, backup_filename, dataDir);
}
if (r == CDBEnv::RECOVER_FAIL)
{
errorStr = strprintf(_("%s corrupt, salvage failed"), walletFile);
return false;
}
}
// also return true if files does not exists
return true;
}
/* End of headers, beginning of key/value data */
static const char *HEADER_END = "HEADER=END";
/* End of key/value data */
static const char *DATA_END = "DATA=END";
bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<CDBEnv::KeyValPair>& vResult)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
u_int32_t flags = DB_SALVAGE;
if (fAggressive)
flags |= DB_AGGRESSIVE;
std::stringstream strDump;
Db db(dbenv, 0);
int result = db.verify(strFile.c_str(), nullptr, &strDump, flags);
if (result == DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage: Database salvage found errors, all data may not be recoverable.\n");
if (!fAggressive) {
LogPrintf("CDBEnv::Salvage: Rerun with aggressive mode to ignore errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage: Database salvage failed with result %d.\n", result);
return false;
}
// Format of bdb dump is ascii lines:
// header lines...
// HEADER=END
// hexadecimal key
// hexadecimal value
// ... repeated
// DATA=END
std::string strLine;
while (!strDump.eof() && strLine != HEADER_END)
getline(strDump, strLine); // Skip past header
std::string keyHex, valueHex;
while (!strDump.eof() && keyHex != DATA_END) {
getline(strDump, keyHex);
if (keyHex != DATA_END) {
if (strDump.eof())
break;
getline(strDump, valueHex);
if (valueHex == DATA_END) {
LogPrintf("CDBEnv::Salvage: WARNING: Number of keys in data does not match number of values.\n");
break;
}
vResult.push_back(make_pair(ParseHex(keyHex), ParseHex(valueHex)));
}
}
if (keyHex != DATA_END) {
LogPrintf("CDBEnv::Salvage: WARNING: Unexpected end of file while reading salvage output.\n");
return false;
}
return (result == 0);
}
void CDBEnv::CheckpointLSN(const std::string& strFile)
{
dbenv->txn_checkpoint(0, 0, 0);
if (fMockDb)
return;
dbenv->lsn_reset(strFile.c_str(), 0);
}
CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr)
{
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
fFlushOnClose = fFlushOnCloseIn;
env = dbw.env;
if (dbw.IsDummy()) {
return;
}
const std::string &strFilename = dbw.strFile;
bool fCreate = strchr(pszMode, 'c') != nullptr;
unsigned int nFlags = DB_THREAD;
if (fCreate)
nFlags |= DB_CREATE;
{
LOCK(env->cs_db);
if (!env->Open(GetDataDir()))
throw std::runtime_error("CDB: Failed to open database environment.");
pdb = env->mapDb[strFilename];
if (pdb == nullptr) {
int ret;
std::unique_ptr<Db> pdb_temp(new Db(env->dbenv, 0));
bool fMockDb = env->IsMock();
if (fMockDb) {
DbMpoolFile* mpf = pdb_temp->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0) {
throw std::runtime_error(strprintf("CDB: Failed to configure for no temp file backing for database %s", strFilename));
}
}
ret = pdb_temp->open(nullptr, // Txn pointer
fMockDb ? nullptr : strFilename.c_str(), // Filename
fMockDb ? strFilename.c_str() : "main", // Logical db name
DB_BTREE, // Database type
nFlags, // Flags
0);
if (ret != 0) {
throw std::runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename));
}
CheckUniqueFileid(*env, strFilename, *pdb_temp);
pdb = pdb_temp.release();
env->mapDb[strFilename] = pdb;
if (fCreate && !Exists(std::string("version"))) {
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(CLIENT_VERSION);
fReadOnly = fTmp;
}
}
++env->mapFileUseCount[strFilename];
strFile = strFilename;
}
}
void CDB::Flush()
{
if (activeTxn)
return;
// Flush database activity from memory pool to disk log
unsigned int nMinutes = 0;
if (fReadOnly)
nMinutes = 1;
env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
}
void CWalletDBWrapper::IncrementUpdateCounter()
{
++nUpdateCounter;
}
void CDB::Close()
{
if (!pdb)
return;
if (activeTxn)
activeTxn->abort();
activeTxn = nullptr;
pdb = nullptr;
if (fFlushOnClose)
Flush();
{
LOCK(env->cs_db);
--env->mapFileUseCount[strFile];
}
}
void CDBEnv::CloseDb(const std::string& strFile)
{
{
LOCK(cs_db);
if (mapDb[strFile] != nullptr) {
// Close the database handle
Db* pdb = mapDb[strFile];
pdb->close(0);
delete pdb;
mapDb[strFile] = nullptr;
}
}
}
bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
{
if (dbw.IsDummy()) {
return true;
}
CDBEnv *env = dbw.env;
const std::string& strFile = dbw.strFile;
while (true) {
{
LOCK(env->cs_db);
if (!env->mapFileUseCount.count(strFile) || env->mapFileUseCount[strFile] == 0) {
// Flush log data to the dat file
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(strFile);
bool fSuccess = true;
LogPrintf("CDB::Rewrite: Rewriting %s...\n", strFile);
std::string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
CDB db(dbw, "r");
Db* pdbCopy = new Db(env->dbenv, 0);
int ret = pdbCopy->open(nullptr, // Txn pointer
strFileRes.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("CDB::Rewrite: Can't create database file %s\n", strFileRes);
fSuccess = false;
}
Dbc* pcursor = db.GetCursor();
if (pcursor)
while (fSuccess) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret1 = db.ReadAtCursor(pcursor, ssKey, ssValue);
if (ret1 == DB_NOTFOUND) {
pcursor->close();
break;
} else if (ret1 != 0) {
pcursor->close();
fSuccess = false;
break;
}
if (pszSkip &&
strncmp(ssKey.data(), pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
continue;
if (strncmp(ssKey.data(), "\x07version", 8) == 0) {
// Update version:
ssValue.clear();
ssValue << CLIENT_VERSION;
}
Dbt datKey(ssKey.data(), ssKey.size());
Dbt datValue(ssValue.data(), ssValue.size());
int ret2 = pdbCopy->put(nullptr, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
if (fSuccess) {
db.Close();
env->CloseDb(strFile);
if (pdbCopy->close(0))
fSuccess = false;
} else {
pdbCopy->close(0);
}
delete pdbCopy;
}
if (fSuccess) {
Db dbA(env->dbenv, 0);
if (dbA.remove(strFile.c_str(), nullptr, 0))
fSuccess = false;
Db dbB(env->dbenv, 0);
if (dbB.rename(strFileRes.c_str(), nullptr, strFile.c_str(), 0))
fSuccess = false;
}
if (!fSuccess)
LogPrintf("CDB::Rewrite: Failed to rewrite database file %s\n", strFileRes);
return fSuccess;
}
}
MilliSleep(100);
}
}
void CDBEnv::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
// Flush log data to the actual data file on all files that are not in use
LogPrint(BCLog::DB, "CDBEnv::Flush: Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started");
if (!fDbEnvInit)
return;
{
LOCK(cs_db);
std::map<std::string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end()) {
std::string strFile = (*mi).first;
int nRefCount = (*mi).second;
LogPrint(BCLog::DB, "CDBEnv::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount);
if (nRefCount == 0) {
// Move log data to the dat file
CloseDb(strFile);
LogPrint(BCLog::DB, "CDBEnv::Flush: %s checkpoint\n", strFile);
dbenv->txn_checkpoint(0, 0, 0);
LogPrint(BCLog::DB, "CDBEnv::Flush: %s detach\n", strFile);
if (!fMockDb)
dbenv->lsn_reset(strFile.c_str(), 0);
LogPrint(BCLog::DB, "CDBEnv::Flush: %s closed\n", strFile);
mapFileUseCount.erase(mi++);
} else
mi++;
}
LogPrint(BCLog::DB, "CDBEnv::Flush: Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart);
if (fShutdown) {
char** listp;
if (mapFileUseCount.empty()) {
dbenv->log_archive(&listp, DB_ARCH_REMOVE);
Close();
if (!fMockDb)
fs::remove_all(fs::path(strPath) / "database");
}
}
}
}
bool CDB::PeriodicFlush(CWalletDBWrapper& dbw)
{
if (dbw.IsDummy()) {
return true;
}
bool ret = false;
CDBEnv *env = dbw.env;
const std::string& strFile = dbw.strFile;
TRY_LOCK(bitdb.cs_db,lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
std::map<std::string, int>::iterator mit = env->mapFileUseCount.begin();
while (mit != env->mapFileUseCount.end())
{
nRefCount += (*mit).second;
mit++;
}
if (nRefCount == 0)
{
boost::this_thread::interruption_point();
std::map<std::string, int>::iterator mi = env->mapFileUseCount.find(strFile);
if (mi != env->mapFileUseCount.end())
{
LogPrint(BCLog::DB, "Flushing %s\n", strFile);
int64_t nStart = GetTimeMillis();
// Flush wallet file so it's self contained
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(mi++);
LogPrint(BCLog::DB, "Flushed %s %dms\n", strFile, GetTimeMillis() - nStart);
ret = true;
}
}
}
return ret;
}
bool CWalletDBWrapper::Rewrite(const char* pszSkip)
{
return CDB::Rewrite(*this, pszSkip);
}
bool CWalletDBWrapper::Backup(const std::string& strDest)
{
if (IsDummy()) {
return false;
}
while (true)
{
{
LOCK(env->cs_db);
if (!env->mapFileUseCount.count(strFile) || env->mapFileUseCount[strFile] == 0)
{
// Flush log data to the dat file
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(strFile);
// Copy wallet file
fs::path pathSrc = GetDataDir() / strFile;
fs::path pathDest(strDest);
if (fs::is_directory(pathDest))
pathDest /= strFile;
try {
fs::copy_file(pathSrc, pathDest, fs::copy_option::overwrite_if_exists);
LogPrintf("copied %s to %s\n", strFile, pathDest.string());
return true;
} catch (const fs::filesystem_error& e) {
LogPrintf("error copying %s to %s - %s\n", strFile, pathDest.string(), e.what());
return false;
}
}
}
MilliSleep(100);
}
}
void CWalletDBWrapper::Flush(bool shutdown)
{
if (!IsDummy()) {
env->Flush(shutdown);
}
}
|
#include "pch.h"
#include "GraphicsCommon.h"
#include "SamplerManager.h"
#include "CommandSignature.h"
namespace Graphics
{
SamplerDesc SamplerLinearWrapDesc;
SamplerDesc SamplerAnisoWrapDesc;
SamplerDesc SamplerShadowDesc;
SamplerDesc SamplerLinearClampDesc;
SamplerDesc SamplerVolumeWrapDesc;
SamplerDesc SamplerPointClampDesc;
SamplerDesc SamplerPointBorderDesc;
SamplerDesc SamplerLinearBorderDesc;
D3D12_CPU_DESCRIPTOR_HANDLE SamplerLinearWrap;
D3D12_CPU_DESCRIPTOR_HANDLE SamplerAnisoWrap;
D3D12_CPU_DESCRIPTOR_HANDLE SamplerShadow;
D3D12_CPU_DESCRIPTOR_HANDLE SamplerLinearClamp;
D3D12_CPU_DESCRIPTOR_HANDLE SamplerVolumeWrap;
D3D12_CPU_DESCRIPTOR_HANDLE SamplerPointClamp;
D3D12_CPU_DESCRIPTOR_HANDLE SamplerPointBorder;
D3D12_CPU_DESCRIPTOR_HANDLE SamplerLinearBorder;
D3D12_RASTERIZER_DESC RasterizerDefault; // Counter-clockwise
D3D12_RASTERIZER_DESC RasterizerDefaultMsaa;
D3D12_RASTERIZER_DESC RasterizerDefaultCw; // Clockwise winding
D3D12_RASTERIZER_DESC RasterizerDefaultCwMsaa;
D3D12_RASTERIZER_DESC RasterizerTwoSided;
D3D12_RASTERIZER_DESC RasterizerTwoSidedMsaa;
D3D12_RASTERIZER_DESC RasterizerShadow;
D3D12_RASTERIZER_DESC RasterizerShadowCW;
D3D12_RASTERIZER_DESC RasterizerShadowTwoSided;
D3D12_BLEND_DESC BlendNoColorWrite;
D3D12_BLEND_DESC BlendDisable;
D3D12_BLEND_DESC BlendPreMultiplied;
D3D12_BLEND_DESC BlendTraditional;
D3D12_BLEND_DESC BlendAdditive;
D3D12_BLEND_DESC BlendTraditionalAdditive;
D3D12_DEPTH_STENCIL_DESC DepthStateDisabled;
D3D12_DEPTH_STENCIL_DESC DepthStateReadWrite;
D3D12_DEPTH_STENCIL_DESC DepthStateReadOnly;
D3D12_DEPTH_STENCIL_DESC DepthStateReadOnlyReversed;
D3D12_DEPTH_STENCIL_DESC DepthStateTestEqual;
CommandSignature DispatchIndirectCommandSignature(1);
CommandSignature DrawIndirectCommandSignature(1);
GraphicsPSO GraphicsPSODefault;
}
void Graphics::InitializeCommonState(void)
{
SamplerLinearWrapDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
SamplerLinearWrap = SamplerLinearWrapDesc.CreateDescriptor();
SamplerAnisoWrapDesc.MaxAnisotropy = 4;
SamplerAnisoWrap = SamplerAnisoWrapDesc.CreateDescriptor();
SamplerShadowDesc.Filter = D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
SamplerShadowDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL;
SamplerShadowDesc.SetTextureAddressMode(D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
SamplerShadow = SamplerShadowDesc.CreateDescriptor();
SamplerLinearClampDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
SamplerLinearClampDesc.SetTextureAddressMode(D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
SamplerLinearClamp = SamplerLinearClampDesc.CreateDescriptor();
SamplerVolumeWrapDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
SamplerVolumeWrap = SamplerVolumeWrapDesc.CreateDescriptor();
SamplerPointClampDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
SamplerPointClampDesc.SetTextureAddressMode(D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
SamplerPointClamp = SamplerPointClampDesc.CreateDescriptor();
SamplerLinearBorderDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
SamplerLinearBorderDesc.SetTextureAddressMode(D3D12_TEXTURE_ADDRESS_MODE_BORDER);
SamplerLinearBorderDesc.SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
SamplerLinearBorder = SamplerLinearBorderDesc.CreateDescriptor();
SamplerPointBorderDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
SamplerPointBorderDesc.SetTextureAddressMode(D3D12_TEXTURE_ADDRESS_MODE_BORDER);
SamplerPointBorderDesc.SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
SamplerPointBorder = SamplerPointBorderDesc.CreateDescriptor();
// Default rasterizer states
RasterizerDefault.FillMode = D3D12_FILL_MODE_SOLID;
RasterizerDefault.CullMode = D3D12_CULL_MODE_BACK;
RasterizerDefault.FrontCounterClockwise = TRUE;
RasterizerDefault.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
RasterizerDefault.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
RasterizerDefault.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
RasterizerDefault.DepthClipEnable = TRUE;
RasterizerDefault.MultisampleEnable = FALSE;
RasterizerDefault.AntialiasedLineEnable = FALSE;
RasterizerDefault.ForcedSampleCount = 0;
RasterizerDefault.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
RasterizerDefaultMsaa = RasterizerDefault;
RasterizerDefaultMsaa.MultisampleEnable = TRUE;
RasterizerDefaultCw = RasterizerDefault;
RasterizerDefaultCw.FrontCounterClockwise = FALSE;
RasterizerDefaultCwMsaa = RasterizerDefaultCw;
RasterizerDefaultCwMsaa.MultisampleEnable = TRUE;
RasterizerTwoSided = RasterizerDefault;
RasterizerTwoSided.CullMode = D3D12_CULL_MODE_NONE;
RasterizerTwoSidedMsaa = RasterizerTwoSided;
RasterizerTwoSidedMsaa.MultisampleEnable = TRUE;
// Shadows need their own rasterizer state so we can reverse the winding of faces
RasterizerShadow = RasterizerDefault;
//RasterizerShadow.CullMode = D3D12_CULL_FRONT; // Hacked here rather than fixing the content
RasterizerShadow.SlopeScaledDepthBias = -1.5f;
RasterizerShadow.DepthBias = -100;
RasterizerShadowTwoSided = RasterizerShadow;
RasterizerShadowTwoSided.CullMode = D3D12_CULL_MODE_NONE;
RasterizerShadowCW = RasterizerShadow;
RasterizerShadowCW.FrontCounterClockwise = FALSE;
DepthStateDisabled.DepthEnable = FALSE;
DepthStateDisabled.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
DepthStateDisabled.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
DepthStateDisabled.StencilEnable = FALSE;
DepthStateDisabled.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK;
DepthStateDisabled.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK;
DepthStateDisabled.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
DepthStateDisabled.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
DepthStateDisabled.FrontFace.StencilFailOp = D3D12_STENCIL_OP_KEEP;
DepthStateDisabled.FrontFace.StencilDepthFailOp = D3D12_STENCIL_OP_KEEP;
DepthStateDisabled.BackFace = DepthStateDisabled.FrontFace;
DepthStateReadWrite = DepthStateDisabled;
DepthStateReadWrite.DepthEnable = TRUE;
DepthStateReadWrite.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
DepthStateReadWrite.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
DepthStateReadOnly = DepthStateReadWrite;
DepthStateReadOnly.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
DepthStateReadOnlyReversed = DepthStateReadOnly;
DepthStateReadOnlyReversed.DepthFunc = D3D12_COMPARISON_FUNC_GREATER;
DepthStateTestEqual = DepthStateReadOnly;
DepthStateTestEqual.DepthFunc = D3D12_COMPARISON_FUNC_EQUAL;
D3D12_BLEND_DESC alphaBlend = {};
alphaBlend.IndependentBlendEnable = FALSE;
alphaBlend.RenderTarget[0].BlendEnable = FALSE;
alphaBlend.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
alphaBlend.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
alphaBlend.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
alphaBlend.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
alphaBlend.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
alphaBlend.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
alphaBlend.RenderTarget[0].RenderTargetWriteMask = 0;
BlendNoColorWrite = alphaBlend;
alphaBlend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
BlendDisable = alphaBlend;
alphaBlend.RenderTarget[0].BlendEnable = TRUE;
BlendTraditional = alphaBlend;
alphaBlend.RenderTarget[0].SrcBlend = D3D12_BLEND_ONE;
BlendPreMultiplied = alphaBlend;
alphaBlend.RenderTarget[0].DestBlend = D3D12_BLEND_ONE;
BlendAdditive = alphaBlend;
alphaBlend.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
BlendTraditionalAdditive = alphaBlend;
DispatchIndirectCommandSignature[0].Dispatch();
DispatchIndirectCommandSignature.Finalize();
DrawIndirectCommandSignature[0].Draw();
DrawIndirectCommandSignature.Finalize();
GraphicsPSODefault.SetRasterizerState(RasterizerDefault);
GraphicsPSODefault.SetBlendState(BlendDisable);
GraphicsPSODefault.SetDepthStencilState(DepthStateDisabled);
GraphicsPSODefault.SetPrimitiveTopologyType(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
}
void Graphics::DestroyCommonState(void)
{
DispatchIndirectCommandSignature.Destroy();
DrawIndirectCommandSignature.Destroy();
}
|
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
void subsetSumHelper(vector<int> a, int i, int sum, vector<int> &out)
{
if(i == a.size())
{
out.push_back(sum);
return;
}
else
{
subsetSumHelper(a, i+1, sum, out);
subsetSumHelper(a, i+1, sum+a[i], out);
}
}
vector<int> subsetSums(vector<int> arr, int N)
{
// Write Your Code here
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
vector<int> out;
subsetSumHelper(arr, 0, 0, out);
sort(out.begin(), out.end());
return out;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int N;
cin>>N;
vector<int> arr(N);
for(int i = 0 ; i < N ; i++){
cin >> arr[i];
}
Solution ob;
vector<int> ans = ob.subsetSums(arr,N);
for(auto sum : ans){
cout<< sum<<" ";
}
cout<<endl;
}
return 0;
} // } Driver Code Ends
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "chainparams.h"
#include "clientversion.h"
#include "compat.h"
#include "fs.h"
#include "rpc/server.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "httpserver.h"
#include "httprpc.h"
#include "utilstrencodings.h"
#include <boost/thread.hpp>
#include <stdio.h>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https://www.bitcoin.org/),
* which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
void WaitForShutdown(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown)
{
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup)
{
Interrupt(*threadGroup);
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
CScheduler scheduler;
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version"))
{
std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";
if (IsArgSet("-version"))
{
strUsage += FormatParagraph(LicenseInfo());
}
else
{
strUsage += "\n" + _("Usage:") + "\n" +
" bitcoind [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
return true;
}
try
{
if (!fs::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return false;
}
try
{
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return false;
}
// Error out when loose non-argument tokens are encountered on command line
for (int i = 1; i < argc; i++) {
if (!IsSwitchChar(argv[i][0])) {
fprintf(stderr, "Error: Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i]);
exit(EXIT_FAILURE);
}
}
// -server defaults to true for bitcoind but not for the GUI so do this here
SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console
InitLogging();
InitParameterInteraction();
if (!AppInitBasicSetup())
{
// InitError will have been called with detailed error, which ends up on console
exit(EXIT_FAILURE);
}
if (!AppInitParameterInteraction())
{
// InitError will have been called with detailed error, which ends up on console
exit(EXIT_FAILURE);
}
if (!AppInitSanityChecks())
{
// InitError will have been called with detailed error, which ends up on console
exit(EXIT_FAILURE);
}
if (GetBoolArg("-daemon", false))
{
#if HAVE_DECL_DAEMON
fprintf(stdout, "Bitcoin server starting\n");
// Daemonize
if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno));
return false;
}
#else
fprintf(stderr, "Error: -daemon is not supported on this operating system\n");
return false;
#endif // HAVE_DECL_DAEMON
}
// Lock data directory after daemonization
if (!AppInitLockDataDirectory())
{
// If locking the data directory failed, exit immediately
exit(EXIT_FAILURE);
}
fRet = AppInitMain(threadGroup, scheduler);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet)
{
Interrupt(threadGroup);
threadGroup.join_all();
} else {
WaitForShutdown(&threadGroup);
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect bitcoind signal handlers
noui_connect();
return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
}
|
// Copyright (c) 2012 The Chromium Embedded Framework 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 "libcef/browser/zip_reader_impl.h"
#include <time.h>
#include "base/logging.h"
#include "base/notreached.h"
#include "include/cef_stream.h"
// Static functions
// static
CefRefPtr<CefZipReader> CefZipReader::Create(
CefRefPtr<CefStreamReader> stream) {
CefRefPtr<CefZipReaderImpl> impl(new CefZipReaderImpl());
if (!impl->Initialize(stream))
return nullptr;
return impl.get();
}
// CefZipReaderImpl
namespace {
voidpf ZCALLBACK zlib_open_callback OF((voidpf opaque,
const void* filename,
int mode)) {
// The stream is already implicitly open so just return the pointer.
return opaque;
}
uLong ZCALLBACK zlib_read_callback
OF((voidpf opaque, voidpf stream, void* buf, uLong size)) {
CefRefPtr<CefStreamReader> reader(static_cast<CefStreamReader*>(opaque));
return reader->Read(buf, 1, size);
}
ZPOS64_T ZCALLBACK zlib_tell_callback OF((voidpf opaque, voidpf stream)) {
CefRefPtr<CefStreamReader> reader(static_cast<CefStreamReader*>(opaque));
return reader->Tell();
}
long ZCALLBACK zlib_seek_callback
OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)) {
CefRefPtr<CefStreamReader> reader(static_cast<CefStreamReader*>(opaque));
int whence;
switch (origin) {
case ZLIB_FILEFUNC_SEEK_CUR:
whence = SEEK_CUR;
break;
case ZLIB_FILEFUNC_SEEK_END:
whence = SEEK_END;
break;
case ZLIB_FILEFUNC_SEEK_SET:
whence = SEEK_SET;
break;
default:
NOTREACHED();
return -1;
}
return reader->Seek(offset, whence);
}
int ZCALLBACK zlib_close_callback OF((voidpf opaque, voidpf stream)) {
CefRefPtr<CefStreamReader> reader(static_cast<CefStreamReader*>(opaque));
// Release the reference added by CefZipReaderImpl::Initialize().
reader->Release();
return 0;
}
int ZCALLBACK zlib_error_callback OF((voidpf opaque, voidpf stream)) {
return 0;
}
} // namespace
CefZipReaderImpl::CefZipReaderImpl()
: supported_thread_id_(base::PlatformThread::CurrentId()),
reader_(nullptr),
has_fileopen_(false),
has_fileinfo_(false),
filesize_(0),
filemodified_(0) {}
CefZipReaderImpl::~CefZipReaderImpl() {
if (reader_ != nullptr) {
if (!VerifyContext()) {
// Close() is supposed to be called directly. We'll try to free the reader
// now on the wrong thread but there's no guarantee this call won't crash.
if (has_fileopen_)
unzCloseCurrentFile(reader_);
unzClose(reader_);
} else {
Close();
}
}
}
bool CefZipReaderImpl::Initialize(CefRefPtr<CefStreamReader> stream) {
zlib_filefunc64_def filefunc_def;
filefunc_def.zopen64_file = zlib_open_callback;
filefunc_def.zread_file = zlib_read_callback;
filefunc_def.zwrite_file = nullptr;
filefunc_def.ztell64_file = zlib_tell_callback;
filefunc_def.zseek64_file = zlib_seek_callback;
filefunc_def.zclose_file = zlib_close_callback;
filefunc_def.zerror_file = zlib_error_callback;
filefunc_def.opaque = stream.get();
// Add a reference that will be released by zlib_close_callback().
stream->AddRef();
reader_ = unzOpen2_64("", &filefunc_def);
return (reader_ != nullptr);
}
bool CefZipReaderImpl::MoveToFirstFile() {
if (!VerifyContext())
return false;
if (has_fileopen_)
CloseFile();
has_fileinfo_ = false;
return (unzGoToFirstFile(reader_) == UNZ_OK);
}
bool CefZipReaderImpl::MoveToNextFile() {
if (!VerifyContext())
return false;
if (has_fileopen_)
CloseFile();
has_fileinfo_ = false;
return (unzGoToNextFile(reader_) == UNZ_OK);
}
bool CefZipReaderImpl::MoveToFile(const CefString& fileName,
bool caseSensitive) {
if (!VerifyContext())
return false;
if (has_fileopen_)
CloseFile();
has_fileinfo_ = false;
std::string fileNameStr = fileName;
return (unzLocateFile(reader_, fileNameStr.c_str(),
(caseSensitive ? 1 : 2)) == UNZ_OK);
}
bool CefZipReaderImpl::Close() {
if (!VerifyContext())
return false;
if (has_fileopen_)
CloseFile();
int result = unzClose(reader_);
reader_ = nullptr;
return (result == UNZ_OK);
}
CefString CefZipReaderImpl::GetFileName() {
if (!VerifyContext() || !GetFileInfo())
return CefString();
return filename_;
}
int64 CefZipReaderImpl::GetFileSize() {
if (!VerifyContext() || !GetFileInfo())
return -1;
return filesize_;
}
CefTime CefZipReaderImpl::GetFileLastModified() {
CefTime time;
if (!VerifyContext() || !GetFileInfo())
return time;
cef_time_from_timet(filemodified_, &time);
return time;
}
bool CefZipReaderImpl::OpenFile(const CefString& password) {
if (!VerifyContext())
return false;
if (has_fileopen_)
CloseFile();
bool ret;
if (password.empty()) {
ret = (unzOpenCurrentFile(reader_) == UNZ_OK);
} else {
std::string passwordStr = password;
ret = (unzOpenCurrentFilePassword(reader_, passwordStr.c_str()) == UNZ_OK);
}
if (ret)
has_fileopen_ = true;
return ret;
}
bool CefZipReaderImpl::CloseFile() {
if (!VerifyContext() || !has_fileopen_)
return false;
has_fileopen_ = false;
has_fileinfo_ = false;
return (unzCloseCurrentFile(reader_) == UNZ_OK);
}
int CefZipReaderImpl::ReadFile(void* buffer, size_t bufferSize) {
if (!VerifyContext() || !has_fileopen_)
return -1;
return unzReadCurrentFile(reader_, buffer, bufferSize);
}
int64 CefZipReaderImpl::Tell() {
if (!VerifyContext() || !has_fileopen_)
return -1;
return unztell64(reader_);
}
bool CefZipReaderImpl::Eof() {
if (!VerifyContext() || !has_fileopen_)
return true;
return (unzeof(reader_) == 1 ? true : false);
}
bool CefZipReaderImpl::GetFileInfo() {
if (has_fileinfo_)
return true;
char file_name[512] = {0};
unz_file_info file_info;
memset(&file_info, 0, sizeof(file_info));
if (unzGetCurrentFileInfo(reader_, &file_info, file_name, sizeof(file_name),
NULL, 0, NULL, 0) != UNZ_OK) {
return false;
}
has_fileinfo_ = true;
filename_ = std::string(file_name);
filesize_ = file_info.uncompressed_size;
struct tm time;
memset(&time, 0, sizeof(time));
time.tm_sec = file_info.tmu_date.tm_sec;
time.tm_min = file_info.tmu_date.tm_min;
time.tm_hour = file_info.tmu_date.tm_hour;
time.tm_mday = file_info.tmu_date.tm_mday;
time.tm_mon = file_info.tmu_date.tm_mon;
time.tm_year = file_info.tmu_date.tm_year - 1900; // Years since 1900.
filemodified_ = mktime(&time);
DCHECK_NE(filemodified_, (time_t)-1);
return true;
}
bool CefZipReaderImpl::VerifyContext() {
if (base::PlatformThread::CurrentId() != supported_thread_id_) {
// This object should only be accessed from the thread that created it.
NOTREACHED();
return false;
}
return (reader_ != nullptr);
}
|
/*=============================================================================
Copyright (c) 2001-2010 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <boost/config/warning_disable.hpp>
#include <input/sexpr.hpp>
#include <input/parse_sexpr_impl.hpp>
#include <utree/io.hpp>
#include <iostream>
#include <fstream>
inline std::ostream& println(std::ostream& out, scheme::utree const& val)
{
out << val << std::endl;
return out;
}
void test(std::string const& in, std::string const& file)
{
scheme::utree result;
if (scheme::input::parse_sexpr(in, result, file))
{
std::cout << "success: ";
println(std::cout, result);
std::cout << std::endl;
}
else
{
std::cout << "parse error" << std::endl;
}
}
///////////////////////////////////////////////////////////////////////////////
// Main program
///////////////////////////////////////////////////////////////////////////////
int main()
{
test("(abc def)", "ok.sexpr");
test("(abc (123 456) def)", "ok.sexpr");
test("(abc \n(\"a string\" 456) \ndef)", "ok.sexpr");
test("(abc \n(\"a string\" 456 \ndef)", "missing close paren.sexpr");
test("(abc \n(\"a string 456) \ndef)", "missing double quote.sexpr");
test("(abc \n(\"a string\" 0xggg) \ndef)", "erronoeus hex.sexpr");
test("(abc \n(\"a \\zstring\" 999) \ndef)", "erronoeus escape.sexpr");
test("(abc \n(\"a \\uzstring\" 999) \ndef)", "erronoeus escape.sexpr");
return 0;
}
|
#ifndef BOOST_METAPARSE_IS_ERROR_HPP
#define BOOST_METAPARSE_IS_ERROR_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/metaparse/v1/is_error.hpp>
namespace boost
{
namespace metaparse
{
using v1::is_error;
}
}
#endif
|
// Copyright 2017 PDFium 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 "core/fpdfapi/edit/cpdf_pagecontentgenerator.h"
#include <memory>
#include <utility>
#include "core/fpdfapi/cpdf_modulemgr.h"
#include "core/fpdfapi/font/cpdf_font.h"
#include "core/fpdfapi/page/cpdf_form.h"
#include "core/fpdfapi/page/cpdf_page.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
#include "core/fpdfapi/parser/cpdf_name.h"
#include "core/fpdfapi/parser/cpdf_parser.h"
#include "core/fpdfapi/parser/cpdf_reference.h"
#include "core/fpdfapi/parser/cpdf_stream.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/base/ptr_util.h"
class CPDF_PageContentGeneratorTest : public testing::Test {
protected:
void SetUp() override { CPDF_ModuleMgr::Get()->Init(); }
void TearDown() override {
CPDF_ModuleMgr::Destroy();
}
void TestProcessPath(CPDF_PageContentGenerator* pGen,
std::ostringstream* buf,
CPDF_PathObject* pPathObj) {
pGen->ProcessPath(buf, pPathObj);
}
CPDF_Dictionary* TestGetResource(CPDF_PageContentGenerator* pGen,
const ByteString& type,
const ByteString& name) {
return pGen->m_pObjHolder->m_pResources->GetDictFor(type)->GetDictFor(name);
}
void TestProcessText(CPDF_PageContentGenerator* pGen,
std::ostringstream* buf,
CPDF_TextObject* pTextObj) {
pGen->ProcessText(buf, pTextObj);
}
};
TEST_F(CPDF_PageContentGeneratorTest, ProcessRect) {
auto pPathObj = pdfium::MakeUnique<CPDF_PathObject>();
pPathObj->set_stroke(true);
pPathObj->set_filltype(FXFILL_ALTERNATE);
pPathObj->path().AppendRect(10, 5, 13, 30);
CPDF_Dictionary dummy_page_dict;
auto pTestPage =
pdfium::MakeRetain<CPDF_Page>(nullptr, &dummy_page_dict, false);
CPDF_PageContentGenerator generator(pTestPage.Get());
std::ostringstream buf;
TestProcessPath(&generator, &buf, pPathObj.get());
EXPECT_EQ("q 1 0 0 1 0 0 cm 10 5 3 25 re B* Q\n", ByteString(buf));
pPathObj = pdfium::MakeUnique<CPDF_PathObject>();
pPathObj->path().AppendPoint(CFX_PointF(0, 0), FXPT_TYPE::MoveTo, false);
pPathObj->path().AppendPoint(CFX_PointF(5.2f, 0), FXPT_TYPE::LineTo, false);
pPathObj->path().AppendPoint(CFX_PointF(5.2f, 3.78f), FXPT_TYPE::LineTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(0, 3.78f), FXPT_TYPE::LineTo, true);
buf.str("");
TestProcessPath(&generator, &buf, pPathObj.get());
EXPECT_EQ("q 1 0 0 1 0 0 cm 0 0 5.1999998 3.78 re n Q\n", ByteString(buf));
}
TEST_F(CPDF_PageContentGeneratorTest, BUG_937) {
static const std::vector<float> rgb = {0.000000000000000000001f, 0.7f, 0.35f};
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB);
{
auto pPathObj = pdfium::MakeUnique<CPDF_PathObject>();
pPathObj->set_filltype(FXFILL_WINDING);
// Test code in ProcessPath that generates re operator
pPathObj->path().AppendRect(0.000000000000000000001,
0.000000000000000000001, 100, 100);
pPathObj->m_ColorState.SetFillColor(pCS, rgb);
pPathObj->m_ColorState.SetStrokeColor(pCS, rgb);
pPathObj->m_GraphState.SetLineWidth(200000000000000000001.0);
pPathObj->Transform(CFX_Matrix(1, 0, 0, 1, 0.000000000000000000001,
200000000000000.000002));
CPDF_Dictionary dummy_page_dict;
auto pTestPage =
pdfium::MakeRetain<CPDF_Page>(nullptr, &dummy_page_dict, false);
CPDF_PageContentGenerator generator(pTestPage.Get());
std::ostringstream buf;
TestProcessPath(&generator, &buf, pPathObj.get());
EXPECT_EQ(
"q 0 0.701961 0.34902 rg 0 0.701961 0.34902 RG 200000000000000000000 w"
" 1 0 0 1 .00000000000000000000099999997 200000000000000 cm .000000000"
"00000000000099999997 .00000000000000000000099999997 100 100 re f Q\n",
ByteString(buf));
}
{
// Test code in ProcessPath that handles bezier operator
auto pPathObj = pdfium::MakeUnique<CPDF_PathObject>();
pPathObj->m_ColorState.SetFillColor(pCS, rgb);
pPathObj->m_ColorState.SetStrokeColor(pCS, rgb);
pPathObj->m_GraphState.SetLineWidth(2.000000000000000000001);
pPathObj->Transform(CFX_Matrix(1, 0, 0, 1, 432, 500000000000000.000002));
pPathObj->set_filltype(FXFILL_WINDING);
pPathObj->path().AppendPoint(CFX_PointF(0.000000000000000000001f, 4.67f),
FXPT_TYPE::MoveTo, false);
pPathObj->path().AppendPoint(
CFX_PointF(0.000000000000000000001, 100000000000000.000002),
FXPT_TYPE::LineTo, false);
pPathObj->path().AppendPoint(CFX_PointF(0.0000000000001f, 3.15f),
FXPT_TYPE::BezierTo, false);
pPathObj->path().AppendPoint(CFX_PointF(3.57f, 2.98f), FXPT_TYPE::BezierTo,
false);
pPathObj->path().AppendPoint(
CFX_PointF(53.4f, 5000000000000000000.00000000000000004),
FXPT_TYPE::BezierTo, true);
CPDF_Dictionary dummy_page_dict;
auto pTestPage =
pdfium::MakeRetain<CPDF_Page>(nullptr, &dummy_page_dict, false);
CPDF_PageContentGenerator generator(pTestPage.Get());
std::ostringstream buf;
TestProcessPath(&generator, &buf, pPathObj.get());
EXPECT_EQ(
"q 0 0.701961 0.34902 rg 0 0.701961 0.34902 RG 2 w 1 0 0 1 432 4999999"
"90000000 cm .00000000000000000000099999997 4.6700001 m .0000000000000"
"0000000099999997 100000000000000 l .000000000000099999998 3.1500001 3"
".5699999 2.98 53.400002 5000000000000000000 c h f Q\n",
ByteString(buf));
}
}
TEST_F(CPDF_PageContentGeneratorTest, ProcessPath) {
auto pPathObj = pdfium::MakeUnique<CPDF_PathObject>();
pPathObj->set_filltype(FXFILL_WINDING);
pPathObj->path().AppendPoint(CFX_PointF(3.102f, 4.67f), FXPT_TYPE::MoveTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(5.45f, 0.29f), FXPT_TYPE::LineTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(4.24f, 3.15f), FXPT_TYPE::BezierTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(4.65f, 2.98f), FXPT_TYPE::BezierTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(3.456f, 0.24f), FXPT_TYPE::BezierTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(10.6f, 11.15f), FXPT_TYPE::LineTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(11, 12.5f), FXPT_TYPE::LineTo, false);
pPathObj->path().AppendPoint(CFX_PointF(11.46f, 12.67f), FXPT_TYPE::BezierTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(11.84f, 12.96f), FXPT_TYPE::BezierTo,
false);
pPathObj->path().AppendPoint(CFX_PointF(12, 13.64f), FXPT_TYPE::BezierTo,
true);
CPDF_Dictionary dummy_page_dict;
auto pTestPage =
pdfium::MakeRetain<CPDF_Page>(nullptr, &dummy_page_dict, false);
CPDF_PageContentGenerator generator(pTestPage.Get());
std::ostringstream buf;
TestProcessPath(&generator, &buf, pPathObj.get());
EXPECT_EQ(
"q 1 0 0 1 0 0 cm 3.102 4.6700001 m 5.4499998 .28999999 l 4.2399998 "
"3.1500001 4.6500001 2.98 3.4560001 .23999999 c 10.6000004 11.149999"
"6 l 11 12.5 l 11.46 12.6700001 11.8400002 12.96 12 13.6400003 c h f"
" Q\n",
ByteString(buf));
}
TEST_F(CPDF_PageContentGeneratorTest, ProcessGraphics) {
auto pPathObj = pdfium::MakeUnique<CPDF_PathObject>();
pPathObj->set_stroke(true);
pPathObj->set_filltype(FXFILL_WINDING);
pPathObj->path().AppendPoint(CFX_PointF(1, 2), FXPT_TYPE::MoveTo, false);
pPathObj->path().AppendPoint(CFX_PointF(3, 4), FXPT_TYPE::LineTo, false);
pPathObj->path().AppendPoint(CFX_PointF(5, 6), FXPT_TYPE::LineTo, true);
static const std::vector<float> rgb = {0.5f, 0.7f, 0.35f};
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB);
pPathObj->m_ColorState.SetFillColor(pCS, rgb);
static const std::vector<float> rgb2 = {1, 0.9f, 0};
pPathObj->m_ColorState.SetStrokeColor(pCS, rgb2);
pPathObj->m_GeneralState.SetFillAlpha(0.5f);
pPathObj->m_GeneralState.SetStrokeAlpha(0.8f);
auto pDoc = pdfium::MakeUnique<CPDF_Document>();
pDoc->CreateNewDoc();
CPDF_Dictionary* pPageDict = pDoc->CreateNewPage(0);
auto pTestPage = pdfium::MakeRetain<CPDF_Page>(pDoc.get(), pPageDict, false);
CPDF_PageContentGenerator generator(pTestPage.Get());
std::ostringstream buf;
TestProcessPath(&generator, &buf, pPathObj.get());
ByteString pathString(buf);
// Color RGB values used are integers divided by 255.
EXPECT_EQ("q 0.501961 0.701961 0.34902 rg 1 0.901961 0 RG /",
pathString.Left(48));
EXPECT_EQ(" gs 1 0 0 1 0 0 cm 1 2 m 3 4 l 5 6 l h B Q\n",
pathString.Right(43));
ASSERT_GT(pathString.GetLength(), 91U);
CPDF_Dictionary* externalGS = TestGetResource(
&generator, "ExtGState", pathString.Mid(48, pathString.GetLength() - 91));
ASSERT_TRUE(externalGS);
EXPECT_EQ(0.5f, externalGS->GetNumberFor("ca"));
EXPECT_EQ(0.8f, externalGS->GetNumberFor("CA"));
// Same path, now with a stroke.
pPathObj->m_GraphState.SetLineWidth(10.5f);
buf.str("");
TestProcessPath(&generator, &buf, pPathObj.get());
ByteString pathString2(buf);
EXPECT_EQ("q 0.501961 0.701961 0.34902 rg 1 0.901961 0 RG 10.5 w /",
pathString2.Left(55));
EXPECT_EQ(" gs 1 0 0 1 0 0 cm 1 2 m 3 4 l 5 6 l h B Q\n",
pathString2.Right(43));
// Compare with the previous (should use same dictionary for gs)
EXPECT_EQ(pathString.GetLength() + 7, pathString2.GetLength());
EXPECT_EQ(pathString.Mid(48, pathString.GetLength() - 76),
pathString2.Mid(55, pathString2.GetLength() - 83));
}
TEST_F(CPDF_PageContentGeneratorTest, ProcessStandardText) {
// Checking font whose font dictionary is not yet indirect object.
auto pDoc = pdfium::MakeUnique<CPDF_Document>();
pDoc->CreateNewDoc();
CPDF_Dictionary* pPageDict = pDoc->CreateNewPage(0);
auto pTestPage = pdfium::MakeRetain<CPDF_Page>(pDoc.get(), pPageDict, false);
CPDF_PageContentGenerator generator(pTestPage.Get());
auto pTextObj = pdfium::MakeUnique<CPDF_TextObject>();
CPDF_Font* pFont = CPDF_Font::GetStockFont(pDoc.get(), "Times-Roman");
pTextObj->m_TextState.SetFont(pFont);
pTextObj->m_TextState.SetFontSize(10.0f);
static const std::vector<float> rgb = {0.5f, 0.7f, 0.35f};
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB);
pTextObj->m_ColorState.SetFillColor(pCS, rgb);
static const std::vector<float> rgb2 = {1, 0.9f, 0};
pTextObj->m_ColorState.SetStrokeColor(pCS, rgb2);
pTextObj->m_GeneralState.SetFillAlpha(0.5f);
pTextObj->m_GeneralState.SetStrokeAlpha(0.8f);
pTextObj->Transform(CFX_Matrix(1, 0, 0, 1, 100, 100));
pTextObj->SetText("Hello World");
std::ostringstream buf;
TestProcessText(&generator, &buf, pTextObj.get());
ByteString textString(buf);
auto firstResourceAt = textString.Find('/');
ASSERT_TRUE(firstResourceAt.has_value());
firstResourceAt = firstResourceAt.value() + 1;
auto secondResourceAt = textString.ReverseFind('/');
ASSERT_TRUE(secondResourceAt.has_value());
secondResourceAt = secondResourceAt.value() + 1;
ByteString firstString = textString.Left(firstResourceAt.value());
ByteString midString =
textString.Mid(firstResourceAt.value(),
secondResourceAt.value() - firstResourceAt.value());
ByteString lastString =
textString.Right(textString.GetLength() - secondResourceAt.value());
// q and Q must be outside the BT .. ET operations
ByteString compareString1 =
"q 0.501961 0.701961 0.34902 rg 1 0.901961 0 RG /";
// Color RGB values used are integers divided by 255.
ByteString compareString2 = " gs BT 1 0 0 1 100 100 Tm /";
ByteString compareString3 = " 10 Tf <48656C6C6F20576F726C64> Tj ET Q\n";
EXPECT_LT(compareString1.GetLength() + compareString2.GetLength() +
compareString3.GetLength(),
textString.GetLength());
EXPECT_EQ(compareString1, firstString.Left(compareString1.GetLength()));
EXPECT_EQ(compareString2, midString.Right(compareString2.GetLength()));
EXPECT_EQ(compareString3, lastString.Right(compareString3.GetLength()));
CPDF_Dictionary* externalGS = TestGetResource(
&generator, "ExtGState",
midString.Left(midString.GetLength() - compareString2.GetLength()));
ASSERT_TRUE(externalGS);
EXPECT_EQ(0.5f, externalGS->GetNumberFor("ca"));
EXPECT_EQ(0.8f, externalGS->GetNumberFor("CA"));
CPDF_Dictionary* fontDict = TestGetResource(
&generator, "Font",
lastString.Left(lastString.GetLength() - compareString3.GetLength()));
ASSERT_TRUE(fontDict);
EXPECT_EQ("Font", fontDict->GetStringFor("Type"));
EXPECT_EQ("Type1", fontDict->GetStringFor("Subtype"));
EXPECT_EQ("Times-Roman", fontDict->GetStringFor("BaseFont"));
}
TEST_F(CPDF_PageContentGeneratorTest, ProcessText) {
// Checking font whose font dictionary is already an indirect object.
auto pDoc = pdfium::MakeUnique<CPDF_Document>();
pDoc->CreateNewDoc();
CPDF_Dictionary* pPageDict = pDoc->CreateNewPage(0);
auto pTestPage = pdfium::MakeRetain<CPDF_Page>(pDoc.get(), pPageDict, false);
CPDF_PageContentGenerator generator(pTestPage.Get());
std::ostringstream buf;
{
// Set the text object font and text
auto pTextObj = pdfium::MakeUnique<CPDF_TextObject>();
CPDF_Dictionary* pDict = pDoc->NewIndirect<CPDF_Dictionary>();
pDict->SetNewFor<CPDF_Name>("Type", "Font");
pDict->SetNewFor<CPDF_Name>("Subtype", "TrueType");
CPDF_Font* pFont = CPDF_Font::GetStockFont(pDoc.get(), "Arial");
pDict->SetNewFor<CPDF_Name>("BaseFont", pFont->GetBaseFont());
CPDF_Dictionary* pDesc = pDoc->NewIndirect<CPDF_Dictionary>();
pDesc->SetNewFor<CPDF_Name>("Type", "FontDescriptor");
pDesc->SetNewFor<CPDF_Name>("FontName", pFont->GetBaseFont());
pDict->SetFor("FontDescriptor", pDesc->MakeReference(pDoc.get()));
CPDF_Font* loadedFont = pDoc->LoadFont(pDict);
pTextObj->m_TextState.SetFont(loadedFont);
pTextObj->m_TextState.SetFontSize(15.5f);
pTextObj->SetText("I am indirect");
TestProcessText(&generator, &buf, pTextObj.get());
}
ByteString textString(buf);
auto firstResourceAt = textString.Find('/');
ASSERT_TRUE(firstResourceAt.has_value());
firstResourceAt = firstResourceAt.value() + 1;
ByteString firstString = textString.Left(firstResourceAt.value());
ByteString lastString =
textString.Right(textString.GetLength() - firstResourceAt.value());
// q and Q must be outside the BT .. ET operations
ByteString compareString1 = "q BT 1 0 0 1 0 0 Tm /";
ByteString compareString2 = " 15.5 Tf <4920616D20696E646972656374> Tj ET Q\n";
EXPECT_LT(compareString1.GetLength() + compareString2.GetLength(),
textString.GetLength());
EXPECT_EQ(compareString1, textString.Left(compareString1.GetLength()));
EXPECT_EQ(compareString2, textString.Right(compareString2.GetLength()));
CPDF_Dictionary* fontDict = TestGetResource(
&generator, "Font",
textString.Mid(compareString1.GetLength(),
textString.GetLength() - compareString1.GetLength() -
compareString2.GetLength()));
ASSERT_TRUE(fontDict);
EXPECT_TRUE(fontDict->GetObjNum());
EXPECT_EQ("Font", fontDict->GetStringFor("Type"));
EXPECT_EQ("TrueType", fontDict->GetStringFor("Subtype"));
EXPECT_EQ("Helvetica", fontDict->GetStringFor("BaseFont"));
CPDF_Dictionary* fontDesc = fontDict->GetDictFor("FontDescriptor");
ASSERT_TRUE(fontDesc);
EXPECT_TRUE(fontDesc->GetObjNum());
EXPECT_EQ("FontDescriptor", fontDesc->GetStringFor("Type"));
EXPECT_EQ("Helvetica", fontDesc->GetStringFor("FontName"));
}
TEST_F(CPDF_PageContentGeneratorTest, ProcessEmptyForm) {
auto pDoc = pdfium::MakeUnique<CPDF_Document>();
pDoc->CreateNewDoc();
auto pDict = pdfium::MakeUnique<CPDF_Dictionary>();
auto pStream = pdfium::MakeUnique<CPDF_Stream>(nullptr, 0, std::move(pDict));
// Create an empty form.
auto pTestForm =
pdfium::MakeUnique<CPDF_Form>(pDoc.get(), nullptr, pStream.get());
pTestForm->ParseContent(nullptr, nullptr, nullptr, nullptr);
ASSERT_EQ(CPDF_PageObjectHolder::ParseState::kParsed,
pTestForm->GetParseState());
// The generated stream for the empty form should be an empty string.
CPDF_PageContentGenerator generator(pTestForm.get());
std::ostringstream buf;
generator.ProcessPageObjects(&buf);
EXPECT_EQ("", ByteString(buf));
}
TEST_F(CPDF_PageContentGeneratorTest, ProcessFormWithPath) {
auto pDoc = pdfium::MakeUnique<CPDF_Document>();
pDoc->CreateNewDoc();
auto pDict = pdfium::MakeUnique<CPDF_Dictionary>();
const char content[] =
"q 1 0 0 1 0 0 cm 3.102 4.6700001 m 5.4500012 .28999999 "
"l 4.2399998 3.1499999 4.65 2.98 3.456 0.24 c 3.102 4.6700001 l h f Q\n";
size_t buf_len = FX_ArraySize(content);
std::unique_ptr<uint8_t, FxFreeDeleter> buf(FX_Alloc(uint8_t, buf_len));
memcpy(buf.get(), content, buf_len);
auto pStream = pdfium::MakeUnique<CPDF_Stream>(std::move(buf), buf_len,
std::move(pDict));
// Create a form with a non-empty stream.
auto pTestForm =
pdfium::MakeUnique<CPDF_Form>(pDoc.get(), nullptr, pStream.get());
pTestForm->ParseContent(nullptr, nullptr, nullptr, nullptr);
ASSERT_EQ(CPDF_PageObjectHolder::ParseState::kParsed,
pTestForm->GetParseState());
CPDF_PageContentGenerator generator(pTestForm.get());
std::ostringstream process_buf;
generator.ProcessPageObjects(&process_buf);
EXPECT_STREQ(
"q 1 0 0 1 0 0 cm 3.102 4.6700001 m 5.4500012 .28999999 l 4.2399998 3.14"
"99999 4.6500001 2.98 3.4560001 .24000001 c 3.102 4.6700001 l h f Q\n",
ByteString(process_buf).c_str());
}
|
#include "Kernel.h"
#include "Utils.h"
#include "Config.h"
#include "SocketHandler.h"
#include "HTTPProcessor.h"
#include "Stream.h"
#include "Main.h"
#include <csignal>
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <strstream>
#include <iterator>
#include <algorithm>
#include <stdio.h>
using namespace std;
long totalTime = 0;
bool serverRunning = true;
Kernel *kernel = NULL;
bool bootstrap = true;
bool convert = false;
bool debug = false;
bool trace = false;
int maxRecursiveDepth = 32;
string botName = "Reeve";
string connectPattern = "CONNECT";
string noMatchPattern = "NOMATCH";
string loopPattern = "LOSTINLOOP";
HttpConfig httpConfig;
void loadConfig();
void run();
void clean(string &);
void process(string &, int, string &, string &);
void signalHandler( int signum )
{
cout << "Segmentation Fault (" << signum << ") received."<<endl;
cleanup_reeve();
exit(1);
}
void reeveSIGINT( int signum )
{
cout << "Interrupt recieved."<<endl;
cleanup_reeve();
exit(1);
}
int init_reeve(int argc, char **argv)
{
cout<<"initialising Reeve"<<endl;
kernel = new Kernel();
loadConfig();
string aimlset="main";
if (argc > 0)
{
string s;
for(int i=0; i<argc; i++)
{
s = argv[i];
if(s=="-aiml")
{
aimlset=argv[++i];
i++;
}
}
}
cout<<"AIMLSET="<<aimlset.c_str()<<endl;
kernel->loadAIML(aimlset);
char str[1024];
sprintf(str, "Total time to startup: %dms\n", totalTime );
getStream("Console")->Write(str);
return 0;
}
#ifndef GUI
int main(int argc, char **argv)
{
signal(SIGSEGV, signalHandler);
signal(SIGINT, reeveSIGINT);
init_reeve(argc, argv);
run_reeve();
cleanup_reeve();
cout << "\nReeve has been shutdown" << endl;
}
#endif
void clean(string &input)
{
string::size_type ix = input.find_first_of(";\n\t\r");
if (ix == string::npos)
{
return;
}
input = input.erase(ix);
ix = input.find_last_not_of(" ");
input = input.erase(ix + 1);
}
void loadConfig()
{
ifstream fin("reeve.ini", ios::binary | ios::in);
if (!fin.is_open())
{
return;
}
string line, section, subsection, property, value;
int ircsection = -1;
while (!fin.eof())
{
getline(fin, line);
clean(line);
if (line.length() > 0)
{
if (line[0] == '[')
{
section = line.substr(1, line.length() - 2);
subsection = "";
}
else
{
string::size_type st = line.find("=");
property = line.substr(0, st);
value = line.substr(st + 1);
process(section, ircsection, property, value);
}
}
}
fin.close();
}
void process(string &s, int ss, string &p, string &v)
{
if (p == "MaxRecursiveDepth")
{
maxRecursiveDepth = atoi(v.c_str());
}
else if (p == "BootstrapEnabled")
{
bootstrap = v == "true";
}
else if (p == "BotName")
{
botName = v;
}
else if (p == "ConnectPattern")
{
connectPattern = v;
}
else if (p == "NoMatchPattern")
{
noMatchPattern = v;
}
else if (p == "LoopPattern")
{
loopPattern = v;
}
else if (p == "Enabled")
{
bool enabled = v == "true";
if (s == "Web Server")
{
httpConfig.enabled = enabled;
}
}
else if (p == "Port")
{
int port = atoi(v.c_str());
if (s == "Web Server")
{
httpConfig.port = port;
}
}
else if (p == "TemplateFile")
{
httpConfig.templateFile = v;
}
else if (p == "StartupPattern")
{
if (s == "Web Server")
{
httpConfig.startupPattern = v;
}
}
}
void run_reeve()
{
// The Web Server (if enabled) !!! CHANGE TO WEBSOCK
if (httpConfig.enabled)
{
new HTTPServer();
}
// Start the SocketHandler loop
SocketHandler::runLoop();
// Once this loop has finished, bot will shutdown
}
void cleanup_reeve()
{
serverRunning = false;
getStream("Console")->Write("Please wait while Reeve exits...");
if (kernel != NULL)
{
delete Kernel::predicates;
getStream("Console")->Write("Saved predicates");
delete kernel;
getStream("Console")->Write("Engine stopped");
kernel = NULL;
}
}
|
--- base/process/memory.cc.orig 2020-03-16 18:39:41 UTC
+++ base/process/memory.cc
@@ -42,7 +42,7 @@ void OnNoMemoryInternal(size_t size) {
} // namespace internal
// Defined in memory_win.cc for Windows.
-#if !defined(OS_WIN)
+#if !defined(OS_WIN) && !defined(OS_BSD)
namespace {
@@ -61,7 +61,7 @@ void TerminateBecauseOutOfMemory(size_t size) {
#endif // !defined(OS_WIN)
// Defined in memory_mac.mm for Mac.
-#if !defined(OS_MACOSX)
+#if !defined(OS_MACOSX) && !defined(OS_BSD)
bool UncheckedCalloc(size_t num_items, size_t size, void** result) {
const size_t alloc_size = num_items * size;
|
/*
MIT License
Copyright(c) 2019 megai2
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 "stdafx.h"
#ifdef ENABLE_METRICS
#define D912PXY_ROUTE_IMPL_START d912pxy_metrics_api_overhead_timer timer(__LINE__, __FUNCTION__);
#define D912PXY_ROUTE_IMPL_END
#define D912PXY_ROUTE_IMPL_STUB(ret) obj->com.ImplStubCall(__FUNCTION__, __LINE__); return ret
#define D912PXY_ROUTE_IMPL_STUB_(ret) obj->com.ImplStubCall(__FUNCTION__, __LINE__);
#ifndef ROUTE_COM_IUNK_DEFAULT
#define ROUTE_COM_IUNK_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_comhandler
#define D912PXY_ROUTE_IMPL_PREFIX return obj->com.
D912PXY_METHOD_IMPL(QueryInterface)(PXY_THIS_ REFIID riid, void** ppvObj)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX QueryInterface(riid, ppvObj);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(ULONG, AddRef)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX AddRef();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(ULONG, Release)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Release();
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
//device
#ifndef ROUTE_DEVICE_DEFAULT
#define ROUTE_DEVICE_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_device
#define D912PXY_ROUTE_IMPL_PREFIX return obj->device.
D912PXY_METHOD_IMPL_(ULONG, ReleaseDevice)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX ReleaseDevice();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(TestCooperativeLevel)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX TestCooperativeLevel();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(UINT, GetAvailableTextureMem)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetAvailableTextureMem();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(EvictManagedResources)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX EvictManagedResources();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDirect3D)(PXY_THIS_ IDirect3D9** ppD3D9)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDirect3D(ppD3D9);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDeviceCaps)(PXY_THIS_ D3DCAPS9* pCaps)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDeviceCaps(pCaps);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDisplayMode)(PXY_THIS_ UINT iSwapChain, D3DDISPLAYMODE* pMode)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDisplayMode(iSwapChain, pMode);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetCreationParameters)(PXY_THIS_ D3DDEVICE_CREATION_PARAMETERS *pParameters)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetCreationParameters(pParameters);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetCursorProperties)(PXY_THIS_ UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9* pCursorBitmap)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(void, SetCursorPosition)(PXY_THIS_ int X, int Y, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetCursorPosition(X, Y, Flags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(BOOL, ShowCursor)(PXY_THIS_ BOOL bShow)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX ShowCursor(bShow);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateAdditionalSwapChain)(PXY_THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain9** pSwapChain)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateAdditionalSwapChain(pPresentationParameters, pSwapChain);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetSwapChain)(PXY_THIS_ UINT iSwapChain, IDirect3DSwapChain9** pSwapChain)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetSwapChain(iSwapChain, pSwapChain);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(UINT, GetNumberOfSwapChains)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetNumberOfSwapChains();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Reset)(PXY_THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Reset(pPresentationParameters);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Present)(PXY_THIS_ CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetBackBuffer)(PXY_THIS_ UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetBackBuffer(iSwapChain, iBackBuffer, Type, ppBackBuffer);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetRasterStatus)(PXY_THIS_ UINT iSwapChain, D3DRASTER_STATUS* pRasterStatus)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetRasterStatus(iSwapChain, pRasterStatus);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetDialogBoxMode)(PXY_THIS_ BOOL bEnableDialogs)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetDialogBoxMode(bEnableDialogs);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(void, SetGammaRamp)(PXY_THIS_ UINT iSwapChain, DWORD Flags, CONST D3DGAMMARAMP* pRamp)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetGammaRamp(iSwapChain, Flags, pRamp);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(void, GetGammaRamp)(PXY_THIS_ UINT iSwapChain, D3DGAMMARAMP* pRamp)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetGammaRamp(iSwapChain, pRamp);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateTexture)(PXY_THIS_ UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9** ppTexture, HANDLE* pSharedHandle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateTexture(Width, Height, Levels, Usage, Format, Pool, ppTexture, pSharedHandle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateVolumeTexture)(PXY_THIS_ UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9** ppVolumeTexture, HANDLE* pSharedHandle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture, pSharedHandle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateCubeTexture)(PXY_THIS_ UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture9** ppCubeTexture, HANDLE* pSharedHandle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture, pSharedHandle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateVertexBuffer)(PXY_THIS_ UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer9** ppVertexBuffer, HANDLE* pSharedHandle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateVertexBuffer(Length, Usage, FVF, Pool, ppVertexBuffer, pSharedHandle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateIndexBuffer)(PXY_THIS_ UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9** ppIndexBuffer, HANDLE* pSharedHandle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, pSharedHandle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateRenderTarget)(PXY_THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateRenderTarget(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateDepthStencilSurface)(PXY_THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateDepthStencilSurface(Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(UpdateSurface)(PXY_THIS_ IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestinationSurface, CONST POINT* pDestPoint)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX UpdateSurface(pSourceSurface, pSourceRect, pDestinationSurface, pDestPoint);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(UpdateTexture)(PXY_THIS_ IDirect3DBaseTexture9* pSourceTexture, IDirect3DBaseTexture9* pDestinationTexture)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX UpdateTexture(pSourceTexture, pDestinationTexture);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetRenderTargetData)(PXY_THIS_ IDirect3DSurface9* pRenderTarget, IDirect3DSurface9* pDestSurface)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetRenderTargetData(pRenderTarget, pDestSurface);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetFrontBufferData)(PXY_THIS_ UINT iSwapChain, IDirect3DSurface9* pDestSurface)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetFrontBufferData(iSwapChain, pDestSurface);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(StretchRect)(PXY_THIS_ IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestSurface, CONST RECT* pDestRect, D3DTEXTUREFILTERTYPE Filter)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX StretchRect(pSourceSurface, pSourceRect, pDestSurface, pDestRect, Filter);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(ColorFill)(PXY_THIS_ IDirect3DSurface9* pSurface, CONST RECT* pRect, D3DCOLOR color)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX ColorFill(pSurface, pRect, color);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateOffscreenPlainSurface)(PXY_THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateOffscreenPlainSurface(Width, Height, Format, Pool, ppSurface, pSharedHandle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetRenderTarget)(PXY_THIS_ DWORD RenderTargetIndex, IDirect3DSurface9* pRenderTarget)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetRenderTarget(RenderTargetIndex, pRenderTarget);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetRenderTarget)(PXY_THIS_ DWORD RenderTargetIndex, IDirect3DSurface9** ppRenderTarget)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetRenderTarget(RenderTargetIndex, ppRenderTarget);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetDepthStencilSurface)(PXY_THIS_ IDirect3DSurface9* pNewZStencil)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetDepthStencilSurface(pNewZStencil);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDepthStencilSurface)(PXY_THIS_ IDirect3DSurface9** ppZStencilSurface)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDepthStencilSurface(ppZStencilSurface);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(BeginScene)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX BeginScene();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(EndScene)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX EndScene();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Clear)(PXY_THIS_ DWORD Count, CONST D3DRECT* pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Clear(Count, pRects, Flags, Color, Z, Stencil);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetTransform)(PXY_THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetTransform(State, pMatrix);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetTransform)(PXY_THIS_ D3DTRANSFORMSTATETYPE State, D3DMATRIX* pMatrix)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetTransform(State, pMatrix);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(MultiplyTransform)(PXY_THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX MultiplyTransform(State, pMatrix);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetViewport)(PXY_THIS_ CONST D3DVIEWPORT9* pViewport)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetViewport(pViewport);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetViewport)(PXY_THIS_ D3DVIEWPORT9* pViewport)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetViewport(pViewport);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetMaterial)(PXY_THIS_ CONST D3DMATERIAL9* pMaterial)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetMaterial(pMaterial);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetMaterial)(PXY_THIS_ D3DMATERIAL9* pMaterial)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetMaterial(pMaterial);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetLight)(PXY_THIS_ DWORD Index, CONST D3DLIGHT9* Light)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetLight(Index, Light);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetLight)(PXY_THIS_ DWORD Index, D3DLIGHT9* Light)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetLight(Index, Light);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(LightEnable)(PXY_THIS_ DWORD Index, BOOL Enable)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX LightEnable(Index, Enable);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetLightEnable)(PXY_THIS_ DWORD Index, BOOL* pEnable)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetLightEnable(Index, pEnable);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetClipPlane)(PXY_THIS_ DWORD Index, CONST float* pPlane)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetClipPlane(Index, pPlane);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetClipPlane)(PXY_THIS_ DWORD Index, float* pPlane)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetClipPlane(Index, pPlane);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetRenderState)(PXY_THIS_ D3DRENDERSTATETYPE State, DWORD Value)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetRenderState(State, Value);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetRenderState_Tracked)(PXY_THIS_ D3DRENDERSTATETYPE State, DWORD Value)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetRenderState_Tracked(State, Value);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetRenderState)(PXY_THIS_ D3DRENDERSTATETYPE State, DWORD* pValue)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetRenderState(State, pValue);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateStateBlock)(PXY_THIS_ D3DSTATEBLOCKTYPE Type, IDirect3DStateBlock9** ppSB)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateStateBlock(Type, ppSB);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(BeginStateBlock)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX BeginStateBlock();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(EndStateBlock)(PXY_THIS_ IDirect3DStateBlock9** ppSB)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX EndStateBlock(ppSB);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetClipStatus)(PXY_THIS_ CONST D3DCLIPSTATUS9* pClipStatus)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetClipStatus(pClipStatus);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetClipStatus)(PXY_THIS_ D3DCLIPSTATUS9* pClipStatus)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetClipStatus(pClipStatus);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetTexture)(PXY_THIS_ DWORD Stage, IDirect3DBaseTexture9** ppTexture)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetTexture(Stage, ppTexture);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetTexture)(PXY_THIS_ DWORD Stage, IDirect3DBaseTexture9* pTexture)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetTexture(Stage, pTexture);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetTextureStageState)(PXY_THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD* pValue)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetTextureStageState(Stage, Type, pValue);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetTextureStageState)(PXY_THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetTextureStageState(Stage, Type, Value);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetSamplerState)(PXY_THIS_ DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD* pValue)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetSamplerState(Sampler, Type, pValue);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetSamplerState)(PXY_THIS_ DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetSamplerState(Sampler, Type, Value);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetSamplerState_Tracked)(PXY_THIS_ DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetSamplerState_Tracked(Sampler, Type, Value);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(ValidateDevice)(PXY_THIS_ DWORD* pNumPasses)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX ValidateDevice(pNumPasses);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetPaletteEntries)(PXY_THIS_ UINT PaletteNumber, CONST PALETTEENTRY* pEntries)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetPaletteEntries(PaletteNumber, pEntries);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetPaletteEntries)(PXY_THIS_ UINT PaletteNumber, PALETTEENTRY* pEntries)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetPaletteEntries(PaletteNumber, pEntries);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetCurrentTexturePalette)(PXY_THIS_ UINT PaletteNumber)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetCurrentTexturePalette(PaletteNumber);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetCurrentTexturePalette)(PXY_THIS_ UINT *PaletteNumber)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetCurrentTexturePalette(PaletteNumber);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetScissorRect)(PXY_THIS_ CONST RECT* pRect)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetScissorRect(pRect);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetScissorRect)(PXY_THIS_ RECT* pRect)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetScissorRect(pRect);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetSoftwareVertexProcessing)(PXY_THIS_ BOOL bSoftware)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetSoftwareVertexProcessing(bSoftware);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(BOOL, GetSoftwareVertexProcessing)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetSoftwareVertexProcessing();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetNPatchMode)(PXY_THIS_ float nSegments)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetNPatchMode(nSegments);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(float, GetNPatchMode)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetNPatchMode();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawPrimitive)(PXY_THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawPrimitive_Compat)(PXY_THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawPrimitive_Compat(PrimitiveType, StartVertex, PrimitiveCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawIndexedPrimitive)(PXY_THIS_ D3DPRIMITIVETYPE PrimitiveType, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawIndexedPrimitive(PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices, startIndex, primCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawPrimitiveUP)(PXY_THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawPrimitiveUP_StateUnsafe)(PXY_THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawPrimitiveUP_StateUnsafe(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawIndexedPrimitiveUP)(PXY_THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, UINT PrimitiveCount, CONST void* pIndexData, D3DFORMAT IndexDataFormat, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawIndexedPrimitiveUP_StateUnsafe)(PXY_THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, UINT PrimitiveCount, CONST void* pIndexData, D3DFORMAT IndexDataFormat, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawIndexedPrimitiveUP_StateUnsafe(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(ProcessVertices)(PXY_THIS_ UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9* pDestBuffer, IDirect3DVertexDeclaration9* pVertexDecl, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer, pVertexDecl, Flags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateVertexDeclaration)(PXY_THIS_ CONST D3DVERTEXELEMENT9* pVertexElements, IDirect3DVertexDeclaration9** ppDecl)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateVertexDeclaration(pVertexElements, ppDecl);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetVertexDeclaration)(PXY_THIS_ IDirect3DVertexDeclaration9* pDecl)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetVertexDeclaration(pDecl);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetVertexDeclaration)(PXY_THIS_ IDirect3DVertexDeclaration9** ppDecl)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetVertexDeclaration(ppDecl);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetFVF)(PXY_THIS_ DWORD FVF)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetFVF(FVF);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetFVF)(PXY_THIS_ DWORD* pFVF)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetFVF(pFVF);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateVertexShader)(PXY_THIS_ CONST DWORD* pFunction, IDirect3DVertexShader9** ppShader)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateVertexShader(pFunction, ppShader);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetVertexShader)(PXY_THIS_ IDirect3DVertexShader9* pShader)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetVertexShader(pShader);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetVertexShader)(PXY_THIS_ IDirect3DVertexShader9** ppShader)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetVertexShader(ppShader);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetVertexShaderConstantF)(PXY_THIS_ UINT StartRegister, CONST float* pConstantData, UINT Vector4fCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetVertexShaderConstantF)(PXY_THIS_ UINT StartRegister, float* pConstantData, UINT Vector4fCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetVertexShaderConstantI)(PXY_THIS_ UINT StartRegister, CONST int* pConstantData, UINT Vector4iCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetVertexShaderConstantI)(PXY_THIS_ UINT StartRegister, int* pConstantData, UINT Vector4iCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetVertexShaderConstantB)(PXY_THIS_ UINT StartRegister, CONST BOOL* pConstantData, UINT BoolCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetVertexShaderConstantB(StartRegister, pConstantData, BoolCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetVertexShaderConstantB)(PXY_THIS_ UINT StartRegister, BOOL* pConstantData, UINT BoolCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetVertexShaderConstantB(StartRegister, pConstantData, BoolCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetStreamSource)(PXY_THIS_ UINT StreamNumber, IDirect3DVertexBuffer9* pStreamData, UINT OffsetInBytes, UINT Stride)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetStreamSource(StreamNumber, pStreamData, OffsetInBytes, Stride);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetStreamSource)(PXY_THIS_ UINT StreamNumber, IDirect3DVertexBuffer9** ppStreamData, UINT* pOffsetInBytes, UINT* pStride)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetStreamSource(StreamNumber, ppStreamData, pOffsetInBytes, pStride);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetStreamSourceFreq)(PXY_THIS_ UINT StreamNumber, UINT Setting)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetStreamSourceFreq(StreamNumber, Setting);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetStreamSourceFreq)(PXY_THIS_ UINT StreamNumber, UINT* pSetting)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetStreamSourceFreq(StreamNumber, pSetting);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetIndices)(PXY_THIS_ IDirect3DIndexBuffer9* pIndexData)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetIndices(pIndexData);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetIndices)(PXY_THIS_ IDirect3DIndexBuffer9** ppIndexData)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetIndices(ppIndexData);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreatePixelShader)(PXY_THIS_ CONST DWORD* pFunction, IDirect3DPixelShader9** ppShader)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreatePixelShader(pFunction, ppShader);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetPixelShader)(PXY_THIS_ IDirect3DPixelShader9* pShader)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetPixelShader(pShader);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetPixelShader)(PXY_THIS_ IDirect3DPixelShader9** ppShader)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetPixelShader(ppShader);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetPixelShaderConstantF)(PXY_THIS_ UINT StartRegister, CONST float* pConstantData, UINT Vector4fCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetPixelShaderConstantF)(PXY_THIS_ UINT StartRegister, float* pConstantData, UINT Vector4fCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetPixelShaderConstantI)(PXY_THIS_ UINT StartRegister, CONST int* pConstantData, UINT Vector4iCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetPixelShaderConstantI)(PXY_THIS_ UINT StartRegister, int* pConstantData, UINT Vector4iCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetPixelShaderConstantB)(PXY_THIS_ UINT StartRegister, CONST BOOL* pConstantData, UINT BoolCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetPixelShaderConstantB(StartRegister, pConstantData, BoolCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetPixelShaderConstantB)(PXY_THIS_ UINT StartRegister, BOOL* pConstantData, UINT BoolCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetPixelShaderConstantB(StartRegister, pConstantData, BoolCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawRectPatch)(PXY_THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DRECTPATCH_INFO* pRectPatchInfo)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawRectPatch(Handle, pNumSegs, pRectPatchInfo);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawTriPatch)(PXY_THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DTRIPATCH_INFO* pTriPatchInfo)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawTriPatch(Handle, pNumSegs, pTriPatchInfo);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DeletePatch)(PXY_THIS_ UINT Handle)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DeletePatch(Handle);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateQuery)(PXY_THIS_ D3DQUERYTYPE Type, IDirect3DQuery9** ppQuery)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateQuery(Type, ppQuery);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(CreateQuery_Optimized)(PXY_THIS_ D3DQUERYTYPE Type, IDirect3DQuery9** ppQuery)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX CreateQuery_Optimized(Type, ppQuery);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(DrawIndexedPrimitive_Compat)(PXY_THIS_ D3DPRIMITIVETYPE PrimitiveType, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX DrawIndexedPrimitive_Compat(PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices, startIndex, primCount);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Present_PG)(PXY_THIS_ CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Present_PG(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Present_Extra)(PXY_THIS_ CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Present_Extra(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Clear_Emulated)(PXY_THIS_ DWORD Count, CONST D3DRECT* pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Clear_Emulated(Count, pRects, Flags, Color, Z, Stencil);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetStreamSource_CAR)(PXY_THIS_ UINT StreamNumber, IDirect3DVertexBuffer9* pStreamData, UINT OffsetInBytes, UINT Stride)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetStreamSource_CAR(StreamNumber, pStreamData, OffsetInBytes, Stride);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetIndices_CAR)(PXY_THIS_ IDirect3DIndexBuffer9* pIndexData)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetIndices_CAR(pIndexData);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetViewport_CAR)(PXY_THIS_ CONST D3DVIEWPORT9* pViewport)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetViewport_CAR(pViewport);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetScissorRect_CAR)(PXY_THIS_ CONST RECT* pRect)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetScissorRect_CAR(pRect);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetRenderTarget_Compat)(PXY_THIS_ DWORD RenderTargetIndex, IDirect3DSurface9* pRenderTarget)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX SetRenderTarget_Compat(RenderTargetIndex, pRenderTarget);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_RESOURCE_DEFAULT
#define ROUTE_RESOURCE_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_resource
#define D912PXY_ROUTE_IMPL_PREFIX return obj->res.
D912PXY_METHOD_IMPL(SetPrivateData)(PXY_THIS_ REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetPrivateData)(PXY_THIS_ REFGUID refguid, void* pData, DWORD* pSizeOfData)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(FreePrivateData)(PXY_THIS_ REFGUID refguid)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(DWORD, SetPriority)(PXY_THIS_ DWORD PriorityNew)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(DWORD, GetPriority)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(void, PreLoad)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(D3DRESOURCETYPE, GetType)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetType();
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_VSTREAM_DEFAULT
#define ROUTE_VSTREAM_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_vstream
#define D912PXY_ROUTE_IMPL_PREFIX return obj->vstream.
D912PXY_METHOD_IMPL(Lock)(PXY_THIS_ UINT OffsetToLock, UINT SizeToLock, void** ppbData, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Lock(OffsetToLock, SizeToLock, ppbData, Flags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Unlock)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Unlock();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDesc)(PXY_THIS_ D3DVERTEXBUFFER_DESC *pDesc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_SURFACE_DEFAULT
#define ROUTE_SURFACE_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_surface
#define D912PXY_ROUTE_IMPL_PREFIX return obj->surface.
D912PXY_METHOD_IMPL(GetContainer)(PXY_THIS_ REFIID riid, void** ppContainer)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDesc)(PXY_THIS_ D3DSURFACE_DESC *pDesc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDesc(pDesc);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(LockRect)(PXY_THIS_ D3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX LockRect(pLockedRect, pRect, Flags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(UnlockRect)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX UnlockRect();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDC)(PXY_THIS_ HDC *phdc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(ReleaseDC)(PXY_THIS_ HDC hdc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_QUERY_DEFAULT
#define ROUTE_QUERY_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_query
#define D912PXY_ROUTE_IMPL_PREFIX return obj->query.
D912PXY_METHOD_IMPL_(D3DQUERYTYPE, GetType)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetType();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(DWORD, GetDataSize)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDataSize();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Issue)(PXY_THIS_ DWORD dwIssueFlags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Issue(dwIssueFlags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetData)(PXY_THIS_ void* pData, DWORD dwSize, DWORD dwGetDataFlags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetData(pData, dwSize, dwGetDataFlags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDataZeroOverride)(PXY_THIS_ void* pData, DWORD dwSize, DWORD dwGetDataFlags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDataZeroOverride(pData, dwSize, dwGetDataFlags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDataOneOverride)(PXY_THIS_ void* pData, DWORD dwSize, DWORD dwGetDataFlags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDataOneOverride(pData, dwSize, dwGetDataFlags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(IssueNOP)(PXY_THIS_ DWORD dwIssueFlags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX IssueNOP(dwIssueFlags);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_QUERY_OCC_DEFAULT
#define ROUTE_QUERY_OCC_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_query_occlusion
#define D912PXY_ROUTE_IMPL_PREFIX return obj->query_occ.
D912PXY_METHOD_IMPL(occ_Issue)(PXY_THIS_ DWORD dwIssueFlags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX occ_Issue(dwIssueFlags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(occ_GetData)(PXY_THIS_ void* pData, DWORD dwSize, DWORD dwGetDataFlags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX occ_GetData(pData, dwSize, dwGetDataFlags);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_BASE_TEX_DEFAULT
#define ROUTE_BASE_TEX_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_basetexture
#define D912PXY_ROUTE_IMPL_PREFIX return obj->basetex.
D912PXY_METHOD_IMPL_(DWORD, SetLOD)(PXY_THIS_ DWORD LODNew)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(DWORD, GetLOD)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(DWORD, GetLevelCount)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetAutoGenFilterType)(PXY_THIS_ D3DTEXTUREFILTERTYPE FilterType)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(D3DTEXTUREFILTERTYPE, GetAutoGenFilterType)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3DTEXF_NONE);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(void, GenerateMipSubLevels)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(DWORD, GetPriority_SRVhack)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetPriority_SRVhack();
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_TEX_2D_DEFAULT
#define ROUTE_TEX_2D_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_texture
#define D912PXY_ROUTE_IMPL_PREFIX return obj->tex_2d.
D912PXY_METHOD_IMPL(GetLevelDesc)(PXY_THIS_ UINT Level, D3DSURFACE_DESC *pDesc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetLevelDesc(Level, pDesc);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetSurfaceLevel)(PXY_THIS_ UINT Level, IDirect3DSurface9** ppSurfaceLevel)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetSurfaceLevel(Level, ppSurfaceLevel);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(LockRect)(PXY_THIS_ UINT Level, D3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX LockRect(Level, pLockedRect, pRect, Flags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(UnlockRect)(PXY_THIS_ UINT Level)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX UnlockRect(Level);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(AddDirtyRect)(PXY_THIS_ CONST RECT* pDirtyRect)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX AddDirtyRect(pDirtyRect);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_TEX_3D_DEFAULT
#define ROUTE_TEX_3D_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_vtexture
#define D912PXY_ROUTE_IMPL_PREFIX return obj->tex_3d.
D912PXY_METHOD_IMPL(GetLevelDesc)(PXY_THIS_ UINT Level, D3DVOLUME_DESC *pDesc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetVolumeLevel)(PXY_THIS_ UINT Level, IDirect3DVolume9** ppVolumeLevel)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(LockBox)(PXY_THIS_ UINT Level, D3DLOCKED_BOX* pLockedVolume, CONST D3DBOX* pBox, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(UnlockBox)(PXY_THIS_ UINT Level)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(AddDirtyBox)(PXY_THIS_ CONST D3DBOX* pDirtyBox)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_TEX_CUBE_DEFAULT
#define ROUTE_TEX_CUBE_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_ctexture
#define D912PXY_ROUTE_IMPL_PREFIX return obj->tex_cube.
D912PXY_METHOD_IMPL(GetLevelDesc)(PXY_THIS_ UINT Level, D3DSURFACE_DESC *pDesc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetLevelDesc(Level, pDesc);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetCubeMapSurface)(PXY_THIS_ D3DCUBEMAP_FACES FaceType, UINT Level, IDirect3DSurface9** ppCubeMapSurface)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetCubeMapSurface(FaceType, Level, ppCubeMapSurface);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(LockRect)(PXY_THIS_ D3DCUBEMAP_FACES FaceType, UINT Level, D3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX LockRect(FaceType, Level, pLockedRect, pRect, Flags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(UnlockRect)(PXY_THIS_ D3DCUBEMAP_FACES FaceType, UINT Level)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX UnlockRect(FaceType, Level);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(AddDirtyRect)(PXY_THIS_ D3DCUBEMAP_FACES FaceType, CONST RECT* pDirtyRect)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX AddDirtyRect(FaceType, pDirtyRect);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_VDECL_DEFAULT
#define ROUTE_VDECL_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_vdecl
#define D912PXY_ROUTE_IMPL_PREFIX return obj->vdecl.
D912PXY_METHOD_IMPL(GetDeclaration)(PXY_THIS_ D3DVERTEXELEMENT9* pElement, UINT* pNumElements)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDeclaration(pElement, pNumElements);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_SHADER_DEFAULT
#define ROUTE_SHADER_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_shader
#define D912PXY_ROUTE_IMPL_PREFIX return obj->shader.
D912PXY_METHOD_IMPL(GetFunction)(PXY_THIS_ void* arg, UINT* pSizeOfData)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_SWAPCHAIN_DEFAULT
#define ROUTE_SWAPCHAIN_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_swapchain
#define D912PXY_ROUTE_IMPL_PREFIX return obj->swapchain.
D912PXY_METHOD_IMPL(Present)(PXY_THIS_ CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion, DWORD dwFlags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetFrontBufferData)(PXY_THIS_ IDirect3DSurface9* pDestSurface)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetFrontBufferData(pDestSurface);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetBackBuffer)(PXY_THIS_ UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetBackBuffer(iBackBuffer, Type, ppBackBuffer);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetRasterStatus)(PXY_THIS_ D3DRASTER_STATUS* pRasterStatus)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDisplayMode)(PXY_THIS_ D3DDISPLAYMODE* pMode)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetPresentParameters)(PXY_THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetPresentParameters(pPresentationParameters);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(ULONG, ReleaseSwapChain)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX ReleaseSwapChain();
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
#ifndef ROUTE_SURFACE_LAYER_DEFAULT
#define ROUTE_SURFACE_LAYER_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_surface_layer
#define D912PXY_ROUTE_IMPL_PREFIX return obj->layer.
#define D912PXY_ROUTE_IMPL_STUB_CUSTOM(ret) obj->layer.GetBaseSurface()->com.ImplStubCall(__FUNCTION__, __LINE__); return ret
#define D912PXY_ROUTE_IMPL_STUB_CUSTOM_(ret) obj->layer.GetBaseSurface()->com.ImplStubCall(__FUNCTION__, __LINE__);
D912PXY_METHOD_IMPL(QueryInterface)(PXY_THIS_ REFIID riid, void** ppvObj)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX QueryInterface(riid, ppvObj);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(ULONG, AddRef)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX AddRef();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(ULONG, Release)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX Release();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDevice)(PXY_THIS_ IDirect3DDevice9** ppDevice)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(SetPrivateData)(PXY_THIS_ REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetPrivateData)(PXY_THIS_ REFGUID refguid, void* pData, DWORD* pSizeOfData)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(FreePrivateData)(PXY_THIS_ REFGUID refguid)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(DWORD, SetPriority)(PXY_THIS_ DWORD PriorityNew)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(DWORD, GetPriority)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(void, PreLoad)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM_(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL_(D3DRESOURCETYPE, GetType)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3DRTYPE_SURFACE);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetContainer)(PXY_THIS_ REFIID riid, void** ppContainer)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDesc)(PXY_THIS_ D3DSURFACE_DESC *pDesc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX GetDesc(pDesc);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(LockRect)(PXY_THIS_ D3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX LockRect(pLockedRect, pRect, Flags);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(UnlockRect)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_PREFIX UnlockRect();
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(GetDC)(PXY_THIS_ HDC *phdc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(ReleaseDC)(PXY_THIS_ HDC hdc)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB_CUSTOM(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#undef D912PXY_ROUTE_IMPL_STUB_CUSTOM
#undef D912PXY_ROUTE_IMPL_STUB_CUSTOM_
#endif
#ifndef ROUTE_SBLOCK_DEFAULT
#define ROUTE_SBLOCK_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_sblock
#define D912PXY_ROUTE_IMPL_PREFIX return obj->sblock
D912PXY_METHOD_IMPL(Capture)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
D912PXY_METHOD_IMPL(Apply)(PXY_THIS)
{
D912PXY_ROUTE_IMPL_START
D912PXY_ROUTE_IMPL_STUB(D3D_OK);
D912PXY_ROUTE_IMPL_END
}
#undef D912PXY_ROUTE_IMPL_PREFIX
#undef D912PXY_METHOD_IMPL_CN
#endif
/*
#ifndef ROUTE_*NAME*_DEFAULT
#define ROUTE_*NAME*_DEFAULT
#define D912PXY_METHOD_IMPL_CN d912pxy_
#define D912PXY_ROUTE_IMPL_PREFIX return obj->
#undef D912PXY_METHOD_IMPL_CN
#undef D912PXY_ROUTE_IMPL_PREFIX
#endif
*/
#endif
|
/*
Plugin-SDK (Grand Theft Auto San Andreas) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CFont.h"
CSprite2d *CFont::Sprite = (CSprite2d *)0xC71AD0;
CSprite2d *CFont::ButtonSprite = (CSprite2d *)0xC71AD8;
unsigned char& CFont::m_nExtraFontSymbolId = *(unsigned char *)0xC71A54;
bool& CFont::m_bNewLine = *(bool *)0xC71A55;
CRGBA *CFont::m_Color = (CRGBA *)0xC71A60;
CVector2D *CFont::m_Scale = (CVector2D *)0xC71A64;
float& CFont::m_fSlant = *(float *)0xC71A6C;
CVector2D *CFont::m_fSlantRefPoint = (CVector2D *)0xC71A70;
bool& CFont::m_bFontJustify = *(bool *)0xC71A78;
bool& CFont::m_bFontCentreAlign = *(bool *)0xC71A79;
bool& CFont::m_bFontRightAlign = *(bool *)0xC71A7A;
bool& CFont::m_bFontBackground = *(bool *)0xC71A7B;
bool& CFont::m_bEnlargeBackgroundBox = *(bool *)0xC71A7C;
bool& CFont::m_bFontPropOn = *(bool *)0xC71A7D;
bool& CFont::m_bFontIsBlip = *(bool *)0xC71A7E;
unsigned int CFont::m_dwFontAlpha = *(unsigned int *)0xC71A80;
CRGBA *CFont::m_FontBackgroundColor = (CRGBA *)0xC71A84;
float& CFont::m_fWrapx = *(float *)0xC71A88;
float& CFont::m_fFontCentreSize = *(float *)0xC71A8C;
float& CFont::m_fRightJustifyWrap = *(float *)0xC71A90;
unsigned char& CFont::m_FontTextureId = *(unsigned char *)0xC71A94;
unsigned char& CFont::m_FontStyle = *(unsigned char *)0xC71A95;
unsigned char& CFont::m_nFontShadow = *(unsigned char *)0xC71A96;
CRGBA *CFont::m_FontDropColor = (CRGBA *)0xC71A97;
unsigned char& CFont::m_nFontOutlineSize = *(unsigned char *)0xC71A9B;
unsigned char& CFont::m_nFontOutline = *(unsigned char *)0xC71A9C;
tFontData *gFontData = (tFontData *)0xC718B0;
void CFont::Initialise()
{
((void (__cdecl *)())0x5BA690)();
}
void CFont::Shutdown()
{
((void (__cdecl *)())0x7189B0)();
}
void CFont::PrintChar(float x, float y, char character)
{
((void (__cdecl *)(float, float, char))0x718A10)(x, y, character);
}
char *CFont::ParseToken(char *text, CRGBA & color, bool isBlip, char *tag)
{
return ((char *(__cdecl *)(char *, CRGBA &, bool, char *))0x718F00)(text, color, isBlip, tag);
}
void CFont::SetScale(float w, float h)
{
((void (__cdecl *)(float, float))0x719380)(w, h);
}
void CFont::SetScaleForCurrentlanguage(float w, float h)
{
((void (__cdecl *)(float, float))0x7193A0)(w, h);
}
void CFont::SetSlantRefPoint(float x, float y)
{
((void (__cdecl *)(float, float))0x719400)(x, y);
}
void CFont::SetSlant(float value)
{
((void (__cdecl *)(float))0x719420)(value);
}
void CFont::SetColor(CRGBA color)
{
((void (__cdecl *)(CRGBA))0x719430)(color);
}
void CFont::SetFontStyle(short style)
{
((void (__cdecl *)(short))0x719490)(style);
}
void CFont::SetWrapx(float value)
{
((void (__cdecl *)(float))0x7194D0)(value);
}
void CFont::SetCentreSize(float value)
{
((void (__cdecl *)(float))0x7194E0)(value);
}
void CFont::SetRightJustifyWrap(float value)
{
((void (__cdecl *)(float))0x7194F0)(value);
}
void CFont::SetAlphaFade(float alpha)
{
((void (__cdecl *)(float))0x719500)(alpha);
}
void CFont::SetDropColor(CRGBA color)
{
((void (__cdecl *)(CRGBA))0x719510)(color);
}
void CFont::SetDropShadowPosition(short value)
{
((void (__cdecl *)(short))0x719570)(value);
}
void CFont::SetEdge(short value)
{
((void (__cdecl *)(short))0x719590)(value);
}
#ifdef SetProp
#define SET_PROP_USED
#undef SetProp
#endif
void CFont::SetProportional(bool on)
{
((void (__cdecl *)(bool))0x7195B0)(on);
}
#ifdef SET_PROP_USED
#undef SET_PROP_USED
#define SetProp SetPropA
#endif
void CFont::SetBackground(bool enable, bool includeWrap)
{
((void (__cdecl *)(bool, bool))0x7195C0)(enable, includeWrap);
}
void CFont::SetBackgroundColor(CRGBA color)
{
((void (__cdecl *)(CRGBA))0x7195E0)(color);
}
void CFont::SetJustify(bool on)
{
((void (__cdecl *)(bool))0x719600)(on);
}
void CFont::SetOrientation(eFontAlignment alignment)
{
((void (__cdecl *)(eFontAlignment))0x719610)(alignment);
}
void CFont::InitPerFrame()
{
((void (__cdecl *)())0x719800)();
}
void CFont::RenderFontBuffer()
{
((void (__cdecl *)())0x719840)();
}
float CFont::GetStringWidth(char *string, bool unk1, bool unk2)
{
return ((float (__cdecl *)(char *, bool, bool))0x71A0E0)(string, unk1, unk2);
}
void CFont::DrawFonts()
{
((void (__cdecl *)())0x71A210)();
}
short CFont::ProcessCurrentString(bool print, float x, float y, char *text)
{
return ((short (__cdecl *)(bool, float, float, char *))0x71A220)(print, x, y, text);
}
short CFont::GetNumberLines(float x, float y, char *text)
{
return ((short (__cdecl *)(float, float, char *))0x71A5E0)(x, y, text);
}
short CFont::ProcessStringToDisplay(float x, float y, char *text)
{
return ((short (__cdecl *)(float, float, char *))0x71A600)(x, y, text);
}
void CFont::GetTextRect(CRect *rect, float x, float y, char *text)
{
((void (__cdecl *)(CRect *, float, float, char *))0x71A620)(rect, x, y, text);
}
void CFont::PrintString(float x, float y, char *text)
{
((void (__cdecl *)(float, float, char *))0x71A700)(x, y, text);
}
void CFont::PrintStringFromBottom(float x, float y, char *text)
{
((void (__cdecl *)(float, float, char *))0x71A820)(x, y, text);
}
|
#ifndef YUKI_SCRIPT_CONTEXT_STACK_HPP
#define YUKI_SCRIPT_CONTEXT_STACK_HPP
#include <deque>
#include <stack>
#include "context.hpp"
namespace yuki::context
{
class context_stack
{
public:
context_stack();
void push(yuki::context::context && c);
yuki::context::context & current_context();
std::size_t size() const;
void pop();
yuki::context::context::function_t get_function(const std::string & identifier) const;
yuki::type::variable & get_variable(const std::string& identifier) const;
private:
std::deque<yuki::context::context> m_contexts;
};
}
#endif
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <tvm/runtime/registry.h>
#include <tvm/runtime/device_api.h>
#include <tvm/target/codegen.h>
#include "core/common/common.h"
#include "tvm_api.h"
namespace onnxruntime {
namespace tvm {
using TvmIntArray = ::tvm::Array<::tvm::Integer>;
using TvmPackedFunc = ::tvm::PackedFunc;
TvmModule TVMCompile(const std::string& onnx_txt,
const std::string& model_path,
const TvmEPOptions& options,
int opset,
const TVMTensorShapes& input_shapes)
{
::tvm::Array<TvmIntArray> shapes;
for (size_t i = 0; i < input_shapes.size(); ++i)
{
TvmIntArray shape;
for (auto& dim : input_shapes[i])
{
shape.push_back(::tvm::Integer(dim));
}
shapes.push_back(shape);
}
const TvmPackedFunc* compile = ::tvm::runtime::Registry::Get("tvm_onnx_import_and_compile");
ORT_ENFORCE(compile != nullptr, "Unable to retrieve 'tvm_onnx_import_and_compile'.");
TvmModule mod = (*compile)(TVMByteArray{onnx_txt.data(), onnx_txt.size()},
model_path,
options.executor,
options.target,
options.target_host,
options.opt_level,
opset,
options.freeze_weights,
shapes,
options.to_nhwc,
options.tuning_file_path,
options.tuning_type);
ORT_ENFORCE(mod.get() != nullptr, "Compiled TVM Module is nullptr!");
return mod;
}
void TVMSetInputs(TvmModule& mod,
std::vector<size_t>& inds,
std::vector<DLTensor>& inputs)
{
TvmPackedFunc set_input = mod.GetFunction("set_input", false);
TvmPackedFunc set_input_zero_copy = mod.GetFunction("set_input_zero_copy", false);
for (size_t i = 0; i < inds.size(); ++i)
{
if (reinterpret_cast<size_t>(inputs[i].data) % ::tvm::runtime::kAllocAlignment == 0) {
set_input_zero_copy(inds[i], &inputs[i]);
} else {
set_input(inds[i], &inputs[i]);
}
}
}
void TVM_VM_SetInputs(TvmModule& mod,
std::vector<size_t>& inds,
std::vector<DLTensor>& inputs)
{
TvmPackedFunc set_input = mod.GetFunction("set_one_input", false);
for (size_t i = 0; i < inds.size(); ++i)
{
set_input("main", inds[i], &inputs[i]);
}
}
void TVMGetOutputs(TvmModule& mod,
std::vector<DLTensor>& outputs)
{
TvmPackedFunc get_output = mod.GetFunction("get_output", false);
for (size_t i = 0; i < outputs.size(); ++i)
{
get_output(i, &outputs[i]);
}
}
void TVM_VM_GetOutputs(TvmModule& mod,
std::vector<DLTensor>& outputs)
{
TvmPackedFunc get_output = mod.GetFunction("get_output", false);
for (size_t i = 0; i < outputs.size(); ++i)
{
// TODO(vvchernov): think about improvement of memory management
::tvm::runtime::NDArray output_array = get_output(i);
output_array.CopyTo(&outputs[i]);
}
}
void TVMGetOutputShapes(TvmModule& mod,
TVMTensorShapes& output_shapes)
{
size_t size = output_shapes.size();
TvmPackedFunc get_output = mod.GetFunction("get_output", false);
for (size_t i = 0; i < size; ++i) {
::tvm::runtime::NDArray output_array = get_output(i);
::tvm::runtime::ShapeTuple shape_tuple = output_array.Shape();
size_t dims_num = shape_tuple.size();
TensorShapeVector dims;
for (size_t j = 0; j < dims_num; ++j) {
dims.push_back(int64_t(shape_tuple[j]));
}
output_shapes[i] = dims;
}
}
void TVMRun(TvmModule& mod)
{
TvmPackedFunc run = mod.GetFunction("run", false);
ORT_ENFORCE(run != nullptr, "Unable to retrieve graph executor run.");
run();
}
void TVM_VM_Run(TvmModule& mod)
{
TvmPackedFunc run = mod.GetFunction("invoke", false);
ORT_ENFORCE(run != nullptr, "Unable to retrieve virtual machine invoke.");
run("main");
}
} // namespace tvm
} // namespace onnxruntime
|
#include <gainput/gainput.h>
#include <X11/Xlib.h>
#include <X11/extensions/XInput2.h>
#include <iostream>
// Define your user buttons
enum Button
{
ButtonMenu,
ButtonConfirm,
MouseX,
MouseY
};
static Window create_win(Display *dpy)
{
XIEventMask mask;
Window win;
unsigned long screen;
screen = DefaultScreen(dpy);
win = RootWindow(dpy, screen);
XSelectInput(dpy, win, ExposureMask);
mask.deviceid = XIAllDevices;
mask.mask_len = XIMaskLen(XI_RawMotion);
mask.mask = (unsigned char*)calloc(mask.mask_len, sizeof(char));
memset(mask.mask, 0, mask.mask_len);
XISetMask(mask.mask, XI_RawMotion);
XISetMask(mask.mask, XI_Enter);
XISetMask(mask.mask, XI_Leave);
XISetMask(mask.mask, XI_ButtonPress);
XISetMask(mask.mask, XI_ButtonRelease);
XISetMask(mask.mask, XI_KeyPress);
XISetMask(mask.mask, XI_KeyRelease);
XISetMask(mask.mask, XI_RawKeyPress);
XISetMask(mask.mask, XI_RawKeyRelease);
XISetMask(mask.mask, XI_RawButtonPress);
XISetMask(mask.mask, XI_RawButtonRelease);
XISelectEvents(dpy, win, &mask, 1);
free(mask.mask);
XMapWindow(dpy, win);
XSync(dpy, True);
return win;
}
int main(int argc, char** argv)
{
// Setup Gainput
gainput::InputManager manager;
const gainput::DeviceId mouseId = manager.CreateDevice<gainput::InputDeviceMouse>(gainput::InputDevice::AutoIndex, gainput::InputDevice::DV_RAW);
const gainput::DeviceId keyboardId = manager.CreateDevice<gainput::InputDeviceKeyboard>(gainput::InputDevice::AutoIndex, gainput::InputDevice::DV_RAW);
const gainput::DeviceId padId = manager.CreateDevice<gainput::InputDevicePad>(gainput::InputDevice::AutoIndex);
gainput::InputMap map(manager);
map.MapBool(ButtonMenu, keyboardId, gainput::KeyEscape);
map.MapBool(ButtonConfirm, mouseId, gainput::MouseButtonLeft);
map.MapFloat(MouseX, mouseId, gainput::MouseAxisX);
map.MapFloat(MouseY, mouseId, gainput::MouseAxisY);
map.MapBool(ButtonConfirm, padId, gainput::PadButtonA);
Display *dpy;
int xi_opcode, event, error;
Window win;
XEvent ev;
dpy = XOpenDisplay(NULL);
if (!dpy) {
fprintf(stderr, "Failed to open display.\n");
return -1;
}
if (!XQueryExtension(dpy, "XInputExtension", &xi_opcode, &event, &error)) {
printf("X Input extension not available.\n");
return -1;
}
win = create_win(dpy);
for (;;)
{
// Update Gainput
manager.Update();
XGenericEventCookie *cookie = &ev.xcookie;
XNextEvent(dpy, &ev);
if (cookie->type != GenericEvent ||
cookie->extension != xi_opcode ||
!XGetEventData(dpy, cookie)) {
continue;
}
manager.HandleEvent(ev);
XFreeEventData(dpy, cookie);
// Check button states
if (map.GetBoolWasDown(ButtonMenu))
{
std::cout << "Open menu!!" << std::endl;
}
if (map.GetBoolWasDown(ButtonConfirm))
{
std::cout << "Confirmed!!" << std::endl;
}
if (map.GetFloatDelta(MouseX) != 0.0f || map.GetFloatDelta(MouseY) != 0.0f)
{
std::cout << "Mouse: " << map.GetFloat(MouseX) << ", " << map.GetFloat(MouseY) << std::endl;
}
}
XCloseDisplay(dpy);
return 0;
}
|
//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the function verifier interface, that can be used for some
// sanity checking of input to the system.
//
// Note that this does not provide full `Java style' security and verifications,
// instead it just tries to ensure that code is well-formed.
//
// * Both of a binary operator's parameters are of the same type
// * Verify that the indices of mem access instructions match other operands
// * Verify that arithmetic and other things are only performed on first-class
// types. Verify that shifts & logicals only happen on integrals f.e.
// * All of the constants in a switch statement are of the correct type
// * The code is in valid SSA form
// * It should be illegal to put a label into any other type (like a structure)
// or to return one. [except constant arrays!]
// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
// * PHI nodes must have an entry for each predecessor, with no extras.
// * PHI nodes must be the first thing in a basic block, all grouped together
// * PHI nodes must have at least one entry
// * All basic blocks should only end with terminator insts, not contain them
// * The entry node to a function must not have predecessors
// * All Instructions must be embedded into a basic block
// * Functions cannot take a void-typed parameter
// * Verify that a function's argument list agrees with it's declared type.
// * It is illegal to specify a name for a void value.
// * It is illegal to have a internal global value with no initializer
// * It is illegal to have a ret instruction that returns a value that does not
// agree with the function return value type.
// * Function call argument types match the function prototype
// * A landing pad is defined by a landingpad instruction, and can be jumped to
// only by the unwind edge of an invoke instruction.
// * A landingpad instruction must be the first non-PHI instruction in the
// block.
// * All landingpad instructions must use the same personality function with
// the same function.
// * All other things that are tested by asserts spread about the code...
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Verifier.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Statepoint.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstdarg>
using namespace llvm;
static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(false));
namespace {
struct VerifierSupport {
raw_ostream &OS;
const Module *M;
/// \brief Track the brokenness of the module while recursively visiting.
bool Broken;
explicit VerifierSupport(raw_ostream &OS)
: OS(OS), M(nullptr), Broken(false) {}
void WriteValue(const Value *V) {
if (!V)
return;
if (isa<Instruction>(V)) {
OS << *V << '\n';
} else {
V->printAsOperand(OS, true, M);
OS << '\n';
}
}
void WriteMetadata(const Metadata *MD) {
if (!MD)
return;
MD->printAsOperand(OS, true, M);
OS << '\n';
}
void WriteType(Type *T) {
if (!T)
return;
OS << ' ' << *T;
}
void WriteComdat(const Comdat *C) {
if (!C)
return;
OS << *C;
}
// CheckFailed - A check failed, so print out the condition and the message
// that failed. This provides a nice place to put a breakpoint if you want
// to see why something is not correct.
void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
const Value *V2 = nullptr, const Value *V3 = nullptr,
const Value *V4 = nullptr) {
OS << Message.str() << "\n";
WriteValue(V1);
WriteValue(V2);
WriteValue(V3);
WriteValue(V4);
Broken = true;
}
void CheckFailed(const Twine &Message, const Metadata *V1, const Metadata *V2,
const Metadata *V3 = nullptr, const Metadata *V4 = nullptr) {
OS << Message.str() << "\n";
WriteMetadata(V1);
WriteMetadata(V2);
WriteMetadata(V3);
WriteMetadata(V4);
Broken = true;
}
void CheckFailed(const Twine &Message, const Metadata *V1,
const Value *V2 = nullptr) {
OS << Message.str() << "\n";
WriteMetadata(V1);
WriteValue(V2);
Broken = true;
}
void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
const Value *V3 = nullptr) {
OS << Message.str() << "\n";
WriteValue(V1);
WriteType(T2);
WriteValue(V3);
Broken = true;
}
void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
Type *T3 = nullptr) {
OS << Message.str() << "\n";
WriteType(T1);
WriteType(T2);
WriteType(T3);
Broken = true;
}
void CheckFailed(const Twine &Message, const Comdat *C) {
OS << Message.str() << "\n";
WriteComdat(C);
Broken = true;
}
};
class Verifier : public InstVisitor<Verifier>, VerifierSupport {
friend class InstVisitor<Verifier>;
LLVMContext *Context;
DominatorTree DT;
/// \brief When verifying a basic block, keep track of all of the
/// instructions we have seen so far.
///
/// This allows us to do efficient dominance checks for the case when an
/// instruction has an operand that is an instruction in the same block.
SmallPtrSet<Instruction *, 16> InstsInThisBlock;
/// \brief Keep track of the metadata nodes that have been checked already.
SmallPtrSet<Metadata *, 32> MDNodes;
/// \brief The personality function referenced by the LandingPadInsts.
/// All LandingPadInsts within the same function must use the same
/// personality function.
const Value *PersonalityFn;
/// \brief Whether we've seen a call to @llvm.frameallocate in this function
/// already.
bool SawFrameAllocate;
public:
explicit Verifier(raw_ostream &OS = dbgs())
: VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
SawFrameAllocate(false) {}
bool verify(const Function &F) {
M = F.getParent();
Context = &M->getContext();
// First ensure the function is well-enough formed to compute dominance
// information.
if (F.empty()) {
OS << "Function '" << F.getName()
<< "' does not contain an entry block!\n";
return false;
}
for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
if (I->empty() || !I->back().isTerminator()) {
OS << "Basic Block in function '" << F.getName()
<< "' does not have terminator!\n";
I->printAsOperand(OS, true);
OS << "\n";
return false;
}
}
// Now directly compute a dominance tree. We don't rely on the pass
// manager to provide this as it isolates us from a potentially
// out-of-date dominator tree and makes it significantly more complex to
// run this code outside of a pass manager.
// FIXME: It's really gross that we have to cast away constness here.
DT.recalculate(const_cast<Function &>(F));
Broken = false;
// FIXME: We strip const here because the inst visitor strips const.
visit(const_cast<Function &>(F));
InstsInThisBlock.clear();
PersonalityFn = nullptr;
SawFrameAllocate = false;
return !Broken;
}
bool verify(const Module &M) {
this->M = &M;
Context = &M.getContext();
Broken = false;
// Scan through, checking all of the external function's linkage now...
for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
visitGlobalValue(*I);
// Check to make sure function prototypes are okay.
if (I->isDeclaration())
visitFunction(*I);
}
for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I)
visitGlobalVariable(*I);
for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
I != E; ++I)
visitGlobalAlias(*I);
for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
E = M.named_metadata_end();
I != E; ++I)
visitNamedMDNode(*I);
for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
visitComdat(SMEC.getValue());
visitModuleFlags(M);
visitModuleIdents(M);
return !Broken;
}
private:
// Verification methods...
void visitGlobalValue(const GlobalValue &GV);
void visitGlobalVariable(const GlobalVariable &GV);
void visitGlobalAlias(const GlobalAlias &GA);
void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
const GlobalAlias &A, const Constant &C);
void visitNamedMDNode(const NamedMDNode &NMD);
void visitMDNode(MDNode &MD);
void visitMetadataAsValue(MetadataAsValue &MD, Function *F);
void visitValueAsMetadata(ValueAsMetadata &MD, Function *F);
void visitComdat(const Comdat &C);
void visitModuleIdents(const Module &M);
void visitModuleFlags(const Module &M);
void visitModuleFlag(const MDNode *Op,
DenseMap<const MDString *, const MDNode *> &SeenIDs,
SmallVectorImpl<const MDNode *> &Requirements);
void visitFunction(const Function &F);
void visitBasicBlock(BasicBlock &BB);
void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
// InstVisitor overrides...
using InstVisitor<Verifier>::visit;
void visit(Instruction &I);
void visitTruncInst(TruncInst &I);
void visitZExtInst(ZExtInst &I);
void visitSExtInst(SExtInst &I);
void visitFPTruncInst(FPTruncInst &I);
void visitFPExtInst(FPExtInst &I);
void visitFPToUIInst(FPToUIInst &I);
void visitFPToSIInst(FPToSIInst &I);
void visitUIToFPInst(UIToFPInst &I);
void visitSIToFPInst(SIToFPInst &I);
void visitIntToPtrInst(IntToPtrInst &I);
void visitPtrToIntInst(PtrToIntInst &I);
void visitBitCastInst(BitCastInst &I);
void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
void visitPHINode(PHINode &PN);
void visitBinaryOperator(BinaryOperator &B);
void visitICmpInst(ICmpInst &IC);
void visitFCmpInst(FCmpInst &FC);
void visitExtractElementInst(ExtractElementInst &EI);
void visitInsertElementInst(InsertElementInst &EI);
void visitShuffleVectorInst(ShuffleVectorInst &EI);
void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
void visitCallInst(CallInst &CI);
void visitInvokeInst(InvokeInst &II);
void visitGetElementPtrInst(GetElementPtrInst &GEP);
void visitLoadInst(LoadInst &LI);
void visitStoreInst(StoreInst &SI);
void verifyDominatesUse(Instruction &I, unsigned i);
void visitInstruction(Instruction &I);
void visitTerminatorInst(TerminatorInst &I);
void visitBranchInst(BranchInst &BI);
void visitReturnInst(ReturnInst &RI);
void visitSwitchInst(SwitchInst &SI);
void visitIndirectBrInst(IndirectBrInst &BI);
void visitSelectInst(SelectInst &SI);
void visitUserOp1(Instruction &I);
void visitUserOp2(Instruction &I) { visitUserOp1(I); }
void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
void visitAtomicRMWInst(AtomicRMWInst &RMWI);
void visitFenceInst(FenceInst &FI);
void visitAllocaInst(AllocaInst &AI);
void visitExtractValueInst(ExtractValueInst &EVI);
void visitInsertValueInst(InsertValueInst &IVI);
void visitLandingPadInst(LandingPadInst &LPI);
void VerifyCallSite(CallSite CS);
void verifyMustTailCall(CallInst &CI);
bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
unsigned ArgNo, std::string &Suffix);
bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
SmallVectorImpl<Type *> &ArgTys);
bool VerifyIntrinsicIsVarArg(bool isVarArg,
ArrayRef<Intrinsic::IITDescriptor> &Infos);
bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
const Value *V);
void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
bool isReturnValue, const Value *V);
void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
const Value *V);
void VerifyConstantExprBitcastType(const ConstantExpr *CE);
};
class DebugInfoVerifier : public VerifierSupport {
public:
explicit DebugInfoVerifier(raw_ostream &OS = dbgs()) : VerifierSupport(OS) {}
bool verify(const Module &M) {
this->M = &M;
verifyDebugInfo();
return !Broken;
}
private:
void verifyDebugInfo();
void processInstructions(DebugInfoFinder &Finder);
void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
};
} // End anonymous namespace
// Assert - We know that cond should be true, if not print an error message.
#define Assert(C, M) \
do { if (!(C)) { CheckFailed(M); return; } } while (0)
#define Assert1(C, M, V1) \
do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
#define Assert2(C, M, V1, V2) \
do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
#define Assert3(C, M, V1, V2, V3) \
do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
#define Assert4(C, M, V1, V2, V3, V4) \
do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
void Verifier::visit(Instruction &I) {
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Assert1(I.getOperand(i) != nullptr, "Operand is null", &I);
InstVisitor<Verifier>::visit(I);
}
void Verifier::visitGlobalValue(const GlobalValue &GV) {
Assert1(!GV.isDeclaration() || GV.hasExternalLinkage() ||
GV.hasExternalWeakLinkage(),
"Global is external, but doesn't have external or weak linkage!",
&GV);
Assert1(GV.getAlignment() <= Value::MaximumAlignment,
"huge alignment values are unsupported", &GV);
Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
"Only global variables can have appending linkage!", &GV);
if (GV.hasAppendingLinkage()) {
const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
"Only global arrays can have appending linkage!", GVar);
}
}
void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
if (GV.hasInitializer()) {
Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
"Global variable initializer type does not match global "
"variable type!", &GV);
// If the global has common linkage, it must have a zero initializer and
// cannot be constant.
if (GV.hasCommonLinkage()) {
Assert1(GV.getInitializer()->isNullValue(),
"'common' global must have a zero initializer!", &GV);
Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
&GV);
Assert1(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
}
} else {
Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
"invalid linkage type for global declaration", &GV);
}
if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
GV.getName() == "llvm.global_dtors")) {
Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
"invalid linkage for intrinsic global variable", &GV);
// Don't worry about emitting an error for it not being an array,
// visitGlobalValue will complain on appending non-array.
if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
StructType *STy = dyn_cast<StructType>(ATy->getElementType());
PointerType *FuncPtrTy =
FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
// FIXME: Reject the 2-field form in LLVM 4.0.
Assert1(STy && (STy->getNumElements() == 2 ||
STy->getNumElements() == 3) &&
STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
STy->getTypeAtIndex(1) == FuncPtrTy,
"wrong type for intrinsic global variable", &GV);
if (STy->getNumElements() == 3) {
Type *ETy = STy->getTypeAtIndex(2);
Assert1(ETy->isPointerTy() &&
cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
"wrong type for intrinsic global variable", &GV);
}
}
}
if (GV.hasName() && (GV.getName() == "llvm.used" ||
GV.getName() == "llvm.compiler.used")) {
Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
"invalid linkage for intrinsic global variable", &GV);
Type *GVType = GV.getType()->getElementType();
if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
Assert1(PTy, "wrong type for intrinsic global variable", &GV);
if (GV.hasInitializer()) {
const Constant *Init = GV.getInitializer();
const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
Assert1(InitArray, "wrong initalizer for intrinsic global variable",
Init);
for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
Assert1(
isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
"invalid llvm.used member", V);
Assert1(V->hasName(), "members of llvm.used must be named", V);
}
}
}
}
Assert1(!GV.hasDLLImportStorageClass() ||
(GV.isDeclaration() && GV.hasExternalLinkage()) ||
GV.hasAvailableExternallyLinkage(),
"Global is marked as dllimport, but not external", &GV);
if (!GV.hasInitializer()) {
visitGlobalValue(GV);
return;
}
// Walk any aggregate initializers looking for bitcasts between address spaces
SmallPtrSet<const Value *, 4> Visited;
SmallVector<const Value *, 4> WorkStack;
WorkStack.push_back(cast<Value>(GV.getInitializer()));
while (!WorkStack.empty()) {
const Value *V = WorkStack.pop_back_val();
if (!Visited.insert(V).second)
continue;
if (const User *U = dyn_cast<User>(V)) {
for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
WorkStack.push_back(U->getOperand(I));
}
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
VerifyConstantExprBitcastType(CE);
if (Broken)
return;
}
}
visitGlobalValue(GV);
}
void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
SmallPtrSet<const GlobalAlias*, 4> Visited;
Visited.insert(&GA);
visitAliaseeSubExpr(Visited, GA, C);
}
void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
const GlobalAlias &GA, const Constant &C) {
if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
Assert1(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
Assert1(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
&GA);
} else {
// Only continue verifying subexpressions of GlobalAliases.
// Do not recurse into global initializers.
return;
}
}
if (const auto *CE = dyn_cast<ConstantExpr>(&C))
VerifyConstantExprBitcastType(CE);
for (const Use &U : C.operands()) {
Value *V = &*U;
if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
else if (const auto *C2 = dyn_cast<Constant>(V))
visitAliaseeSubExpr(Visited, GA, *C2);
}
}
void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
Assert1(!GA.getName().empty(),
"Alias name cannot be empty!", &GA);
Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
"Alias should have private, internal, linkonce, weak, linkonce_odr, "
"weak_odr, or external linkage!",
&GA);
const Constant *Aliasee = GA.getAliasee();
Assert1(Aliasee, "Aliasee cannot be NULL!", &GA);
Assert1(GA.getType() == Aliasee->getType(),
"Alias and aliasee types should match!", &GA);
Assert1(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
"Aliasee should be either GlobalValue or ConstantExpr", &GA);
visitAliaseeSubExpr(GA, *Aliasee);
visitGlobalValue(GA);
}
void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
MDNode *MD = NMD.getOperand(i);
if (!MD)
continue;
visitMDNode(*MD);
}
}
void Verifier::visitMDNode(MDNode &MD) {
// Only visit each node once. Metadata can be mutually recursive, so this
// avoids infinite recursion here, as well as being an optimization.
if (!MDNodes.insert(&MD).second)
return;
for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
Metadata *Op = MD.getOperand(i);
if (!Op)
continue;
Assert2(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
&MD, Op);
if (auto *N = dyn_cast<MDNode>(Op)) {
visitMDNode(*N);
continue;
}
if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
visitValueAsMetadata(*V, nullptr);
continue;
}
}
// Check these last, so we diagnose problems in operands first.
Assert1(!isa<MDNodeFwdDecl>(MD), "Expected no forward declarations!", &MD);
Assert1(MD.isResolved(), "All nodes should be resolved!", &MD);
}
void Verifier::visitValueAsMetadata(ValueAsMetadata &MD, Function *F) {
Assert1(MD.getValue(), "Expected valid value", &MD);
Assert2(!MD.getValue()->getType()->isMetadataTy(),
"Unexpected metadata round-trip through values", &MD, MD.getValue());
auto *L = dyn_cast<LocalAsMetadata>(&MD);
if (!L)
return;
Assert1(F, "function-local metadata used outside a function", L);
// If this was an instruction, bb, or argument, verify that it is in the
// function that we expect.
Function *ActualF = nullptr;
if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
Assert2(I->getParent(), "function-local metadata not in basic block", L, I);
ActualF = I->getParent()->getParent();
} else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
ActualF = BB->getParent();
else if (Argument *A = dyn_cast<Argument>(L->getValue()))
ActualF = A->getParent();
assert(ActualF && "Unimplemented function local metadata case!");
Assert1(ActualF == F, "function-local metadata used in wrong function", L);
}
void Verifier::visitMetadataAsValue(MetadataAsValue &MDV, Function *F) {
Metadata *MD = MDV.getMetadata();
if (auto *N = dyn_cast<MDNode>(MD)) {
visitMDNode(*N);
return;
}
// Only visit each node once. Metadata can be mutually recursive, so this
// avoids infinite recursion here, as well as being an optimization.
if (!MDNodes.insert(MD).second)
return;
if (auto *V = dyn_cast<ValueAsMetadata>(MD))
visitValueAsMetadata(*V, F);
}
void Verifier::visitComdat(const Comdat &C) {
// All Comdat::SelectionKind values other than Comdat::Any require a
// GlobalValue with the same name as the Comdat.
const GlobalValue *GV = M->getNamedValue(C.getName());
if (C.getSelectionKind() != Comdat::Any)
Assert1(GV,
"comdat selection kind requires a global value with the same name",
&C);
// The Module is invalid if the GlobalValue has private linkage. Entities
// with private linkage don't have entries in the symbol table.
if (GV)
Assert1(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
GV);
}
void Verifier::visitModuleIdents(const Module &M) {
const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
if (!Idents)
return;
// llvm.ident takes a list of metadata entry. Each entry has only one string.
// Scan each llvm.ident entry and make sure that this requirement is met.
for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
const MDNode *N = Idents->getOperand(i);
Assert1(N->getNumOperands() == 1,
"incorrect number of operands in llvm.ident metadata", N);
Assert1(isa<MDString>(N->getOperand(0)),
("invalid value for llvm.ident metadata entry operand"
"(the operand should be a string)"),
N->getOperand(0));
}
}
void Verifier::visitModuleFlags(const Module &M) {
const NamedMDNode *Flags = M.getModuleFlagsMetadata();
if (!Flags) return;
// Scan each flag, and track the flags and requirements.
DenseMap<const MDString*, const MDNode*> SeenIDs;
SmallVector<const MDNode*, 16> Requirements;
for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
}
// Validate that the requirements in the module are valid.
for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
const MDNode *Requirement = Requirements[I];
const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
const Metadata *ReqValue = Requirement->getOperand(1);
const MDNode *Op = SeenIDs.lookup(Flag);
if (!Op) {
CheckFailed("invalid requirement on flag, flag is not present in module",
Flag);
continue;
}
if (Op->getOperand(2) != ReqValue) {
CheckFailed(("invalid requirement on flag, "
"flag does not have the required value"),
Flag);
continue;
}
}
}
void
Verifier::visitModuleFlag(const MDNode *Op,
DenseMap<const MDString *, const MDNode *> &SeenIDs,
SmallVectorImpl<const MDNode *> &Requirements) {
// Each module flag should have three arguments, the merge behavior (a
// constant int), the flag ID (an MDString), and the value.
Assert1(Op->getNumOperands() == 3,
"incorrect number of operands in module flag", Op);
Module::ModFlagBehavior MFB;
if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
Assert1(
mdconst::dyn_extract<ConstantInt>(Op->getOperand(0)),
"invalid behavior operand in module flag (expected constant integer)",
Op->getOperand(0));
Assert1(false,
"invalid behavior operand in module flag (unexpected constant)",
Op->getOperand(0));
}
MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
Assert1(ID,
"invalid ID operand in module flag (expected metadata string)",
Op->getOperand(1));
// Sanity check the values for behaviors with additional requirements.
switch (MFB) {
case Module::Error:
case Module::Warning:
case Module::Override:
// These behavior types accept any value.
break;
case Module::Require: {
// The value should itself be an MDNode with two operands, a flag ID (an
// MDString), and a value.
MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
Assert1(Value && Value->getNumOperands() == 2,
"invalid value for 'require' module flag (expected metadata pair)",
Op->getOperand(2));
Assert1(isa<MDString>(Value->getOperand(0)),
("invalid value for 'require' module flag "
"(first value operand should be a string)"),
Value->getOperand(0));
// Append it to the list of requirements, to check once all module flags are
// scanned.
Requirements.push_back(Value);
break;
}
case Module::Append:
case Module::AppendUnique: {
// These behavior types require the operand be an MDNode.
Assert1(isa<MDNode>(Op->getOperand(2)),
"invalid value for 'append'-type module flag "
"(expected a metadata node)", Op->getOperand(2));
break;
}
}
// Unless this is a "requires" flag, check the ID is unique.
if (MFB != Module::Require) {
bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
Assert1(Inserted,
"module flag identifiers must be unique (or of 'require' type)",
ID);
}
}
void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
bool isFunction, const Value *V) {
unsigned Slot = ~0U;
for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
if (Attrs.getSlotIndex(I) == Idx) {
Slot = I;
break;
}
assert(Slot != ~0U && "Attribute set inconsistency!");
for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
I != E; ++I) {
if (I->isStringAttribute())
continue;
if (I->getKindAsEnum() == Attribute::NoReturn ||
I->getKindAsEnum() == Attribute::NoUnwind ||
I->getKindAsEnum() == Attribute::NoInline ||
I->getKindAsEnum() == Attribute::AlwaysInline ||
I->getKindAsEnum() == Attribute::OptimizeForSize ||
I->getKindAsEnum() == Attribute::StackProtect ||
I->getKindAsEnum() == Attribute::StackProtectReq ||
I->getKindAsEnum() == Attribute::StackProtectStrong ||
I->getKindAsEnum() == Attribute::NoRedZone ||
I->getKindAsEnum() == Attribute::NoImplicitFloat ||
I->getKindAsEnum() == Attribute::Naked ||
I->getKindAsEnum() == Attribute::InlineHint ||
I->getKindAsEnum() == Attribute::StackAlignment ||
I->getKindAsEnum() == Attribute::UWTable ||
I->getKindAsEnum() == Attribute::NonLazyBind ||
I->getKindAsEnum() == Attribute::ReturnsTwice ||
I->getKindAsEnum() == Attribute::SanitizeAddress ||
I->getKindAsEnum() == Attribute::SanitizeThread ||
I->getKindAsEnum() == Attribute::SanitizeMemory ||
I->getKindAsEnum() == Attribute::MinSize ||
I->getKindAsEnum() == Attribute::NoDuplicate ||
I->getKindAsEnum() == Attribute::Builtin ||
I->getKindAsEnum() == Attribute::NoBuiltin ||
I->getKindAsEnum() == Attribute::Cold ||
I->getKindAsEnum() == Attribute::OptimizeNone ||
I->getKindAsEnum() == Attribute::JumpTable) {
if (!isFunction) {
CheckFailed("Attribute '" + I->getAsString() +
"' only applies to functions!", V);
return;
}
} else if (I->getKindAsEnum() == Attribute::ReadOnly ||
I->getKindAsEnum() == Attribute::ReadNone) {
if (Idx == 0) {
CheckFailed("Attribute '" + I->getAsString() +
"' does not apply to function returns");
return;
}
} else if (isFunction) {
CheckFailed("Attribute '" + I->getAsString() +
"' does not apply to functions!", V);
return;
}
}
}
// VerifyParameterAttrs - Check the given attributes for an argument or return
// value of the specified type. The value V is printed in error messages.
void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
bool isReturnValue, const Value *V) {
if (!Attrs.hasAttributes(Idx))
return;
VerifyAttributeTypes(Attrs, Idx, false, V);
if (isReturnValue)
Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
!Attrs.hasAttribute(Idx, Attribute::Nest) &&
!Attrs.hasAttribute(Idx, Attribute::StructRet) &&
!Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
!Attrs.hasAttribute(Idx, Attribute::Returned) &&
!Attrs.hasAttribute(Idx, Attribute::InAlloca),
"Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
"'returned' do not apply to return values!", V);
// Check for mutually incompatible attributes. Only inreg is compatible with
// sret.
unsigned AttrCount = 0;
AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
Attrs.hasAttribute(Idx, Attribute::InReg);
AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
"and 'sret' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
"'inalloca and readonly' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
"'sret and returned' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
"'zeroext and signext' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
"'readnone and readonly' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
"'noinline and alwaysinline' are incompatible!", V);
Assert1(!AttrBuilder(Attrs, Idx).
hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
"Wrong types for attribute: " +
AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
if (!PTy->getElementType()->isSized()) {
Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
!Attrs.hasAttribute(Idx, Attribute::InAlloca),
"Attributes 'byval' and 'inalloca' do not support unsized types!",
V);
}
} else {
Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
"Attribute 'byval' only applies to parameters with pointer type!",
V);
}
}
// VerifyFunctionAttrs - Check parameter attributes against a function type.
// The value V is printed in error messages.
void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
const Value *V) {
if (Attrs.isEmpty())
return;
bool SawNest = false;
bool SawReturned = false;
bool SawSRet = false;
for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
unsigned Idx = Attrs.getSlotIndex(i);
Type *Ty;
if (Idx == 0)
Ty = FT->getReturnType();
else if (Idx-1 < FT->getNumParams())
Ty = FT->getParamType(Idx-1);
else
break; // VarArgs attributes, verified elsewhere.
VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
if (Idx == 0)
continue;
if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
Assert1(!SawNest, "More than one parameter has attribute nest!", V);
SawNest = true;
}
if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
Assert1(!SawReturned, "More than one parameter has attribute returned!",
V);
Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
"argument and return types for 'returned' attribute", V);
SawReturned = true;
}
if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
Assert1(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
Assert1(Idx == 1 || Idx == 2,
"Attribute 'sret' is not on first or second parameter!", V);
SawSRet = true;
}
if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
Assert1(Idx == FT->getNumParams(),
"inalloca isn't on the last parameter!", V);
}
}
if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
return;
VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::ReadNone) &&
Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::ReadOnly)),
"Attributes 'readnone and readonly' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::NoInline) &&
Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::AlwaysInline)),
"Attributes 'noinline and alwaysinline' are incompatible!", V);
if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::OptimizeNone)) {
Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::NoInline),
"Attribute 'optnone' requires 'noinline'!", V);
Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::OptimizeForSize),
"Attributes 'optsize and optnone' are incompatible!", V);
Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::MinSize),
"Attributes 'minsize and optnone' are incompatible!", V);
}
if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::JumpTable)) {
const GlobalValue *GV = cast<GlobalValue>(V);
Assert1(GV->hasUnnamedAddr(),
"Attribute 'jumptable' requires 'unnamed_addr'", V);
}
}
void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
if (CE->getOpcode() != Instruction::BitCast)
return;
Assert1(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
CE->getType()),
"Invalid bitcast", CE);
}
bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
if (Attrs.getNumSlots() == 0)
return true;
unsigned LastSlot = Attrs.getNumSlots() - 1;
unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
if (LastIndex <= Params
|| (LastIndex == AttributeSet::FunctionIndex
&& (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
return true;
return false;
}
// visitFunction - Verify that a function is ok.
//
void Verifier::visitFunction(const Function &F) {
// Check function arguments.
FunctionType *FT = F.getFunctionType();
unsigned NumArgs = F.arg_size();
Assert1(Context == &F.getContext(),
"Function context does not match Module context!", &F);
Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
Assert2(FT->getNumParams() == NumArgs,
"# formal arguments must match # of arguments for function type!",
&F, FT);
Assert1(F.getReturnType()->isFirstClassType() ||
F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
"Functions cannot return aggregate values!", &F);
Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
"Invalid struct return type!", &F);
AttributeSet Attrs = F.getAttributes();
Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
"Attribute after last parameter!", &F);
// Check function attributes.
VerifyFunctionAttrs(FT, Attrs, &F);
// On function declarations/definitions, we do not support the builtin
// attribute. We do not check this in VerifyFunctionAttrs since that is
// checking for Attributes that can/can not ever be on functions.
Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::Builtin),
"Attribute 'builtin' can only be applied to a callsite.", &F);
// Check that this function meets the restrictions on this calling convention.
// Sometimes varargs is used for perfectly forwarding thunks, so some of these
// restrictions can be lifted.
switch (F.getCallingConv()) {
default:
case CallingConv::C:
break;
case CallingConv::Fast:
case CallingConv::Cold:
case CallingConv::Intel_OCL_BI:
case CallingConv::PTX_Kernel:
case CallingConv::PTX_Device:
Assert1(!F.isVarArg(), "Calling convention does not support varargs or "
"perfect forwarding!", &F);
break;
}
bool isLLVMdotName = F.getName().size() >= 5 &&
F.getName().substr(0, 5) == "llvm.";
// Check that the argument values match the function type for this function...
unsigned i = 0;
for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
++I, ++i) {
Assert2(I->getType() == FT->getParamType(i),
"Argument value does not match function argument type!",
I, FT->getParamType(i));
Assert1(I->getType()->isFirstClassType(),
"Function arguments must have first-class types!", I);
if (!isLLVMdotName)
Assert2(!I->getType()->isMetadataTy(),
"Function takes metadata but isn't an intrinsic", I, &F);
}
if (F.isMaterializable()) {
// Function has a body somewhere we can't see.
} else if (F.isDeclaration()) {
Assert1(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
"invalid linkage type for function declaration", &F);
} else {
// Verify that this function (which has a body) is not named "llvm.*". It
// is not legal to define intrinsics.
Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
// Check the entry node
const BasicBlock *Entry = &F.getEntryBlock();
Assert1(pred_empty(Entry),
"Entry block to function must not have predecessors!", Entry);
// The address of the entry block cannot be taken, unless it is dead.
if (Entry->hasAddressTaken()) {
Assert1(!BlockAddress::lookup(Entry)->isConstantUsed(),
"blockaddress may not be used with the entry block!", Entry);
}
}
// If this function is actually an intrinsic, verify that it is only used in
// direct call/invokes, never having its "address taken".
if (F.getIntrinsicID()) {
const User *U;
if (F.hasAddressTaken(&U))
Assert1(0, "Invalid user of intrinsic instruction!", U);
}
Assert1(!F.hasDLLImportStorageClass() ||
(F.isDeclaration() && F.hasExternalLinkage()) ||
F.hasAvailableExternallyLinkage(),
"Function is marked as dllimport, but not external.", &F);
}
// verifyBasicBlock - Verify that a basic block is well formed...
//
void Verifier::visitBasicBlock(BasicBlock &BB) {
InstsInThisBlock.clear();
// Ensure that basic blocks have terminators!
Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
// Check constraints that this basic block imposes on all of the PHI nodes in
// it.
if (isa<PHINode>(BB.front())) {
SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
std::sort(Preds.begin(), Preds.end());
PHINode *PN;
for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
// Ensure that PHI nodes have at least one entry!
Assert1(PN->getNumIncomingValues() != 0,
"PHI nodes must have at least one entry. If the block is dead, "
"the PHI should be removed!", PN);
Assert1(PN->getNumIncomingValues() == Preds.size(),
"PHINode should have one entry for each predecessor of its "
"parent basic block!", PN);
// Get and sort all incoming values in the PHI node...
Values.clear();
Values.reserve(PN->getNumIncomingValues());
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Values.push_back(std::make_pair(PN->getIncomingBlock(i),
PN->getIncomingValue(i)));
std::sort(Values.begin(), Values.end());
for (unsigned i = 0, e = Values.size(); i != e; ++i) {
// Check to make sure that if there is more than one entry for a
// particular basic block in this PHI node, that the incoming values are
// all identical.
//
Assert4(i == 0 || Values[i].first != Values[i-1].first ||
Values[i].second == Values[i-1].second,
"PHI node has multiple entries for the same basic block with "
"different incoming values!", PN, Values[i].first,
Values[i].second, Values[i-1].second);
// Check to make sure that the predecessors and PHI node entries are
// matched up.
Assert3(Values[i].first == Preds[i],
"PHI node entries do not match predecessors!", PN,
Values[i].first, Preds[i]);
}
}
}
// Check that all instructions have their parent pointers set up correctly.
for (auto &I : BB)
{
Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
}
}
void Verifier::visitTerminatorInst(TerminatorInst &I) {
// Ensure that terminators only exist at the end of the basic block.
Assert1(&I == I.getParent()->getTerminator(),
"Terminator found in the middle of a basic block!", I.getParent());
visitInstruction(I);
}
void Verifier::visitBranchInst(BranchInst &BI) {
if (BI.isConditional()) {
Assert2(BI.getCondition()->getType()->isIntegerTy(1),
"Branch condition is not 'i1' type!", &BI, BI.getCondition());
}
visitTerminatorInst(BI);
}
void Verifier::visitReturnInst(ReturnInst &RI) {
Function *F = RI.getParent()->getParent();
unsigned N = RI.getNumOperands();
if (F->getReturnType()->isVoidTy())
Assert2(N == 0,
"Found return instr that returns non-void in Function of void "
"return type!", &RI, F->getReturnType());
else
Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
"Function return type does not match operand "
"type of return inst!", &RI, F->getReturnType());
// Check to make sure that the return value has necessary properties for
// terminators...
visitTerminatorInst(RI);
}
void Verifier::visitSwitchInst(SwitchInst &SI) {
// Check to make sure that all of the constants in the switch instruction
// have the same type as the switched-on value.
Type *SwitchTy = SI.getCondition()->getType();
SmallPtrSet<ConstantInt*, 32> Constants;
for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
Assert1(i.getCaseValue()->getType() == SwitchTy,
"Switch constants must all be same type as switch value!", &SI);
Assert2(Constants.insert(i.getCaseValue()).second,
"Duplicate integer as switch case", &SI, i.getCaseValue());
}
visitTerminatorInst(SI);
}
void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
Assert1(BI.getAddress()->getType()->isPointerTy(),
"Indirectbr operand must have pointer type!", &BI);
for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
Assert1(BI.getDestination(i)->getType()->isLabelTy(),
"Indirectbr destinations must all have pointer type!", &BI);
visitTerminatorInst(BI);
}
void Verifier::visitSelectInst(SelectInst &SI) {
Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
SI.getOperand(2)),
"Invalid operands for select instruction!", &SI);
Assert1(SI.getTrueValue()->getType() == SI.getType(),
"Select values must have same type as select instruction!", &SI);
visitInstruction(SI);
}
/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
/// a pass, if any exist, it's an error.
///
void Verifier::visitUserOp1(Instruction &I) {
Assert1(0, "User-defined operators should not live outside of a pass!", &I);
}
void Verifier::visitTruncInst(TruncInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
// Get the size of the types in bits, we'll need this later
unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
unsigned DestBitSize = DestTy->getScalarSizeInBits();
Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
"trunc source and destination must both be a vector or neither", &I);
Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
visitInstruction(I);
}
void Verifier::visitZExtInst(ZExtInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
// Get the size of the types in bits, we'll need this later
Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
"zext source and destination must both be a vector or neither", &I);
unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
unsigned DestBitSize = DestTy->getScalarSizeInBits();
Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
visitInstruction(I);
}
void Verifier::visitSExtInst(SExtInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
// Get the size of the types in bits, we'll need this later
unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
unsigned DestBitSize = DestTy->getScalarSizeInBits();
Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
"sext source and destination must both be a vector or neither", &I);
Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
visitInstruction(I);
}
void Verifier::visitFPTruncInst(FPTruncInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
// Get the size of the types in bits, we'll need this later
unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
unsigned DestBitSize = DestTy->getScalarSizeInBits();
Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
"fptrunc source and destination must both be a vector or neither",&I);
Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
visitInstruction(I);
}
void Verifier::visitFPExtInst(FPExtInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
// Get the size of the types in bits, we'll need this later
unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
unsigned DestBitSize = DestTy->getScalarSizeInBits();
Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
"fpext source and destination must both be a vector or neither", &I);
Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
visitInstruction(I);
}
void Verifier::visitUIToFPInst(UIToFPInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
bool SrcVec = SrcTy->isVectorTy();
bool DstVec = DestTy->isVectorTy();
Assert1(SrcVec == DstVec,
"UIToFP source and dest must both be vector or scalar", &I);
Assert1(SrcTy->isIntOrIntVectorTy(),
"UIToFP source must be integer or integer vector", &I);
Assert1(DestTy->isFPOrFPVectorTy(),
"UIToFP result must be FP or FP vector", &I);
if (SrcVec && DstVec)
Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
cast<VectorType>(DestTy)->getNumElements(),
"UIToFP source and dest vector length mismatch", &I);
visitInstruction(I);
}
void Verifier::visitSIToFPInst(SIToFPInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
bool SrcVec = SrcTy->isVectorTy();
bool DstVec = DestTy->isVectorTy();
Assert1(SrcVec == DstVec,
"SIToFP source and dest must both be vector or scalar", &I);
Assert1(SrcTy->isIntOrIntVectorTy(),
"SIToFP source must be integer or integer vector", &I);
Assert1(DestTy->isFPOrFPVectorTy(),
"SIToFP result must be FP or FP vector", &I);
if (SrcVec && DstVec)
Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
cast<VectorType>(DestTy)->getNumElements(),
"SIToFP source and dest vector length mismatch", &I);
visitInstruction(I);
}
void Verifier::visitFPToUIInst(FPToUIInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
bool SrcVec = SrcTy->isVectorTy();
bool DstVec = DestTy->isVectorTy();
Assert1(SrcVec == DstVec,
"FPToUI source and dest must both be vector or scalar", &I);
Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
&I);
Assert1(DestTy->isIntOrIntVectorTy(),
"FPToUI result must be integer or integer vector", &I);
if (SrcVec && DstVec)
Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
cast<VectorType>(DestTy)->getNumElements(),
"FPToUI source and dest vector length mismatch", &I);
visitInstruction(I);
}
void Verifier::visitFPToSIInst(FPToSIInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
bool SrcVec = SrcTy->isVectorTy();
bool DstVec = DestTy->isVectorTy();
Assert1(SrcVec == DstVec,
"FPToSI source and dest must both be vector or scalar", &I);
Assert1(SrcTy->isFPOrFPVectorTy(),
"FPToSI source must be FP or FP vector", &I);
Assert1(DestTy->isIntOrIntVectorTy(),
"FPToSI result must be integer or integer vector", &I);
if (SrcVec && DstVec)
Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
cast<VectorType>(DestTy)->getNumElements(),
"FPToSI source and dest vector length mismatch", &I);
visitInstruction(I);
}
void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
Assert1(SrcTy->getScalarType()->isPointerTy(),
"PtrToInt source must be pointer", &I);
Assert1(DestTy->getScalarType()->isIntegerTy(),
"PtrToInt result must be integral", &I);
Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
"PtrToInt type mismatch", &I);
if (SrcTy->isVectorTy()) {
VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
VectorType *VDest = dyn_cast<VectorType>(DestTy);
Assert1(VSrc->getNumElements() == VDest->getNumElements(),
"PtrToInt Vector width mismatch", &I);
}
visitInstruction(I);
}
void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
// Get the source and destination types
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
Assert1(SrcTy->getScalarType()->isIntegerTy(),
"IntToPtr source must be an integral", &I);
Assert1(DestTy->getScalarType()->isPointerTy(),
"IntToPtr result must be a pointer",&I);
Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
"IntToPtr type mismatch", &I);
if (SrcTy->isVectorTy()) {
VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
VectorType *VDest = dyn_cast<VectorType>(DestTy);
Assert1(VSrc->getNumElements() == VDest->getNumElements(),
"IntToPtr Vector width mismatch", &I);
}
visitInstruction(I);
}
void Verifier::visitBitCastInst(BitCastInst &I) {
Assert1(
CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
"Invalid bitcast", &I);
visitInstruction(I);
}
void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
Type *SrcTy = I.getOperand(0)->getType();
Type *DestTy = I.getType();
Assert1(SrcTy->isPtrOrPtrVectorTy(),
"AddrSpaceCast source must be a pointer", &I);
Assert1(DestTy->isPtrOrPtrVectorTy(),
"AddrSpaceCast result must be a pointer", &I);
Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
"AddrSpaceCast must be between different address spaces", &I);
if (SrcTy->isVectorTy())
Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
"AddrSpaceCast vector pointer number of elements mismatch", &I);
visitInstruction(I);
}
/// visitPHINode - Ensure that a PHI node is well formed.
///
void Verifier::visitPHINode(PHINode &PN) {
// Ensure that the PHI nodes are all grouped together at the top of the block.
// This can be tested by checking whether the instruction before this is
// either nonexistent (because this is begin()) or is a PHI node. If not,
// then there is some other instruction before a PHI.
Assert2(&PN == &PN.getParent()->front() ||
isa<PHINode>(--BasicBlock::iterator(&PN)),
"PHI nodes not grouped at top of basic block!",
&PN, PN.getParent());
// Check that all of the values of the PHI node have the same type as the
// result, and that the incoming blocks are really basic blocks.
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
"PHI node operands are not the same type as the result!", &PN);
}
// All other PHI node constraints are checked in the visitBasicBlock method.
visitInstruction(PN);
}
void Verifier::VerifyCallSite(CallSite CS) {
Instruction *I = CS.getInstruction();
Assert1(CS.getCalledValue()->getType()->isPointerTy(),
"Called function must be a pointer!", I);
PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
Assert1(FPTy->getElementType()->isFunctionTy(),
"Called function is not pointer to function type!", I);
FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
// Verify that the correct number of arguments are being passed
if (FTy->isVarArg())
Assert1(CS.arg_size() >= FTy->getNumParams(),
"Called function requires more parameters than were provided!",I);
else
Assert1(CS.arg_size() == FTy->getNumParams(),
"Incorrect number of arguments passed to called function!", I);
// Verify that all arguments to the call match the function type.
for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
"Call parameter type does not match function signature!",
CS.getArgument(i), FTy->getParamType(i), I);
AttributeSet Attrs = CS.getAttributes();
Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
"Attribute after last parameter!", I);
// Verify call attributes.
VerifyFunctionAttrs(FTy, Attrs, I);
// Conservatively check the inalloca argument.
// We have a bug if we can find that there is an underlying alloca without
// inalloca.
if (CS.hasInAllocaArgument()) {
Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
Assert2(AI->isUsedWithInAlloca(),
"inalloca argument for call has mismatched alloca", AI, I);
}
if (FTy->isVarArg()) {
// FIXME? is 'nest' even legal here?
bool SawNest = false;
bool SawReturned = false;
for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
if (Attrs.hasAttribute(Idx, Attribute::Nest))
SawNest = true;
if (Attrs.hasAttribute(Idx, Attribute::Returned))
SawReturned = true;
}
// Check attributes on the varargs part.
for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
Type *Ty = CS.getArgument(Idx-1)->getType();
VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
Assert1(!SawNest, "More than one parameter has attribute nest!", I);
SawNest = true;
}
if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
Assert1(!SawReturned, "More than one parameter has attribute returned!",
I);
Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
"Incompatible argument and return types for 'returned' "
"attribute", I);
SawReturned = true;
}
Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
"Attribute 'sret' cannot be used for vararg call arguments!", I);
if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!",
I);
}
}
// Verify that there's no metadata unless it's a direct call to an intrinsic.
if (CS.getCalledFunction() == nullptr ||
!CS.getCalledFunction()->getName().startswith("llvm.")) {
for (FunctionType::param_iterator PI = FTy->param_begin(),
PE = FTy->param_end(); PI != PE; ++PI)
Assert1(!(*PI)->isMetadataTy(),
"Function has metadata parameter but isn't an intrinsic", I);
}
visitInstruction(*I);
}
/// Two types are "congruent" if they are identical, or if they are both pointer
/// types with different pointee types and the same address space.
static bool isTypeCongruent(Type *L, Type *R) {
if (L == R)
return true;
PointerType *PL = dyn_cast<PointerType>(L);
PointerType *PR = dyn_cast<PointerType>(R);
if (!PL || !PR)
return false;
return PL->getAddressSpace() == PR->getAddressSpace();
}
static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
static const Attribute::AttrKind ABIAttrs[] = {
Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
Attribute::InReg, Attribute::Returned};
AttrBuilder Copy;
for (auto AK : ABIAttrs) {
if (Attrs.hasAttribute(I + 1, AK))
Copy.addAttribute(AK);
}
if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
return Copy;
}
void Verifier::verifyMustTailCall(CallInst &CI) {
Assert1(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
// - The caller and callee prototypes must match. Pointer types of
// parameters or return types may differ in pointee type, but not
// address space.
Function *F = CI.getParent()->getParent();
auto GetFnTy = [](Value *V) {
return cast<FunctionType>(
cast<PointerType>(V->getType())->getElementType());
};
FunctionType *CallerTy = GetFnTy(F);
FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
Assert1(CallerTy->getNumParams() == CalleeTy->getNumParams(),
"cannot guarantee tail call due to mismatched parameter counts", &CI);
Assert1(CallerTy->isVarArg() == CalleeTy->isVarArg(),
"cannot guarantee tail call due to mismatched varargs", &CI);
Assert1(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
"cannot guarantee tail call due to mismatched return types", &CI);
for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
Assert1(
isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
"cannot guarantee tail call due to mismatched parameter types", &CI);
}
// - The calling conventions of the caller and callee must match.
Assert1(F->getCallingConv() == CI.getCallingConv(),
"cannot guarantee tail call due to mismatched calling conv", &CI);
// - All ABI-impacting function attributes, such as sret, byval, inreg,
// returned, and inalloca, must match.
AttributeSet CallerAttrs = F->getAttributes();
AttributeSet CalleeAttrs = CI.getAttributes();
for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
Assert2(CallerABIAttrs == CalleeABIAttrs,
"cannot guarantee tail call due to mismatched ABI impacting "
"function attributes", &CI, CI.getOperand(I));
}
// - The call must immediately precede a :ref:`ret <i_ret>` instruction,
// or a pointer bitcast followed by a ret instruction.
// - The ret instruction must return the (possibly bitcasted) value
// produced by the call or void.
Value *RetVal = &CI;
Instruction *Next = CI.getNextNode();
// Handle the optional bitcast.
if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
Assert1(BI->getOperand(0) == RetVal,
"bitcast following musttail call must use the call", BI);
RetVal = BI;
Next = BI->getNextNode();
}
// Check the return.
ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
Assert1(Ret, "musttail call must be precede a ret with an optional bitcast",
&CI);
Assert1(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
"musttail call result must be returned", Ret);
}
void Verifier::visitCallInst(CallInst &CI) {
VerifyCallSite(&CI);
if (CI.isMustTailCall())
verifyMustTailCall(CI);
if (Function *F = CI.getCalledFunction())
if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
visitIntrinsicFunctionCall(ID, CI);
}
void Verifier::visitInvokeInst(InvokeInst &II) {
VerifyCallSite(&II);
// Verify that there is a landingpad instruction as the first non-PHI
// instruction of the 'unwind' destination.
Assert1(II.getUnwindDest()->isLandingPad(),
"The unwind destination does not have a landingpad instruction!",&II);
visitTerminatorInst(II);
}
/// visitBinaryOperator - Check that both arguments to the binary operator are
/// of the same type!
///
void Verifier::visitBinaryOperator(BinaryOperator &B) {
Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
"Both operands to a binary operator are not of the same type!", &B);
switch (B.getOpcode()) {
// Check that integer arithmetic operators are only used with
// integral operands.
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::SDiv:
case Instruction::UDiv:
case Instruction::SRem:
case Instruction::URem:
Assert1(B.getType()->isIntOrIntVectorTy(),
"Integer arithmetic operators only work with integral types!", &B);
Assert1(B.getType() == B.getOperand(0)->getType(),
"Integer arithmetic operators must have same type "
"for operands and result!", &B);
break;
// Check that floating-point arithmetic operators are only used with
// floating-point operands.
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
case Instruction::FDiv:
case Instruction::FRem:
Assert1(B.getType()->isFPOrFPVectorTy(),
"Floating-point arithmetic operators only work with "
"floating-point types!", &B);
Assert1(B.getType() == B.getOperand(0)->getType(),
"Floating-point arithmetic operators must have same type "
"for operands and result!", &B);
break;
// Check that logical operators are only used with integral operands.
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
Assert1(B.getType()->isIntOrIntVectorTy(),
"Logical operators only work with integral types!", &B);
Assert1(B.getType() == B.getOperand(0)->getType(),
"Logical operators must have same type for operands and result!",
&B);
break;
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
Assert1(B.getType()->isIntOrIntVectorTy(),
"Shifts only work with integral types!", &B);
Assert1(B.getType() == B.getOperand(0)->getType(),
"Shift return type must be same as operands!", &B);
break;
default:
llvm_unreachable("Unknown BinaryOperator opcode!");
}
visitInstruction(B);
}
void Verifier::visitICmpInst(ICmpInst &IC) {
// Check that the operands are the same type
Type *Op0Ty = IC.getOperand(0)->getType();
Type *Op1Ty = IC.getOperand(1)->getType();
Assert1(Op0Ty == Op1Ty,
"Both operands to ICmp instruction are not of the same type!", &IC);
// Check that the operands are the right type
Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
"Invalid operand types for ICmp instruction", &IC);
// Check that the predicate is valid.
Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
"Invalid predicate in ICmp instruction!", &IC);
visitInstruction(IC);
}
void Verifier::visitFCmpInst(FCmpInst &FC) {
// Check that the operands are the same type
Type *Op0Ty = FC.getOperand(0)->getType();
Type *Op1Ty = FC.getOperand(1)->getType();
Assert1(Op0Ty == Op1Ty,
"Both operands to FCmp instruction are not of the same type!", &FC);
// Check that the operands are the right type
Assert1(Op0Ty->isFPOrFPVectorTy(),
"Invalid operand types for FCmp instruction", &FC);
// Check that the predicate is valid.
Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
"Invalid predicate in FCmp instruction!", &FC);
visitInstruction(FC);
}
void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
EI.getOperand(1)),
"Invalid extractelement operands!", &EI);
visitInstruction(EI);
}
void Verifier::visitInsertElementInst(InsertElementInst &IE) {
Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
IE.getOperand(1),
IE.getOperand(2)),
"Invalid insertelement operands!", &IE);
visitInstruction(IE);
}
void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
SV.getOperand(2)),
"Invalid shufflevector operands!", &SV);
visitInstruction(SV);
}
void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
Assert1(isa<PointerType>(TargetTy),
"GEP base pointer is not a vector or a vector of pointers", &GEP);
Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
"GEP into unsized type!", &GEP);
Assert1(GEP.getPointerOperandType()->isVectorTy() ==
GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
&GEP);
SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
Type *ElTy =
GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
== ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
if (GEP.getPointerOperandType()->isVectorTy()) {
// Additional checks for vector GEPs.
unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
"Vector GEP result width doesn't match operand's", &GEP);
for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Type *IndexTy = Idxs[i]->getType();
Assert1(IndexTy->isVectorTy(),
"Vector GEP must have vector indices!", &GEP);
unsigned IndexWidth = IndexTy->getVectorNumElements();
Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
}
}
visitInstruction(GEP);
}
static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
}
void Verifier::visitRangeMetadata(Instruction& I,
MDNode* Range, Type* Ty) {
assert(Range &&
Range == I.getMetadata(LLVMContext::MD_range) &&
"precondition violation");
unsigned NumOperands = Range->getNumOperands();
Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
unsigned NumRanges = NumOperands / 2;
Assert1(NumRanges >= 1, "It should have at least one range!", Range);
ConstantRange LastRange(1); // Dummy initial value
for (unsigned i = 0; i < NumRanges; ++i) {
ConstantInt *Low =
mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
Assert1(Low, "The lower limit must be an integer!", Low);
ConstantInt *High =
mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
Assert1(High, "The upper limit must be an integer!", High);
Assert1(High->getType() == Low->getType() &&
High->getType() == Ty, "Range types must match instruction type!",
&I);
APInt HighV = High->getValue();
APInt LowV = Low->getValue();
ConstantRange CurRange(LowV, HighV);
Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
"Range must not be empty!", Range);
if (i != 0) {
Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
"Intervals are overlapping", Range);
Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
Range);
Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
Range);
}
LastRange = ConstantRange(LowV, HighV);
}
if (NumRanges > 2) {
APInt FirstLow =
mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
APInt FirstHigh =
mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
ConstantRange FirstRange(FirstLow, FirstHigh);
Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
"Intervals are overlapping", Range);
Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
Range);
}
}
void Verifier::visitLoadInst(LoadInst &LI) {
PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
Assert1(PTy, "Load operand must be a pointer.", &LI);
Type *ElTy = PTy->getElementType();
Assert2(ElTy == LI.getType(),
"Load result type does not match pointer operand type!", &LI, ElTy);
Assert1(LI.getAlignment() <= Value::MaximumAlignment,
"huge alignment values are unsupported", &LI);
if (LI.isAtomic()) {
Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
"Load cannot have Release ordering", &LI);
Assert1(LI.getAlignment() != 0,
"Atomic load must specify explicit alignment", &LI);
if (!ElTy->isPointerTy()) {
Assert2(ElTy->isIntegerTy(),
"atomic load operand must have integer type!",
&LI, ElTy);
unsigned Size = ElTy->getPrimitiveSizeInBits();
Assert2(Size >= 8 && !(Size & (Size - 1)),
"atomic load operand must be power-of-two byte-sized integer",
&LI, ElTy);
}
} else {
Assert1(LI.getSynchScope() == CrossThread,
"Non-atomic load cannot have SynchronizationScope specified", &LI);
}
visitInstruction(LI);
}
void Verifier::visitStoreInst(StoreInst &SI) {
PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
Assert1(PTy, "Store operand must be a pointer.", &SI);
Type *ElTy = PTy->getElementType();
Assert2(ElTy == SI.getOperand(0)->getType(),
"Stored value type does not match pointer operand type!",
&SI, ElTy);
Assert1(SI.getAlignment() <= Value::MaximumAlignment,
"huge alignment values are unsupported", &SI);
if (SI.isAtomic()) {
Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
"Store cannot have Acquire ordering", &SI);
Assert1(SI.getAlignment() != 0,
"Atomic store must specify explicit alignment", &SI);
if (!ElTy->isPointerTy()) {
Assert2(ElTy->isIntegerTy(),
"atomic store operand must have integer type!",
&SI, ElTy);
unsigned Size = ElTy->getPrimitiveSizeInBits();
Assert2(Size >= 8 && !(Size & (Size - 1)),
"atomic store operand must be power-of-two byte-sized integer",
&SI, ElTy);
}
} else {
Assert1(SI.getSynchScope() == CrossThread,
"Non-atomic store cannot have SynchronizationScope specified", &SI);
}
visitInstruction(SI);
}
void Verifier::visitAllocaInst(AllocaInst &AI) {
SmallPtrSet<const Type*, 4> Visited;
PointerType *PTy = AI.getType();
Assert1(PTy->getAddressSpace() == 0,
"Allocation instruction pointer not in the generic address space!",
&AI);
Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
&AI);
Assert1(AI.getArraySize()->getType()->isIntegerTy(),
"Alloca array size must have integer type", &AI);
Assert1(AI.getAlignment() <= Value::MaximumAlignment,
"huge alignment values are unsupported", &AI);
visitInstruction(AI);
}
void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
// FIXME: more conditions???
Assert1(CXI.getSuccessOrdering() != NotAtomic,
"cmpxchg instructions must be atomic.", &CXI);
Assert1(CXI.getFailureOrdering() != NotAtomic,
"cmpxchg instructions must be atomic.", &CXI);
Assert1(CXI.getSuccessOrdering() != Unordered,
"cmpxchg instructions cannot be unordered.", &CXI);
Assert1(CXI.getFailureOrdering() != Unordered,
"cmpxchg instructions cannot be unordered.", &CXI);
Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
"cmpxchg instructions be at least as constrained on success as fail",
&CXI);
Assert1(CXI.getFailureOrdering() != Release &&
CXI.getFailureOrdering() != AcquireRelease,
"cmpxchg failure ordering cannot include release semantics", &CXI);
PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
Type *ElTy = PTy->getElementType();
Assert2(ElTy->isIntegerTy(),
"cmpxchg operand must have integer type!",
&CXI, ElTy);
unsigned Size = ElTy->getPrimitiveSizeInBits();
Assert2(Size >= 8 && !(Size & (Size - 1)),
"cmpxchg operand must be power-of-two byte-sized integer",
&CXI, ElTy);
Assert2(ElTy == CXI.getOperand(1)->getType(),
"Expected value type does not match pointer operand type!",
&CXI, ElTy);
Assert2(ElTy == CXI.getOperand(2)->getType(),
"Stored value type does not match pointer operand type!",
&CXI, ElTy);
visitInstruction(CXI);
}
void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
Assert1(RMWI.getOrdering() != NotAtomic,
"atomicrmw instructions must be atomic.", &RMWI);
Assert1(RMWI.getOrdering() != Unordered,
"atomicrmw instructions cannot be unordered.", &RMWI);
PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
Type *ElTy = PTy->getElementType();
Assert2(ElTy->isIntegerTy(),
"atomicrmw operand must have integer type!",
&RMWI, ElTy);
unsigned Size = ElTy->getPrimitiveSizeInBits();
Assert2(Size >= 8 && !(Size & (Size - 1)),
"atomicrmw operand must be power-of-two byte-sized integer",
&RMWI, ElTy);
Assert2(ElTy == RMWI.getOperand(1)->getType(),
"Argument value type does not match pointer operand type!",
&RMWI, ElTy);
Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
"Invalid binary operation!", &RMWI);
visitInstruction(RMWI);
}
void Verifier::visitFenceInst(FenceInst &FI) {
const AtomicOrdering Ordering = FI.getOrdering();
Assert1(Ordering == Acquire || Ordering == Release ||
Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
"fence instructions may only have "
"acquire, release, acq_rel, or seq_cst ordering.", &FI);
visitInstruction(FI);
}
void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
EVI.getIndices()) ==
EVI.getType(),
"Invalid ExtractValueInst operands!", &EVI);
visitInstruction(EVI);
}
void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
IVI.getIndices()) ==
IVI.getOperand(1)->getType(),
"Invalid InsertValueInst operands!", &IVI);
visitInstruction(IVI);
}
void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
BasicBlock *BB = LPI.getParent();
// The landingpad instruction is ill-formed if it doesn't have any clauses and
// isn't a cleanup.
Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
"LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
// The landingpad instruction defines its parent as a landing pad block. The
// landing pad block may be branched to only by the unwind edge of an invoke.
for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
"Block containing LandingPadInst must be jumped to "
"only by the unwind edge of an invoke.", &LPI);
}
// The landingpad instruction must be the first non-PHI instruction in the
// block.
Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
"LandingPadInst not the first non-PHI instruction in the block.",
&LPI);
// The personality functions for all landingpad instructions within the same
// function should match.
if (PersonalityFn)
Assert1(LPI.getPersonalityFn() == PersonalityFn,
"Personality function doesn't match others in function", &LPI);
PersonalityFn = LPI.getPersonalityFn();
// All operands must be constants.
Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
&LPI);
for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
Constant *Clause = LPI.getClause(i);
if (LPI.isCatch(i)) {
Assert1(isa<PointerType>(Clause->getType()),
"Catch operand does not have pointer type!", &LPI);
} else {
Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
"Filter operand is not an array of constants!", &LPI);
}
}
visitInstruction(LPI);
}
void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
Instruction *Op = cast<Instruction>(I.getOperand(i));
// If the we have an invalid invoke, don't try to compute the dominance.
// We already reject it in the invoke specific checks and the dominance
// computation doesn't handle multiple edges.
if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
if (II->getNormalDest() == II->getUnwindDest())
return;
}
const Use &U = I.getOperandUse(i);
Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
"Instruction does not dominate all uses!", Op, &I);
}
/// verifyInstruction - Verify that an instruction is well formed.
///
void Verifier::visitInstruction(Instruction &I) {
BasicBlock *BB = I.getParent();
Assert1(BB, "Instruction not embedded in basic block!", &I);
if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
for (User *U : I.users()) {
Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB),
"Only PHI nodes may reference their own value!", &I);
}
}
// Check that void typed values don't have names
Assert1(!I.getType()->isVoidTy() || !I.hasName(),
"Instruction has a name, but provides a void value!", &I);
// Check that the return value of the instruction is either void or a legal
// value type.
Assert1(I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
"Instruction returns a non-scalar type!", &I);
// Check that the instruction doesn't produce metadata. Calls are already
// checked against the callee type.
Assert1(!I.getType()->isMetadataTy() ||
isa<CallInst>(I) || isa<InvokeInst>(I),
"Invalid use of metadata!", &I);
// Check that all uses of the instruction, if they are instructions
// themselves, actually have parent basic blocks. If the use is not an
// instruction, it is an error!
for (Use &U : I.uses()) {
if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
Assert2(Used->getParent() != nullptr, "Instruction referencing"
" instruction not embedded in a basic block!", &I, Used);
else {
CheckFailed("Use of instruction is not an instruction!", U);
return;
}
}
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Assert1(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
// Check to make sure that only first-class-values are operands to
// instructions.
if (!I.getOperand(i)->getType()->isFirstClassType()) {
Assert1(0, "Instruction operands must be first-class values!", &I);
}
if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
// Check to make sure that the "address of" an intrinsic function is never
// taken.
Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 :
isa<InvokeInst>(I) ? e-3 : 0),
"Cannot take the address of an intrinsic!", &I);
Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
F->getIntrinsicID() == Intrinsic::donothing ||
F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64,
"Cannot invoke an intrinsinc other than"
" donothing or patchpoint", &I);
Assert1(F->getParent() == M, "Referencing function in another module!",
&I);
} else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
Assert1(OpBB->getParent() == BB->getParent(),
"Referring to a basic block in another function!", &I);
} else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
Assert1(OpArg->getParent() == BB->getParent(),
"Referring to an argument in another function!", &I);
} else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
Assert1(GV->getParent() == M, "Referencing global in another module!",
&I);
} else if (isa<Instruction>(I.getOperand(i))) {
verifyDominatesUse(I, i);
} else if (isa<InlineAsm>(I.getOperand(i))) {
Assert1((i + 1 == e && isa<CallInst>(I)) ||
(i + 3 == e && isa<InvokeInst>(I)),
"Cannot take the address of an inline asm!", &I);
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
if (CE->getType()->isPtrOrPtrVectorTy()) {
// If we have a ConstantExpr pointer, we need to see if it came from an
// illegal bitcast (inttoptr <constant int> )
SmallVector<const ConstantExpr *, 4> Stack;
SmallPtrSet<const ConstantExpr *, 4> Visited;
Stack.push_back(CE);
while (!Stack.empty()) {
const ConstantExpr *V = Stack.pop_back_val();
if (!Visited.insert(V).second)
continue;
VerifyConstantExprBitcastType(V);
for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
Stack.push_back(Op);
}
}
}
}
}
if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
Assert1(I.getType()->isFPOrFPVectorTy(),
"fpmath requires a floating point result!", &I);
Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
if (ConstantFP *CFP0 =
mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
APFloat Accuracy = CFP0->getValueAPF();
Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
"fpmath accuracy not a positive number!", &I);
} else {
Assert1(false, "invalid fpmath accuracy!", &I);
}
}
if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
Assert1(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
"Ranges are only for loads, calls and invokes!", &I);
visitRangeMetadata(I, Range, I.getType());
}
if (I.getMetadata(LLVMContext::MD_nonnull)) {
Assert1(I.getType()->isPointerTy(),
"nonnull applies only to pointer types", &I);
Assert1(isa<LoadInst>(I),
"nonnull applies only to load instructions, use attributes"
" for calls or invokes", &I);
}
InstsInThisBlock.insert(&I);
}
/// VerifyIntrinsicType - Verify that the specified type (which comes from an
/// intrinsic argument or return value) matches the type constraints specified
/// by the .td file (e.g. an "any integer" argument really is an integer).
///
/// This return true on error but does not print a message.
bool Verifier::VerifyIntrinsicType(Type *Ty,
ArrayRef<Intrinsic::IITDescriptor> &Infos,
SmallVectorImpl<Type*> &ArgTys) {
using namespace Intrinsic;
// If we ran out of descriptors, there are too many arguments.
if (Infos.empty()) return true;
IITDescriptor D = Infos.front();
Infos = Infos.slice(1);
switch (D.Kind) {
case IITDescriptor::Void: return !Ty->isVoidTy();
case IITDescriptor::VarArg: return true;
case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
case IITDescriptor::Metadata: return !Ty->isMetadataTy();
case IITDescriptor::Half: return !Ty->isHalfTy();
case IITDescriptor::Float: return !Ty->isFloatTy();
case IITDescriptor::Double: return !Ty->isDoubleTy();
case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
case IITDescriptor::Vector: {
VectorType *VT = dyn_cast<VectorType>(Ty);
return !VT || VT->getNumElements() != D.Vector_Width ||
VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
}
case IITDescriptor::Pointer: {
PointerType *PT = dyn_cast<PointerType>(Ty);
return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
}
case IITDescriptor::Struct: {
StructType *ST = dyn_cast<StructType>(Ty);
if (!ST || ST->getNumElements() != D.Struct_NumElements)
return true;
for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
return true;
return false;
}
case IITDescriptor::Argument:
// Two cases here - If this is the second occurrence of an argument, verify
// that the later instance matches the previous instance.
if (D.getArgumentNumber() < ArgTys.size())
return Ty != ArgTys[D.getArgumentNumber()];
// Otherwise, if this is the first instance of an argument, record it and
// verify the "Any" kind.
assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
ArgTys.push_back(Ty);
switch (D.getArgumentKind()) {
case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
}
llvm_unreachable("all argument kinds not covered");
case IITDescriptor::ExtendArgument: {
// This may only be used when referring to a previous vector argument.
if (D.getArgumentNumber() >= ArgTys.size())
return true;
Type *NewTy = ArgTys[D.getArgumentNumber()];
if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
NewTy = VectorType::getExtendedElementVectorType(VTy);
else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
else
return true;
return Ty != NewTy;
}
case IITDescriptor::TruncArgument: {
// This may only be used when referring to a previous vector argument.
if (D.getArgumentNumber() >= ArgTys.size())
return true;
Type *NewTy = ArgTys[D.getArgumentNumber()];
if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
NewTy = VectorType::getTruncatedElementVectorType(VTy);
else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
else
return true;
return Ty != NewTy;
}
case IITDescriptor::HalfVecArgument:
// This may only be used when referring to a previous vector argument.
return D.getArgumentNumber() >= ArgTys.size() ||
!isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
VectorType::getHalfElementsVectorType(
cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
case IITDescriptor::SameVecWidthArgument: {
if (D.getArgumentNumber() >= ArgTys.size())
return true;
VectorType * ReferenceType =
dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
if (!ThisArgType || !ReferenceType ||
(ReferenceType->getVectorNumElements() !=
ThisArgType->getVectorNumElements()))
return true;
return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
Infos, ArgTys);
}
case IITDescriptor::PtrToArgument: {
if (D.getArgumentNumber() >= ArgTys.size())
return true;
Type * ReferenceType = ArgTys[D.getArgumentNumber()];
PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
}
}
llvm_unreachable("unhandled");
}
/// \brief Verify if the intrinsic has variable arguments.
/// This method is intended to be called after all the fixed arguments have been
/// verified first.
///
/// This method returns true on error and does not print an error message.
bool
Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
ArrayRef<Intrinsic::IITDescriptor> &Infos) {
using namespace Intrinsic;
// If there are no descriptors left, then it can't be a vararg.
if (Infos.empty())
return isVarArg ? true : false;
// There should be only one descriptor remaining at this point.
if (Infos.size() != 1)
return true;
// Check and verify the descriptor.
IITDescriptor D = Infos.front();
Infos = Infos.slice(1);
if (D.Kind == IITDescriptor::VarArg)
return isVarArg ? false : true;
return true;
}
/// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
///
void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
Function *IF = CI.getCalledFunction();
Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
IF);
// Verify that the intrinsic prototype lines up with what the .td files
// describe.
FunctionType *IFTy = IF->getFunctionType();
bool IsVarArg = IFTy->isVarArg();
SmallVector<Intrinsic::IITDescriptor, 8> Table;
getIntrinsicInfoTableEntries(ID, Table);
ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
SmallVector<Type *, 4> ArgTys;
Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
"Intrinsic has incorrect return type!", IF);
for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
"Intrinsic has incorrect argument type!", IF);
// Verify if the intrinsic call matches the vararg property.
if (IsVarArg)
Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
"Intrinsic was not defined with variable arguments!", IF);
else
Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
"Callsite was not defined with variable arguments!", IF);
// All descriptors should be absorbed by now.
Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
// Now that we have the intrinsic ID and the actual argument types (and we
// know they are legal for the intrinsic!) get the intrinsic name through the
// usual means. This allows us to verify the mangling of argument types into
// the name.
const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
Assert1(ExpectedName == IF->getName(),
"Intrinsic name not mangled correctly for type arguments! "
"Should be: " + ExpectedName, IF);
// If the intrinsic takes MDNode arguments, verify that they are either global
// or are local to *this* function.
for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
visitMetadataAsValue(*MD, CI.getParent()->getParent());
switch (ID) {
default:
break;
case Intrinsic::ctlz: // llvm.ctlz
case Intrinsic::cttz: // llvm.cttz
Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
"is_zero_undef argument of bit counting intrinsics must be a "
"constant int", &CI);
break;
case Intrinsic::dbg_declare: { // llvm.dbg.declare
Assert1(CI.getArgOperand(0) && isa<MetadataAsValue>(CI.getArgOperand(0)),
"invalid llvm.dbg.declare intrinsic call 1", &CI);
} break;
case Intrinsic::memcpy:
case Intrinsic::memmove:
case Intrinsic::memset:
Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
"alignment argument of memory intrinsics must be a constant int",
&CI);
Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
"isvolatile argument of memory intrinsics must be a constant int",
&CI);
break;
case Intrinsic::gcroot:
case Intrinsic::gcwrite:
case Intrinsic::gcread:
if (ID == Intrinsic::gcroot) {
AllocaInst *AI =
dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
Assert1(isa<Constant>(CI.getArgOperand(1)),
"llvm.gcroot parameter #2 must be a constant.", &CI);
if (!AI->getType()->getElementType()->isPointerTy()) {
Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
"llvm.gcroot parameter #1 must either be a pointer alloca, "
"or argument #2 must be a non-null constant.", &CI);
}
}
Assert1(CI.getParent()->getParent()->hasGC(),
"Enclosing function does not use GC.", &CI);
break;
case Intrinsic::init_trampoline:
Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
"llvm.init_trampoline parameter #2 must resolve to a function.",
&CI);
break;
case Intrinsic::prefetch:
Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
isa<ConstantInt>(CI.getArgOperand(2)) &&
cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
"invalid arguments to llvm.prefetch",
&CI);
break;
case Intrinsic::stackprotector:
Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
"llvm.stackprotector parameter #2 must resolve to an alloca.",
&CI);
break;
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
case Intrinsic::invariant_start:
Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
"size argument of memory use markers must be a constant integer",
&CI);
break;
case Intrinsic::invariant_end:
Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
"llvm.invariant.end parameter #2 must be a constant integer", &CI);
break;
case Intrinsic::frameallocate: {
BasicBlock *BB = CI.getParent();
Assert1(BB == &BB->getParent()->front(),
"llvm.frameallocate used outside of entry block", &CI);
Assert1(!SawFrameAllocate,
"multiple calls to llvm.frameallocate in one function", &CI);
SawFrameAllocate = true;
Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
"llvm.frameallocate argument must be constant integer size", &CI);
break;
}
case Intrinsic::framerecover: {
Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
Function *Fn = dyn_cast<Function>(FnArg);
Assert1(Fn && !Fn->isDeclaration(), "llvm.framerecover first "
"argument must be function defined in this module", &CI);
break;
}
case Intrinsic::experimental_gc_statepoint: {
Assert1(!CI.doesNotAccessMemory() &&
!CI.onlyReadsMemory(),
"gc.statepoint must read and write memory to preserve "
"reordering restrictions required by safepoint semantics", &CI);
Assert1(!CI.isInlineAsm(),
"gc.statepoint support for inline assembly unimplemented", &CI);
const Value *Target = CI.getArgOperand(0);
const PointerType *PT = dyn_cast<PointerType>(Target->getType());
Assert2(PT && PT->getElementType()->isFunctionTy(),
"gc.statepoint callee must be of function pointer type",
&CI, Target);
FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
Assert1(!TargetFuncType->isVarArg(),
"gc.statepoint support for var arg functions not implemented", &CI);
const Value *NumCallArgsV = CI.getArgOperand(1);
Assert1(isa<ConstantInt>(NumCallArgsV),
"gc.statepoint number of arguments to underlying call "
"must be constant integer", &CI);
const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
Assert1(NumCallArgs >= 0,
"gc.statepoint number of arguments to underlying call "
"must be positive", &CI);
Assert1(NumCallArgs == (int)TargetFuncType->getNumParams(),
"gc.statepoint mismatch in number of call args", &CI);
const Value *Unused = CI.getArgOperand(2);
Assert1(isa<ConstantInt>(Unused) &&
cast<ConstantInt>(Unused)->isNullValue(),
"gc.statepoint parameter #3 must be zero", &CI);
// Verify that the types of the call parameter arguments match
// the type of the wrapped callee.
for (int i = 0; i < NumCallArgs; i++) {
Type *ParamType = TargetFuncType->getParamType(i);
Type *ArgType = CI.getArgOperand(3+i)->getType();
Assert1(ArgType == ParamType,
"gc.statepoint call argument does not match wrapped "
"function type", &CI);
}
const int EndCallArgsInx = 2+NumCallArgs;
const Value *NumDeoptArgsV = CI.getArgOperand(EndCallArgsInx+1);
Assert1(isa<ConstantInt>(NumDeoptArgsV),
"gc.statepoint number of deoptimization arguments "
"must be constant integer", &CI);
const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
Assert1(NumDeoptArgs >= 0,
"gc.statepoint number of deoptimization arguments "
"must be positive", &CI);
Assert1(4 + NumCallArgs + NumDeoptArgs <= (int)CI.getNumArgOperands(),
"gc.statepoint too few arguments according to length fields", &CI);
// Check that the only uses of this gc.statepoint are gc.result or
// gc.relocate calls which are tied to this statepoint and thus part
// of the same statepoint sequence
for (User *U : CI.users()) {
const CallInst *Call = dyn_cast<const CallInst>(U);
Assert2(Call, "illegal use of statepoint token", &CI, U);
if (!Call) continue;
Assert2(isGCRelocate(Call) || isGCResult(Call),
"gc.result or gc.relocate are the only value uses"
"of a gc.statepoint", &CI, U);
if (isGCResult(Call)) {
Assert2(Call->getArgOperand(0) == &CI,
"gc.result connected to wrong gc.statepoint",
&CI, Call);
} else if (isGCRelocate(Call)) {
Assert2(Call->getArgOperand(0) == &CI,
"gc.relocate connected to wrong gc.statepoint",
&CI, Call);
}
}
// Note: It is legal for a single derived pointer to be listed multiple
// times. It's non-optimal, but it is legal. It can also happen after
// insertion if we strip a bitcast away.
// Note: It is really tempting to check that each base is relocated and
// that a derived pointer is never reused as a base pointer. This turns
// out to be problematic since optimizations run after safepoint insertion
// can recognize equality properties that the insertion logic doesn't know
// about. See example statepoint.ll in the verifier subdirectory
break;
}
case Intrinsic::experimental_gc_result_int:
case Intrinsic::experimental_gc_result_float:
case Intrinsic::experimental_gc_result_ptr: {
// Are we tied to a statepoint properly?
CallSite StatepointCS(CI.getArgOperand(0));
const Function *StatepointFn =
StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
Assert2(StatepointFn && StatepointFn->isDeclaration() &&
StatepointFn->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
"gc.result operand #1 must be from a statepoint",
&CI, CI.getArgOperand(0));
// Assert that result type matches wrapped callee.
const Value *Target = StatepointCS.getArgument(0);
const PointerType *PT = cast<PointerType>(Target->getType());
const FunctionType *TargetFuncType =
cast<FunctionType>(PT->getElementType());
Assert1(CI.getType() == TargetFuncType->getReturnType(),
"gc.result result type does not match wrapped callee",
&CI);
break;
}
case Intrinsic::experimental_gc_relocate: {
// Are we tied to a statepoint properly?
CallSite StatepointCS(CI.getArgOperand(0));
const Function *StatepointFn =
StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
Assert2(StatepointFn && StatepointFn->isDeclaration() &&
StatepointFn->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
"gc.relocate operand #1 must be from a statepoint",
&CI, CI.getArgOperand(0));
// Both the base and derived must be piped through the safepoint
Value* Base = CI.getArgOperand(1);
Assert1(isa<ConstantInt>(Base),
"gc.relocate operand #2 must be integer offset", &CI);
Value* Derived = CI.getArgOperand(2);
Assert1(isa<ConstantInt>(Derived),
"gc.relocate operand #3 must be integer offset", &CI);
const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
// Check the bounds
Assert1(0 <= BaseIndex &&
BaseIndex < (int)StatepointCS.arg_size(),
"gc.relocate: statepoint base index out of bounds", &CI);
Assert1(0 <= DerivedIndex &&
DerivedIndex < (int)StatepointCS.arg_size(),
"gc.relocate: statepoint derived index out of bounds", &CI);
// Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
// section of the statepoint's argument
const int NumCallArgs =
cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
const int NumDeoptArgs =
cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
const int GCParamArgsEnd = StatepointCS.arg_size();
Assert1(GCParamArgsStart <= BaseIndex &&
BaseIndex < GCParamArgsEnd,
"gc.relocate: statepoint base index doesn't fall within the "
"'gc parameters' section of the statepoint call", &CI);
Assert1(GCParamArgsStart <= DerivedIndex &&
DerivedIndex < GCParamArgsEnd,
"gc.relocate: statepoint derived index doesn't fall within the "
"'gc parameters' section of the statepoint call", &CI);
// Assert that the result type matches the type of the relocated pointer
GCRelocateOperands Operands(&CI);
Assert1(Operands.derivedPtr()->getType() == CI.getType(),
"gc.relocate: relocating a pointer shouldn't change its type",
&CI);
break;
}
};
}
void DebugInfoVerifier::verifyDebugInfo() {
if (!VerifyDebugInfo)
return;
DebugInfoFinder Finder;
Finder.processModule(*M);
processInstructions(Finder);
// Verify Debug Info.
//
// NOTE: The loud braces are necessary for MSVC compatibility.
for (DICompileUnit CU : Finder.compile_units()) {
Assert1(CU.Verify(), "DICompileUnit does not Verify!", CU);
}
for (DISubprogram S : Finder.subprograms()) {
Assert1(S.Verify(), "DISubprogram does not Verify!", S);
}
for (DIGlobalVariable GV : Finder.global_variables()) {
Assert1(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
}
for (DIType T : Finder.types()) {
Assert1(T.Verify(), "DIType does not Verify!", T);
}
for (DIScope S : Finder.scopes()) {
Assert1(S.Verify(), "DIScope does not Verify!", S);
}
}
void DebugInfoVerifier::processInstructions(DebugInfoFinder &Finder) {
for (const Function &F : *M)
for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
Finder.processLocation(*M, DILocation(MD));
if (const CallInst *CI = dyn_cast<CallInst>(&*I))
processCallInst(Finder, *CI);
}
}
void DebugInfoVerifier::processCallInst(DebugInfoFinder &Finder,
const CallInst &CI) {
if (Function *F = CI.getCalledFunction())
if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
switch (ID) {
case Intrinsic::dbg_declare:
Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
break;
case Intrinsic::dbg_value:
Finder.processValue(*M, cast<DbgValueInst>(&CI));
break;
default:
break;
}
}
//===----------------------------------------------------------------------===//
// Implement the public interfaces to this file...
//===----------------------------------------------------------------------===//
bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
Function &F = const_cast<Function &>(f);
assert(!F.isDeclaration() && "Cannot verify external functions");
raw_null_ostream NullStr;
Verifier V(OS ? *OS : NullStr);
// Note that this function's return value is inverted from what you would
// expect of a function called "verify".
return !V.verify(F);
}
bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
raw_null_ostream NullStr;
Verifier V(OS ? *OS : NullStr);
bool Broken = false;
for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isDeclaration() && !I->isMaterializable())
Broken |= !V.verify(*I);
// Note that this function's return value is inverted from what you would
// expect of a function called "verify".
DebugInfoVerifier DIV(OS ? *OS : NullStr);
return !V.verify(M) || !DIV.verify(M) || Broken;
}
namespace {
struct VerifierLegacyPass : public FunctionPass {
static char ID;
Verifier V;
bool FatalErrors;
VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) {
initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
}
explicit VerifierLegacyPass(bool FatalErrors)
: FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (!V.verify(F) && FatalErrors)
report_fatal_error("Broken function found, compilation aborted!");
return false;
}
bool doFinalization(Module &M) override {
if (!V.verify(M) && FatalErrors)
report_fatal_error("Broken module found, compilation aborted!");
return false;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}
};
struct DebugInfoVerifierLegacyPass : public ModulePass {
static char ID;
DebugInfoVerifier V;
bool FatalErrors;
DebugInfoVerifierLegacyPass() : ModulePass(ID), FatalErrors(true) {
initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
}
explicit DebugInfoVerifierLegacyPass(bool FatalErrors)
: ModulePass(ID), V(dbgs()), FatalErrors(FatalErrors) {
initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override {
if (!V.verify(M) && FatalErrors)
report_fatal_error("Broken debug info found, compilation aborted!");
return false;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}
};
}
char VerifierLegacyPass::ID = 0;
INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
char DebugInfoVerifierLegacyPass::ID = 0;
INITIALIZE_PASS(DebugInfoVerifierLegacyPass, "verify-di", "Debug Info Verifier",
false, false)
FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
return new VerifierLegacyPass(FatalErrors);
}
ModulePass *llvm::createDebugInfoVerifierPass(bool FatalErrors) {
return new DebugInfoVerifierLegacyPass(FatalErrors);
}
PreservedAnalyses VerifierPass::run(Module &M) {
if (verifyModule(M, &dbgs()) && FatalErrors)
report_fatal_error("Broken module found, compilation aborted!");
return PreservedAnalyses::all();
}
PreservedAnalyses VerifierPass::run(Function &F) {
if (verifyFunction(F, &dbgs()) && FatalErrors)
report_fatal_error("Broken function found, compilation aborted!");
return PreservedAnalyses::all();
}
|
#include <vtkSmartPointer.h>
#include <vtkBYUReader.h>
#include <vtkOBJReader.h>
#include <vtkPLYReader.h>
#include <vtkPolyDataReader.h>
#include <vtkSTLReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkPointSource.h>
#include <vtkUnsignedDistance.h>
#include <vtkImageMapToColors.h>
#include <vtkLookupTable.h>
#include <vtkImageData.h>
#include <vtkImageActor.h>
#include <vtkScalarBarActor.h>
#include <vtkImageMapper3D.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkCamera.h>
#include <vtksys/SystemTools.hxx>
namespace
{
vtkSmartPointer<vtkPolyData> ReadPolyData(const char *fileName);
}
int main (int argc, char *argv[])
{
vtkSmartPointer<vtkPolyData> polyData = ReadPolyData(argc > 1 ? argv[1] : "");;
double bounds[6];
polyData->GetBounds(bounds);
double range[3];
for (int i = 0; i < 3; ++i)
{
range[i] = bounds[2*i + 1] - bounds[2*i];
}
int sampleSize = polyData->GetNumberOfPoints() * .00005;
if (sampleSize < 10)
{
sampleSize = 10;
}
std::cout << "Sample size is: " << sampleSize << std::endl;
std::cout << "Range: "
<< range[0] << ", "
<< range[1] << ", "
<< range[2] << std::endl;
int dimension = 256;
dimension = 128;
double radius = range[0] * .02;
radius = range[0] / static_cast<double>(dimension) * 5;; // ~5 voxels
std::cout << "Radius: " << radius << std::endl;
vtkSmartPointer<vtkUnsignedDistance> distance =
vtkSmartPointer<vtkUnsignedDistance>::New();
distance->SetInputData (polyData);
distance->SetRadius(radius);
distance->SetDimensions(dimension, dimension, dimension);
distance->SetBounds(
bounds[0] - range[0] * .1,
bounds[1] + range[0] * .1,
bounds[2] - range[1] * .1,
bounds[3] + range[1] * .1,
bounds[4] - range[2] * .1,
bounds[5] + range[2] * .1);
// Create a lookup table that consists of the full hue circle
// (from HSV).
vtkSmartPointer<vtkLookupTable> hueLut =
vtkSmartPointer<vtkLookupTable>::New();
hueLut->SetTableRange (-.99 * radius, .99 * radius);
hueLut->SetHueRange (.667, 0);
hueLut->SetSaturationRange (1, 1);
hueLut->SetValueRange (1, 1);
hueLut->UseAboveRangeColorOn();
hueLut->SetAboveRangeColor(0, 0, 0, 0);
hueLut->SetNumberOfColors(5);
hueLut->Build();
double *last = hueLut->GetTableValue(4);
hueLut->SetAboveRangeColor(last[0], last[1], last[2], 0);
vtkSmartPointer<vtkImageMapToColors> sagittalColors =
vtkSmartPointer<vtkImageMapToColors>::New();
sagittalColors->SetInputConnection(distance->GetOutputPort());
sagittalColors->SetLookupTable(hueLut);
sagittalColors->Update();
vtkSmartPointer<vtkImageActor> sagittal =
vtkSmartPointer<vtkImageActor>::New();
sagittal->GetMapper()->SetInputConnection(sagittalColors->GetOutputPort());
sagittal->SetDisplayExtent(dimension/2, dimension/2, 0, dimension - 1, 0, dimension - 1);
sagittal->ForceOpaqueOn();
vtkSmartPointer<vtkImageMapToColors> axialColors =
vtkSmartPointer<vtkImageMapToColors>::New();
axialColors->SetInputConnection(distance->GetOutputPort());
axialColors->SetLookupTable(hueLut);
axialColors->Update();
vtkSmartPointer<vtkImageActor> axial =
vtkSmartPointer<vtkImageActor>::New();
axial->GetMapper()->SetInputConnection(axialColors->GetOutputPort());
axial->SetDisplayExtent(0, dimension - 1, 0, dimension - 1, dimension/2, dimension/2);
axial->ForceOpaqueOn();
vtkSmartPointer<vtkImageMapToColors> coronalColors =
vtkSmartPointer<vtkImageMapToColors>::New();
coronalColors->SetInputConnection(distance->GetOutputPort());
coronalColors->SetLookupTable(hueLut);
coronalColors->Update();
vtkSmartPointer<vtkImageActor> coronal =
vtkSmartPointer<vtkImageActor>::New();
coronal->GetMapper()->SetInputConnection(coronalColors->GetOutputPort());
coronal->SetDisplayExtent(0, dimension - 1, dimension/2, dimension/2, 0, dimension - 1);
coronal->ForceOpaqueOn();
// Create a scalar bar
vtkSmartPointer<vtkScalarBarActor> scalarBar =
vtkSmartPointer<vtkScalarBarActor>::New();
scalarBar->SetLookupTable(hueLut);
scalarBar->SetTitle("Distance");
scalarBar->SetNumberOfLabels(5);
// Create graphics stuff
//
vtkSmartPointer<vtkRenderer> ren1 =
vtkSmartPointer<vtkRenderer>::New();
ren1->SetBackground(.3, .4, .6);
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(ren1);
renWin->SetSize(512,512);
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
// Add the actors to the renderer, set the background and size
//
ren1->AddActor(sagittal);
ren1->AddActor(axial);
ren1->AddActor(coronal);
ren1->AddActor2D(scalarBar);
// Generate an interesting view
//
ren1->ResetCamera();
ren1->GetActiveCamera()->Azimuth(120);
ren1->GetActiveCamera()->Elevation(30);
ren1->GetActiveCamera()->Dolly(1.5);
ren1->ResetCameraClippingRange();
renWin->Render();
iren->Initialize();
iren->Start();
std::cout << distance->GetOutput()->GetScalarRange()[0] << ", "
<< distance->GetOutput()->GetScalarRange()[1] << std::endl;
return EXIT_SUCCESS;
}
namespace
{
vtkSmartPointer<vtkPolyData> ReadPolyData(const char *fileName)
{
vtkSmartPointer<vtkPolyData> polyData;
std::string extension = vtksys::SystemTools::GetFilenameExtension(std::string(fileName));
if (extension == ".ply")
{
vtkSmartPointer<vtkPLYReader> reader =
vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".vtp")
{
vtkSmartPointer<vtkXMLPolyDataReader> reader =
vtkSmartPointer<vtkXMLPolyDataReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".vtk")
{
vtkSmartPointer<vtkPolyDataReader> reader =
vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".obj")
{
vtkSmartPointer<vtkOBJReader> reader =
vtkSmartPointer<vtkOBJReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".stl")
{
vtkSmartPointer<vtkSTLReader> reader =
vtkSmartPointer<vtkSTLReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".g")
{
vtkSmartPointer<vtkBYUReader> reader =
vtkSmartPointer<vtkBYUReader>::New();
reader->SetGeometryFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else
{
vtkSmartPointer<vtkPointSource> points =
vtkSmartPointer<vtkPointSource>::New();
points->SetNumberOfPoints(100000);
points->SetRadius(10.0);
points->SetCenter(vtkMath::Random(-100, 100),
vtkMath::Random(-100, 100),
vtkMath::Random(-100, 100));
points->SetDistributionToShell();
points->Update();
polyData = points->GetOutput();
}
return polyData;
}
}
|
/**
* Author: Patrick T Cox
* Date of Creation: 15 September 2017
* Last Updated: 15 December 2017
* Project: SmallpoxAttackSim
*/
#include <random>
#include <fstream>
int main()
{
const int n_persons = 5000;
const int n_groups = 1000;
const int minGroups = 3;
const int maxGroups = 20;
std::default_random_engine engine(std::random_device{}());
std::uniform_int_distribution<int> groupRange(minGroups, maxGroups);
std::uniform_int_distribution<int> groupDist(0, n_groups);
std::vector<std::string> personVector;
for (int p=0; p < n_persons; ++p)
{
int p_groups = groupRange(engine);
std::string groups = "";
for (int g=0; g < p_groups; ++g)
{
groups += std::to_string(groupDist(engine)) + " ";
}
personVector.push_back(groups);
}
std::ofstream fout;
fout.open("./groups.data");
for (int p=0; p< n_persons; ++p)
{
fout << personVector[p] << "\n";
}
fout.close();
return 0;
}
|
<?hh // strict
namespace Dust\Ast;
class Reference extends InlinePart
{
/**
* @var array[string]
*/
public array<string> $filters;
/**
* @var string
*/
public string $identifier;
/**
* @return string
*/
public function __toString(): string {
$str = $this->identifier;
if (!empty($this->filters))
foreach ($this->filters as $value) $str .= $value;
return "{" . $str . "}";
}
}
|
/**
* @example oglplus/013_spiral_sphere.cpp
* @brief Shows how to draw a jumping and rotating sphere
*
* @oglplus_screenshot{013_spiral_sphere}
*
* Copyright 2008-2013 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* @oglplus_example_uses_gl{GL_VERSION_3_1}
*/
#include <oglplus/gl.hpp>
#include <oglplus/all.hpp>
#include <oglplus/shapes/sphere.hpp>
#include <cmath>
#include "example.hpp"
namespace oglplus {
class SphereExample : public Example
{
private:
// helper object building sphere vertex attributes
shapes::Sphere make_sphere;
// helper object encapsulating sphere drawing instructions
shapes::DrawingInstructions sphere_instr;
// indices pointing to sphere primitive elements
shapes::Sphere::IndexArray sphere_indices;
// wrapper around the current OpenGL context
Context gl;
// Vertex shader
VertexShader vs;
// Fragment shader
FragmentShader fs;
// Program
Program prog;
// Uniforms
LazyUniform<Mat4f> projection_matrix, camera_matrix, model_matrix;
// A vertex array object for the rendered sphere
VertexArray sphere;
// VBOs for the sphere's vertices and tex-coordinates
Buffer verts;
Buffer texcoords;
public:
SphereExample(void)
: sphere_instr(make_sphere.Instructions())
, sphere_indices(make_sphere.Indices())
, projection_matrix(prog, "ProjectionMatrix")
, camera_matrix(prog, "CameraMatrix")
, model_matrix(prog, "ModelMatrix")
{
// Set the vertex shader source
vs.Source(
"#version 330\n"
"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
"in vec4 Position;"
"in vec2 TexCoord;"
"out vec2 vertTexCoord;"
"void main(void)"
"{"
" vertTexCoord = TexCoord;"
" gl_Position = "
" ProjectionMatrix *"
" CameraMatrix *"
" ModelMatrix *"
" Position;"
"}"
);
// compile it
vs.Compile();
// set the fragment shader source
fs.Source(
"#version 330\n"
"in vec2 vertTexCoord;"
"out vec4 fragColor;"
"void main(void)"
"{"
" float i = int(("
" vertTexCoord.x+"
" vertTexCoord.y "
" )*16) % 2;"
" fragColor = mix("
" vec4(0.9, 0.9, 0.9, 1.0),"
" vec4(1.0, 0.3, 0.4, 1.0),"
" i"
" );"
"}"
);
// compile it
fs.Compile();
// attach the shaders to the program
prog.AttachShader(vs);
prog.AttachShader(fs);
// link and use it
prog.Link();
prog.Use();
// bind the VAO for the sphere
sphere.Bind();
// bind the VBO for the sphere vertices
verts.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_sphere.Positions(data);
// upload the data
Buffer::Data(Buffer::Target::Array, data);
// setup the vertex attribs array for the vertices
VertexAttribArray attr(prog, "Position");
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VBO for the sphere UV-coordinates
texcoords.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_sphere.TexCoordinates(data);
// upload the data
Buffer::Data(Buffer::Target::Array, data);
// setup the vertex attribs array for the vertices
VertexAttribArray attr(prog, "TexCoord");
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
//
gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f);
gl.ClearDepth(1.0f);
gl.Enable(Capability::DepthTest);
}
void Reshape(GLuint width, GLuint height)
{
gl.Viewport(width, height);
prog.Use();
projection_matrix.Set(
CamMatrixf::PerspectiveX(
Degrees(70),
double(width)/height,
1, 70
)
);
}
void Render(double time)
{
gl.Clear().ColorBuffer().DepthBuffer();
//
camera_matrix.Set(
CamMatrixf::LookingAt(
Vec3f(2.5, 3.5, 2.5),
Vec3f()
)
);
model_matrix.Set(
ModelMatrixf::Translation(
0.0f,
sqrt(1.0f+SineWave(time / 2.0)),
0.0f
) *
ModelMatrixf::RotationY(Degrees(time * 180))
);
sphere_instr.Draw(sphere_indices);
}
bool Continue(double time)
{
return time < 30.0;
}
};
void setupExample(ExampleParams& /*params*/){ }
std::unique_ptr<ExampleThread> makeExampleThread(
Example& /*example*/,
unsigned /*thread_id*/,
const ExampleParams& /*params*/
){ return std::unique_ptr<ExampleThread>(); }
std::unique_ptr<Example> makeExample(const ExampleParams& /*params*/)
{
return std::unique_ptr<Example>(new SphereExample);
}
} // namespace oglplus
|
//===-- PlatformRemoteAppleBridge.cpp -------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <string>
#include <vector>
#include "PlatformRemoteAppleBridge.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Host/Host.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/ArchSpec.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/StreamString.h"
using namespace lldb;
using namespace lldb_private;
//------------------------------------------------------------------
/// Default Constructor
//------------------------------------------------------------------
PlatformRemoteAppleBridge::PlatformRemoteAppleBridge()
: PlatformRemoteDarwinDevice () {}
//------------------------------------------------------------------
// Static Variables
//------------------------------------------------------------------
static uint32_t g_initialize_count = 0;
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
void PlatformRemoteAppleBridge::Initialize() {
PlatformDarwin::Initialize();
if (g_initialize_count++ == 0) {
PluginManager::RegisterPlugin(PlatformRemoteAppleBridge::GetPluginNameStatic(),
PlatformRemoteAppleBridge::GetDescriptionStatic(),
PlatformRemoteAppleBridge::CreateInstance);
}
}
void PlatformRemoteAppleBridge::Terminate() {
if (g_initialize_count > 0) {
if (--g_initialize_count == 0) {
PluginManager::UnregisterPlugin(PlatformRemoteAppleBridge::CreateInstance);
}
}
PlatformDarwin::Terminate();
}
PlatformSP PlatformRemoteAppleBridge::CreateInstance(bool force,
const ArchSpec *arch) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
if (log) {
const char *arch_name;
if (arch && arch->GetArchitectureName())
arch_name = arch->GetArchitectureName();
else
arch_name = "<null>";
const char *triple_cstr =
arch ? arch->GetTriple().getTriple().c_str() : "<null>";
log->Printf("PlatformRemoteAppleBridge::%s(force=%s, arch={%s,%s})",
__FUNCTION__, force ? "true" : "false", arch_name, triple_cstr);
}
bool create = force;
if (!create && arch && arch->IsValid()) {
switch (arch->GetMachine()) {
case llvm::Triple::aarch64: {
const llvm::Triple &triple = arch->GetTriple();
llvm::Triple::VendorType vendor = triple.getVendor();
switch (vendor) {
case llvm::Triple::Apple:
create = true;
break;
#if defined(__APPLE__)
// Only accept "unknown" for the vendor if the host is Apple and
// it "unknown" wasn't specified (it was just returned because it
// was NOT specified)
case llvm::Triple::UnknownVendor:
create = !arch->TripleVendorWasSpecified();
break;
#endif
default:
break;
}
if (create) {
switch (triple.getOS()) {
// NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS:
break;
default:
create = false;
break;
}
}
} break;
default:
break;
}
}
if (create) {
if (log)
log->Printf("PlatformRemoteAppleBridge::%s() creating platform",
__FUNCTION__);
return lldb::PlatformSP(new PlatformRemoteAppleBridge());
}
if (log)
log->Printf("PlatformRemoteAppleBridge::%s() aborting creation of platform",
__FUNCTION__);
return lldb::PlatformSP();
}
lldb_private::ConstString PlatformRemoteAppleBridge::GetPluginNameStatic() {
static ConstString g_name("remote-bridgeos");
return g_name;
}
const char *PlatformRemoteAppleBridge::GetDescriptionStatic() {
return "Remote BridgeOS platform plug-in.";
}
bool PlatformRemoteAppleBridge::GetSupportedArchitectureAtIndex(uint32_t idx,
ArchSpec &arch) {
ArchSpec system_arch(GetSystemArchitecture());
const ArchSpec::Core system_core = system_arch.GetCore();
switch (system_core) {
default:
switch (idx) {
case 0:
arch.SetTriple("arm64-apple-bridgeos");
return true;
default:
break;
}
break;
case ArchSpec::eCore_arm_arm64:
switch (idx) {
case 0:
arch.SetTriple("arm64-apple-bridgeos");
return true;
default:
break;
}
break;
}
arch.Clear();
return false;
}
void PlatformRemoteAppleBridge::GetDeviceSupportDirectoryNames (std::vector<std::string> &dirnames)
{
dirnames.clear();
dirnames.push_back("BridgeOS DeviceSupport");
}
std::string PlatformRemoteAppleBridge::GetPlatformName ()
{
return "BridgeOS.platform";
}
|
/**
* @file Params.cpp
*
* @brief Parameter class for Zerocoin.
*
* @author Ian Miers, Christina Garman and Matthew Green
* @date June 2013
*
* @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license This project is released under the MIT license.
**/
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018-2019 The Ion developers
#include "Params.h"
#include "ParamGeneration.h"
namespace libzerocoin {
ZerocoinParams::ZerocoinParams(CBigNum N, uint32_t securityLevel) {
this->zkp_hash_len = securityLevel;
this->zkp_iterations = securityLevel;
this->accumulatorParams.k_prime = ACCPROOF_KPRIME;
this->accumulatorParams.k_dprime = ACCPROOF_KDPRIME;
// Generate the parameters
CalculateParams(*this, N, ZEROCOIN_PROTOCOL_VERSION, securityLevel);
this->accumulatorParams.initialized = true;
this->initialized = true;
}
AccumulatorAndProofParams::AccumulatorAndProofParams() {
this->initialized = false;
}
IntegerGroupParams::IntegerGroupParams() {
this->initialized = false;
}
CBigNum IntegerGroupParams::randomElement() const {
// The generator of the group raised
// to a random number less than the order of the group
// provides us with a uniformly distributed random number.
return this->g.pow_mod(CBigNum::randBignum(this->groupOrder),this->modulus);
}
} /* namespace libzerocoin */
|
//===-- CommandUtil.cpp ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "CommandUtil.h"
#include "llbuild/Commands/Commands.h"
#include "llbuild/Basic/LLVM.h"
#include "llbuild/Ninja/ManifestLoader.h"
#include "llbuild/Ninja/Parser.h"
#include "llvm/ADT/STLExtras.h"
#include <iostream>
#include <sstream>
using namespace llbuild;
using namespace llbuild::commands;
static std::string programName;
void commands::setProgramName(StringRef name) {
assert(programName.empty());
programName = name;
}
const char* commands::getProgramName() {
if (programName.empty())
return nullptr;
return programName.c_str();
}
static char hexdigit(unsigned input) {
return (input < 10) ? '0' + input : 'A' + input - 10;
}
std::string util::escapedString(const char* start, unsigned length) {
std::stringstream result;
for (unsigned i = 0; i != length; ++i) {
char c = start[i];
if (c == '"') {
result << "\\\"";
} else if (isprint(c)) {
result << c;
} else if (c == '\n') {
result << "\\n";
} else {
result << "\\x"
<< hexdigit(((unsigned char) c >> 4) & 0xF)
<< hexdigit((unsigned char) c & 0xF);
}
}
return result.str();
}
std::string util::escapedString(const std::string& string) {
return escapedString(string.data(), string.size());
}
static void emitError(const std::string& filename, const std::string& message,
const char* position, unsigned length,
int line, int column,
StringRef buffer) {
assert(position >= buffer.begin() && position <= buffer.end() &&
"invalid position");
assert(position + length <= buffer.end() && "invalid length");
// Compute the line and column, if not provided.
//
// FIXME: This is not very efficient, if there are a lot of diagnostics.
if (line == -1) {
line = 1;
column = 0;
for (const char *c = buffer.begin(); c != position; ++c) {
if (*c == '\n') {
++line;
column = 0;
} else {
++column;
}
}
}
std::cerr << filename << ":" << line << ":" << column
<< ": error: " << message << "\n";
// Skip carat diagnostics on EOF token.
if (position == buffer.end())
return;
// Simple caret style diagnostics.
const char *lineBegin = position, *lineEnd = position;
const char *bufferBegin = buffer.begin(), *bufferEnd = buffer.end();
// Run line pointers forward and back.
while (lineBegin > bufferBegin &&
lineBegin[-1] != '\r' && lineBegin[-1] != '\n')
--lineBegin;
while (lineEnd < bufferEnd &&
lineEnd[0] != '\r' && lineEnd[0] != '\n')
++lineEnd;
// Show the line, indented by 2.
std::cerr << " " << std::string(lineBegin, lineEnd) << "\n";
// Show the caret or squiggly, making sure to print back spaces the same.
std::cerr << " ";
for (const char* s = lineBegin; s != position; ++s)
std::cerr << (isspace(*s) ? *s : ' ');
if (length > 1) {
for (unsigned i = 0; i != length; ++i)
std::cerr << '~';
} else {
std::cerr << '^';
}
std::cerr << '\n';
}
void util::emitError(const std::string& filename, const std::string& message,
const ninja::Token& at, const ninja::Parser* parser) {
::emitError(filename, message, at.start, at.length, at.line, at.column,
parser->getLexer().getBuffer());
}
void util::emitError(const std::string& filename, const std::string& message,
const char* position, unsigned length,
StringRef buffer) {
::emitError(filename, message, position, length, -1, -1, buffer);
}
bool util::readFileContents(std::string path,
std::unique_ptr<char[]> *data_out,
uint64_t* size_out,
std::string* error_out) {
// Open the input buffer and compute its size.
FILE* fp = ::fopen(path.c_str(), "rb");
if (!fp) {
int errorNumber = errno;
*error_out = std::string("unable to open input: \"") +
util::escapedString(path) + "\" (" + ::strerror(errorNumber) + ")";
return false;
}
fseek(fp, 0, SEEK_END);
uint64_t size = *size_out = ::ftell(fp);
fseek(fp, 0, SEEK_SET);
// Read the file contents.
auto data = llvm::make_unique<char[]>(size);
uint64_t pos = 0;
while (pos < size) {
// Read data into the buffer.
size_t result = ::fread(data.get() + pos, 1, size - pos, fp);
if (result <= 0) {
*error_out = std::string("unable to read input: ") + path;
return false;
}
pos += result;
}
// Close the file.
::fclose(fp);
*data_out = std::move(data);
return true;
}
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2019 The UFY developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactionfilterproxy.h"
#include "transactionrecord.h"
#include "transactiontablemodel.h"
#include <cstdlib>
#include <QDateTime>
// Earliest date that can be represented (far in the past)
const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0);
// Last date that can be represented (far in the future)
const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF);
TransactionFilterProxy::TransactionFilterProxy(QObject* parent) : QSortFilterProxyModel(parent),
dateFrom(MIN_DATE),
dateTo(MAX_DATE),
addrPrefix(),
typeFilter(COMMON_TYPES),
watchOnlyFilter(WatchOnlyFilter_All),
minAmount(0),
limitRows(-1),
showInactive(true),
fHideOrphans(false)
{
}
bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
int type = index.data(TransactionTableModel::TypeRole).toInt();
QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();
bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool();
QString address = index.data(TransactionTableModel::AddressRole).toString();
QString label = index.data(TransactionTableModel::LabelRole).toString();
qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());
int status = index.data(TransactionTableModel::StatusRole).toInt();
if (!showInactive && status == TransactionStatus::Conflicted)
return false;
if (fHideOrphans && isOrphan(status, type))
return false;
if (!(TYPE(type) & typeFilter))
return false;
if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No)
return false;
if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes)
return false;
if (datetime < dateFrom || datetime > dateTo)
return false;
if (!address.contains(addrPrefix, Qt::CaseInsensitive) && !label.contains(addrPrefix, Qt::CaseInsensitive))
return false;
if (amount < minAmount)
return false;
return true;
}
void TransactionFilterProxy::setDateRange(const QDateTime& from, const QDateTime& to)
{
this->dateFrom = from;
this->dateTo = to;
invalidateFilter();
}
void TransactionFilterProxy::setAddressPrefix(const QString& addrPrefix)
{
this->addrPrefix = addrPrefix;
invalidateFilter();
}
void TransactionFilterProxy::setTypeFilter(quint32 modes)
{
this->typeFilter = modes;
invalidateFilter();
}
void TransactionFilterProxy::setMinAmount(const CAmount& minimum)
{
this->minAmount = minimum;
invalidateFilter();
}
void TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter)
{
this->watchOnlyFilter = filter;
invalidateFilter();
}
void TransactionFilterProxy::setLimit(int limit)
{
this->limitRows = limit;
}
void TransactionFilterProxy::setShowInactive(bool showInactive)
{
this->showInactive = showInactive;
invalidateFilter();
}
void TransactionFilterProxy::setHideOrphans(bool fHide)
{
this->fHideOrphans = fHide;
invalidateFilter();
}
int TransactionFilterProxy::rowCount(const QModelIndex& parent) const
{
if (limitRows != -1) {
return std::min(QSortFilterProxyModel::rowCount(parent), limitRows);
} else {
return QSortFilterProxyModel::rowCount(parent);
}
}
bool TransactionFilterProxy::isOrphan(const int status, const int type)
{
return ( (type == TransactionRecord::Generated || type == TransactionRecord::StakeMint ||
type == TransactionRecord::StakeZUFY || type == TransactionRecord::MNReward)
&& (status == TransactionStatus::Conflicted || status == TransactionStatus::NotAccepted) );
}
|
#include "helper.h"
Helper::Helper(QObject *parent) : QObject(parent)
{
}
|
#include "scannerDisplay.h"
namespace DisplayScan
{
// Define the extern variables:
//PointBuffer displayBuffer1, displayBuffer2;
P2 displayBuffer1[MAX_NUM_POINTS];
P2 displayBuffer2[MAX_NUM_POINTS];
volatile P2 *ptrCurrentDisplayBuffer, *ptrHiddenDisplayBuffer;
uint16_t readingHead, newSizeBufferDisplay; // no need to be volatile
volatile uint16_t sizeBufferDisplay;
volatile bool needSwapFlag;
IntervalTimer scannerTimer;
uint32_t dt;
bool running, interpointBlanking;
StateDisplayEngine stateDisplayEngine;
elapsedMicros delayMirrorsInterPointMicros, delayMirrorsInterFigureBlankingMicros;
elapsedMicros delayInPoint;
elapsedMicros delayLaserOnMicros, delayLaserOffMicros;
void init()
{
// Set the displaying buffer pointer to the first ring buffer [filled with the
// central point], and set swapping flag:
// NOTE: I don't need to initialize the whole array because the ONLY place the
// effective buffer size is changed is in the render() method (Renderer namespace),
// which does fill the buffer as needed. HOWEVER, for some reason [maybe an error
// on the indexes, will check later] accessing a not defined point will make
// the program crash!!???
for (uint16_t i = 0; i < MAX_NUM_POINTS; i++)
{
displayBuffer1[i] = P2(CENTER_MIRROR_ADX, CENTER_MIRROR_ADY);
displayBuffer2[i] = P2(CENTER_MIRROR_ADX, CENTER_MIRROR_ADY);
}
sizeBufferDisplay = newSizeBufferDisplay = 0;
ptrCurrentDisplayBuffer = &(displayBuffer1[0]); // Note: displayBuffer1 is a const pointer to
// the first element of the array displayBuffer1[].
ptrHiddenDisplayBuffer = &(displayBuffer2[0]);
readingHead = 0;
needSwapFlag = false;
// 3) Default scan parameters:
setInterPointTime(DEFAULT_ISR_PERIOD_RENDER);
// 3) Start interrupt routine by default? YES
scannerTimer.begin(displayISR, dt);
running = true;
// 4) Initialize waiting timers:
resetWaitingTimers();
// 5) initialize display engine state and variables:
stateDisplayEngine = STATE_START;
interpointBlanking = false;
// Set ISR priority?
// * NOTE 1 : lower numbers are higher priority, with 0 the highest and 255 the lowest.
// Most other interrupts default to 128, millis() and micros() are priority 32.
// As a general guideline, interrupt routines that run longer should be given lower
// priority (higher numerical values).
// * NOTE 2 : priority should be set after begin - meaning it has to be set every time we stop
// and restart??? I put it in "startDisplay()" method then.
// Check here for details:
// - https://www.pjrc.com/teensy/td_timing_IntervalTimer.html
// - https://forum.pjrc.com/archive/index.php/t-26642.html
// scannerTimer.priority(112); // 112 to lower than millis/micros but higher than others... or higher than millis/micros?
}
uint32_t getInterPointTime() { return (dt); }
uint32_t getInterPointBlankingMode() { return (interpointBlanking); }
void resetWaitingTimers()
{
delayMirrorsInterPointMicros = 0;
delayMirrorsInterFigureBlankingMicros = 0;
delayLaserOnMicros = 0;
delayLaserOffMicros = 0;
delayInPoint = 0;
}
void startDisplay()
{
if (!running)
{ // otherwise do nothing, the ISR is already running
if (scannerTimer.begin(displayISR, dt))
{
// Priority: lower than millis/micros but higher than "most others", in particular the clock to produce the camera trigger
scannerTimer.priority(112);
running = true;
resetWaitingTimers();
}
else
{
PRINTLN(">> ERROR: could not set ISR.");
}
}
}
void stopDisplay()
{
if (running)
{
scannerTimer.end(); // perhaps the condition is not necessary
// Switch Off laser? (power *state* is not affected, and
// will be retrieved when restarting the engine):
Hardware::Lasers::switchOffAll(); // not "setStateSwitchAll(false)"
// Also, set the PIN_INTENSITY_BLANKING to LOW (will be set to HIGH when retrieving the laser
// state AND if at least one laser is not switched off):
Hardware::Gpio::setIntensityBlanking(false);
}
running = false;
}
bool getRunningState() { return (running); }
uint16_t getBufferSize() { return (sizeBufferDisplay); }
void setInterPointTime(uint16_t _dt)
{
#ifdef BLOCKING_DELAYS
// NOTE: in blocking mode, if the ISR last LESS than the sum of inter-times, it can hang the program,
// so we need to check that:
uint32_t minimumDt = 10 + MIRROR_INTER_FIGURE_WAITING_TIME + MIRROR_INTER_POINT_WAITING_TIME + LASER_ON_WAITING_TIME + IN_NORMAL_POINT_WAIT;
if (_dt > minimumDt)
dt = _dt;
else
dt = minimumDt;
#else
dt = _dt;
#endif
// NOTE: there is a difference between "update" and "start",
// check PJRC page. myTimer.update(microseconds);
scannerTimer.update(dt);
}
void setInterPointBlankingMode(bool _mode)
{
interpointBlanking = _mode; // for the time being, this is not per-laser!
//stateDisplayEngine = STATE_START; // important when changing variables that may affect
// the ISR program flow!! (START of display engine clears also the laser "style" stack)
// Needed or the reset to current state may not be called in the ISR
if (!interpointBlanking)
Hardware::Lasers::setToCurrentState();
}
void setDisplayBuffer(const P2 *_ptrFrameBuffer, uint16_t _size)
{
// note: can I use memcpy with size(P2)?? probably yes and much faster... TP TRY!!
//memcpy (ptrHiddenDisplayBuffer, _ptrFrameBuffer, _size*sizeof(P2));
for (uint16_t k = 0; k < _size; k++)
{
ptrHiddenDisplayBuffer[k].x = _ptrFrameBuffer[k].x;
ptrHiddenDisplayBuffer[k].y = _ptrFrameBuffer[k].y;
}
needSwapFlag = true;
// The following is a critical piece of code and must be ATOMIC, otherwise
// the flag may be reset
// by the ISR before newSizeBufferDisplay is set.
// Now, this means the displaying engine will briefly stop,
// but really briefly, and moreover the resizing of the buffer is
// only done at the end of a rendering figure: not very often...
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
//noInterrupts();
newSizeBufferDisplay = _size;
//interrupts();
}
}
// =================================================================
// =========== Mirror-psitioning ISR that is called every dt =======
//==================================================================
// * NOTE 1 : the ISR set and display ONE point at each entry
// * NOTE 2 : this is perhaps the most critical method. And it has to be
// as fast as possible!! (in the future, do NOT use analogWrite() !!)
// * NOTE 3 : general guideline is to keep your function short and avoid
// calling other functions if possible.
void displayISR()
{
// static uint8_t multiDisplay = 0;
// if (!readingHead) multiDisplay = (multiDisplay+1)%3;
// First of all, regardless of the state of the displaying engine, exchange buffers
// when finishing displaying the current buffer AND needSwapFlag is true - meaning
// the rendering engine finished drawing a
// new figure on the hidden buffer [check renderFigure() method]:
if (needSwapFlag)
{ //&& (readingHead==0) ) {// need to swap AND we are in the start of buffer
// * NOTE : the second condition is optional: we could start displaying from
// the current readingHead - but this will deform the figure when
// rendering too fast, basically rendering double buffering obsolete.
// Now, IF we still want that [to smooth the *perceptual illusion* of deformation],
// we also need to check readingHead is in the new range:
readingHead = (readingHead % newSizeBufferDisplay);
// * NOTE : The following variables are volatile - they
// need to be, because they are modified in the ISR:
sizeBufferDisplay = newSizeBufferDisplay;
volatile P2 *ptrAux = ptrCurrentDisplayBuffer;
ptrCurrentDisplayBuffer = ptrHiddenDisplayBuffer;
ptrHiddenDisplayBuffer = ptrAux;
needSwapFlag = false;
// NOTE : not using the style stack here is better for several reasons,
// the most important being avoiding stack overflows when the program flow
// changes as a result to some variables setting (ex: point-blanking)
//Hardware::Lasers::clearStateStack();
//Hardware::Lasers::resetToCurrentState();
}
// * NOTE 1: it is a detail, but in case there are no points
// in the buffer [after clear for instance] we need to recenter
// the mirrors for instance.
// * NOTE 2: this will be done only after finishing the previous
// figure... [nice or not?]
if (sizeBufferDisplay == 0)
stateDisplayEngine = STATE_START;
switch (stateDisplayEngine)
{
case STATE_START: // not the start of a figure, but a start of the display engine, including
// the "restart" when the number of points is >0
// NOTE: there is a difference between STOPPING the
// display engine and CLEARING the blueprint which recenters the mirror, while
// stopping the engine will pause on the last point being displayed
//Hardware::Lasers::clearStateStack();
//Hardware::Scanner::recenterPosRaw(); // recenter? no
Hardware::Lasers::setToCurrentState();
stateDisplayEngine = STATE_IDLE;
//break; // proceed with the next case...
case STATE_IDLE:
{
if (sizeBufferDisplay)
{
stateDisplayEngine = STATE_START_BLANKING;
// Check and activate blanking if necessary:
//Hardware::Lasers::pushState();
for (uint8_t k = 0; k < NUM_LASERS; k++)
{
// switch laser off if blankingMode set (regardless of the mode - carrier or continuous)
//if (Hardware::Lasers::laserArray[k].myState.blankingMode) Hardware::Lasers::laserArray[k].setSwitch(false);
Hardware::Lasers::laserArray[k].updateBlank(); // will only blank IF blanking mode true.
}
}
// otherwise do nothing, but keep checking if the buffer gets filled with something.
}
break;
case STATE_START_BLANKING:
{
// Position the mirrors to next point (this is, the first point in the trajectory, with readinHead = 0):
int16_t adcX = static_cast<int16_t>(ptrCurrentDisplayBuffer->x);
int16_t adcY = static_cast<int16_t>(ptrCurrentDisplayBuffer->y);
// NOTE: avoid calling a function here if possible. It is okay if it is inline though!
Hardware::Scanner::setPosRaw(adcX, adcY);
delayMirrorsInterFigureBlankingMicros = 0;
stateDisplayEngine = STATE_BLANKING_WAIT;
}
//... proceed to STATE_BLANKING_WAIT in the same call
case STATE_BLANKING_WAIT:
{
#ifdef BLOCKING_DELAYS
while (delayMirrorsInterFigureBlankingMicros < MIRROR_INTER_FIGURE_WAITING_TIME)
{
}
#else // non blocking delay:
if (delayMirrorsInterFigureBlankingMicros < MIRROR_INTER_FIGURE_WAITING_TIME)
break; // do nothing and break;
#endif
// End of mirror blanking waiting time: we are supposed to be in the right coordinates of first figure point: go directly to
// laser on waiting state after setting the lasers ON (or whatever is needed)
//Hardware::Lasers::popState(); // <-- IMPORTANT (do not forget or the stack will overflow).
Hardware::Lasers::setToCurrentState();
stateDisplayEngine = STATE_LASER_ON_WAITING;
}
// .. proceed!
case STATE_START_NORMAL_POINT:
{
// Position mirrors [ATTN: (0,0) is the center of the mirrors]
int16_t adcX = static_cast<int16_t>((ptrCurrentDisplayBuffer + readingHead)->x);
int16_t adcY = static_cast<int16_t>((ptrCurrentDisplayBuffer + readingHead)->y);
// NOTE: avoid calling a function here if possible. It is okay if it is inline though!
Hardware::Scanner::setPosRaw(adcX, adcY);
stateDisplayEngine = STATE_TO_NORMAL_POINT_WAIT;
delayMirrorsInterPointMicros = 0;
}
//... proceed
case STATE_TO_NORMAL_POINT_WAIT:
{
#ifdef BLOCKING_DELAYS
while (delayMirrorsInterPointMicros < MIRROR_INTER_POINT_WAITING_TIME)
{
}
#else
if (delayMirrorsInterPointMicros < MIRROR_INTER_POINT_WAITING_TIME)
break;
#endif
// For the time being, color is not per-point, but uses the current state of the lasers which should
// not have changed during the whole figure. By the way, the lasers can be switched off at the end the
// normal point or not. If not [the default behaviour] the laser will be on during the jump to the next point.
// SWITCH ON lasers IF interpointBlanking was true (this is COMMON for all lasers):
// ATTN: interpointBlanking may have changed in the meantime, so that the laser will never
// go back to the "current state". One solution is to do this setting all the time (no condition),
// or call setToCurrentState() whenever we set interpointBlanking to false. I will use this last strategy.
if (interpointBlanking)
Hardware::Lasers::setToCurrentState(); //Hardware::Lasers::popState();
stateDisplayEngine = STATE_LASER_ON_WAITING;
delayLaserOnMicros = 0;
}
//... proceed to next case [STATE_LASER_ON_WAITING]
case STATE_LASER_ON_WAITING:
{
#ifdef BLOCKING_DELAYS
while (delayLaserOnMicros < LASER_ON_WAITING_TIME)
{
}
#else
if (delayLaserOnMicros < LASER_ON_WAITING_TIME)
break;
#endif
delayInPoint = 0;
stateDisplayEngine = STATE_IN_NORMAL_POINT_WAIT;
}
// .. and then proceed
case STATE_IN_NORMAL_POINT_WAIT:
{
#ifdef BLOCKING_DELAYS
while (delayInPoint < IN_NORMAL_POINT_WAIT)
{
}
#else
if (delayInPoint < IN_NORMAL_POINT_WAIT)
break;
#endif
// Advance the readingHead on the round-robin buffer and check if we are in a normal cycle or final figure:
// * NOTE 1 : no need to qualify readingHead it as volatile
// since only the ISR will use it.
// * NOTE 2 : if the second operand of / or % is zero the behavior is undefined in C++,
// hence the condition on sizeBuffer size [but the check is done for this portion of
// the ISR anyway]:
//if (sizeBufferDisplay) readingHead = (readingHead + 1) % sizeBufferDisplay;
readingHead = (readingHead + 1) % sizeBufferDisplay;
if (readingHead == 0)
{
// We WERE in the last point [TODO: this is not the right condition for a generic "end of figure"...]
for (uint8_t k = 0; k < NUM_LASERS; k++)
{
// Switch laser off if blankingMode set [regardless of the mode - carrier or continuous]
//if (Hardware::Lasers::laserArray[k].myState.blankingMode) Hardware::Lasers::laserArray[k].setSwitch(false);
Hardware::Lasers::laserArray[k].updateBlank(); // will only blank IF blanking mode true.
// NOTE: we don't do inter-point blanking here! this is "true" blanking (between figures)
}
stateDisplayEngine = STATE_START_BLANKING;
}
else
{
// Switch OFF lasers
if (interpointBlanking)
{
//Hardware::Lasers::pushState();
Hardware::Lasers::switchOffAll(); // does not affect the current laser color/state
}
stateDisplayEngine = STATE_START_NORMAL_POINT;
}
}
break;
} // end switch state for the display engine modes
} // end display ISR
} // namespace DisplayScan
|
/*
* Edgecore DeviceManager
* Copyright 2020-2021 Edgecore Networks, Inc.
*
* 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.
*/
#pragma once
#include <memory>
/*! Agent namspace */
namespace agent {
/*! Chassis namspace */
namespace chassis {
/*! ecrf_pal namspace */
namespace ecrf_pal {
/*! Watcher namspace */
namespace watcher {
/*! ecrf_pal watcher task interface*/
class Task {
public:
virtual ~Task();
/*! Executes task */
virtual void execute() = 0;
};
/*! ecrf_pal watcher task shared pointer */
using TaskSPtr = std::shared_ptr<Task>;
}
}
}
}
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItemStructure_BaseRailing_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function PrimalItemStructure_BaseRailing.PrimalItemStructure_BaseRailing_C.ExecuteUbergraph_PrimalItemStructure_BaseRailing
struct UPrimalItemStructure_BaseRailing_C_ExecuteUbergraph_PrimalItemStructure_BaseRailing_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.