blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e5bde1585275d292d5fefe909d820b8c58f98cc5 | 8a98ebab7c04eda74ed84b66364e6a3b00f682b7 | /src/qt/darksendconfig.cpp | 0789c299a3910a2ca0b54f1442f894839b290ca9 | [
"MIT"
] | permissive | momopay/momo | eaa87f84513c219babb9a89d02a9224231739ad7 | 2a2ace2f3d2a0b2fd3c9257cbb0225b078ea5c49 | refs/heads/master | 2021-04-09T15:46:48.294563 | 2018-06-27T08:21:23 | 2018-06-27T08:21:23 | 125,665,637 | 3 | 4 | MIT | 2018-04-02T04:14:48 | 2018-03-17T20:15:36 | C++ | UTF-8 | C++ | false | false | 2,474 | cpp | #include "darksendconfig.h"
#include "ui_darksendconfig.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "privatesend-client.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
#include <QSettings>
DarksendConfig::DarksendConfig(QWidget *parent) :
QDialog(parent),
ui(new Ui::DarksendConfig),
model(0)
{
ui->setupUi(this);
connect(ui->buttonBasic, SIGNAL(clicked()), this, SLOT(clickBasic()));
connect(ui->buttonHigh, SIGNAL(clicked()), this, SLOT(clickHigh()));
connect(ui->buttonMax, SIGNAL(clicked()), this, SLOT(clickMax()));
}
DarksendConfig::~DarksendConfig()
{
delete ui;
}
void DarksendConfig::setModel(WalletModel *model)
{
this->model = model;
}
void DarksendConfig::clickBasic()
{
configure(true, 1000, 2);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("PrivateSend Configuration"),
tr(
"PrivateSend was successfully set to basic (%1 and 2 rounds). You can change this at any time by opening Momo's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::clickHigh()
{
configure(true, 1000, 8);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("PrivateSend Configuration"),
tr(
"PrivateSend was successfully set to high (%1 and 8 rounds). You can change this at any time by opening Momo's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::clickMax()
{
configure(true, 1000, 16);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("PrivateSend Configuration"),
tr(
"PrivateSend was successfully set to maximum (%1 and 16 rounds). You can change this at any time by opening Momo's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::configure(bool enabled, int coins, int rounds) {
QSettings settings;
settings.setValue("nPrivateSendRounds", rounds);
settings.setValue("nPrivateSendAmount", coins);
privateSendClient.nPrivateSendRounds = rounds;
privateSendClient.nPrivateSendAmount = coins;
}
| [
"iven@momopay.org"
] | iven@momopay.org |
195688486204ed8d4ae1a5cde71b3afe8b17bae5 | 7456393444e8e47d682295ff85adb1459813012e | /dji_m600_sim/src/rviz_collision_publisher_no_gazebo.cpp | c8e8b5522d1ebdb48ddc3fed3ac619c379b52ba8 | [] | no_license | eichmeierbr/aacas_ros_sim | 9dffb141944029e019757a984f6e056e1dbf289b | 81da663d2b1293c87f06c2c74c305b01684fb384 | refs/heads/master | 2021-05-25T20:17:56.196369 | 2020-09-28T15:31:09 | 2020-09-28T15:31:09 | 253,905,058 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,539 | cpp | #include <ros/ros.h>
#include <rviz_visual_tools/rviz_visual_tools.h>
#include "lidar_process/tracked_obj.h"
#include "lidar_process/tracked_obj_arr.h"
#include <vector>
#include <string>
namespace {
constexpr double radius = 0.127;
} // namespace
rviz_visual_tools::RvizVisualToolsPtr visual_tools_;
// Update Visual Object Location callback
void obstacle_visualization_callback(const lidar_process::tracked_obj_arr msg)
{
visual_tools_.reset(
new rviz_visual_tools::RvizVisualTools("/world", "/obstacles"));
std::vector<geometry_msgs::Point> sphere_centers;
std::vector<lidar_process::tracked_obj> detections = msg.tracked_obj_arr;
geometry_msgs::Point sphere;
for(int i=0; i<detections.size(); ++i)
{
sphere.x = detections[i].point.x;
sphere.y = detections[i].point.y;
sphere.z = detections[i].point.z;
sphere_centers.push_back(sphere);
}
visual_tools_->loadMarkerPub();
visual_tools_->waitForMarkerPub();
visual_tools_->setLifetime(0);
visual_tools_->publishSpheres(sphere_centers, rviz_visual_tools::RED, radius*2.0,
"obstacles");
visual_tools_->trigger();
}
int main(int argc, char **argv) {
ros::init(argc, argv, "rviz_collision_publisher");
ros::NodeHandle nh;
std::string obstacle_location_topic;
obstacle_location_topic = nh.getParam("true_obstacle_topic", obstacle_location_topic);
ros::Subscriber obj_detection_sub = nh.subscribe("obstacle_information", 1000, obstacle_visualization_callback);
ros::spin();
return 0;
} | [
"eichmeierbr@gmail.com"
] | eichmeierbr@gmail.com |
b622f51893bc68cd3eee0fa2d839c93c09888964 | 5f428ff26262012813283099d401880280832682 | /Editor/ResourcesBrowser/EditorResourceBrowser.cpp | 7e53f474bd1bddd756142fd0172bde5d643438da | [] | no_license | ziranjuanchow/ZenonEngine | 42b4e9697ced90a7252293fbe7c66c70637463c8 | 4dbc79eafa75d4d9293409b165fae9fd166a8cc0 | refs/heads/master | 2023-08-20T12:35:44.698443 | 2021-10-29T07:35:25 | 2021-10-29T07:35:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,034 | cpp | #include "stdafx.h"
// General
#include "EditorResourceBrowser.h"
// Additional
#include "EditorUI/DragUtils.h"
#include "TreeViewItems/FolderTreeViewItem.h"
#include "TreeViewItems/ModelTreeViewItem.h"
#include "TreeViewItems/NodeProtoTreeViewItem.h"
#include "TreeViewItems/TextureTreeViewItem.h"
#include "TreeViewItems/ParticleSystemTreeViewItem.h"
#include "TreeViewItems/MaterialTreeViewItem.h"
#include "Filesystem/ResourcesFilesystem.h"
/*
Engine formats:
Models:
*.dds - Texture
*.png - Texture
*.znxobj - xml ZenonEngine object
*.znxscn - xml ZenonEngine scene
*.znxmat - xml material
*.znxgtr - xml geometry
*.fbx - model
*.znmdl - binary model
*.znxmdl - xml model
*/
namespace
{
std::shared_ptr<IznTreeViewItem> ResourceFileToTreeView(const IBaseManager& BaseManager, IScene& Scene, std::shared_ptr<IResourceFile> ResourceFile, ResoureFilterFunc_t ResourceFilterFunc)
{
if (ResourceFile->IsDirectory())
{
auto directoryTreeViewItem = MakeShared(CFolderTreeViewItem, ResourceFile->GetFilenameStruct().NameWithoutExtension);
for (const auto& childResourceFile : ResourceFile->GetChilds())
if (auto treeViewItem = ResourceFileToTreeView(BaseManager, Scene, childResourceFile, ResourceFilterFunc))
directoryTreeViewItem->AddChild(treeViewItem);
// Skip empty directories
if (directoryTreeViewItem->GetChildsCount() == 0)
return nullptr;
return directoryTreeViewItem;
}
else if (ResourceFile->IsFile())
{
_ASSERT(ResourceFile->GetChilds().empty());
if (ResourceFilterFunc)
if (false == ResourceFilterFunc(ResourceFile))
return nullptr;
const auto& fileNameStruct = ResourceFile->GetFilenameStruct();
if (fileNameStruct.Extension == "znmdl" || fileNameStruct.Extension == "znxmdl" || fileNameStruct.Extension == "fbx")
{
auto modelTreeViewItem = MakeShared(CModelTreeViewItem, BaseManager, fileNameStruct.ToString());
BaseManager.GetManager<ILoader>()->AddToLoadQueue(modelTreeViewItem);
return modelTreeViewItem;
}
else if (fileNameStruct.Extension == "znobj")
{
try
{
CXMLManager xmlManager(BaseManager);
auto reader = xmlManager.CreateReaderFromFile(fileNameStruct.ToString());
_ASSERT(false == reader->GetChilds().empty());
auto firstXMLChild = reader->GetChilds()[0];
auto sceneNodeProtoRoot = BaseManager.GetManager<IObjectsFactory>()->GetClassFactoryCast<CSceneNodeFactory>()->LoadSceneNode3DXML(firstXMLChild, Scene);
sceneNodeProtoRoot->MakeMeOrphan();
return MakeShared(CNodeProtoTreeViewItem, sceneNodeProtoRoot);
}
catch (const CException& e)
{
Log::Error("Error while loading '%s' NodeProto.", fileNameStruct.ToString().c_str());
Log::Error("--->%s", e.MessageCStr());
}
}
else if (/*fileNameStruct.Extension == "dds" ||*/ fileNameStruct.Extension == "png")
{
auto textureTreeViewItem = MakeShared(CTextureTreeViewItem, BaseManager, fileNameStruct.ToString());
BaseManager.GetManager<ILoader>()->AddToLoadQueue(textureTreeViewItem);
return textureTreeViewItem;
}
else
Log::Warn("Resource file '%s' has unsupported format.", fileNameStruct.ToString().c_str());
}
return nullptr;
}
}
CEditorResourceBrowser::CEditorResourceBrowser(IEditor& Editor)
: m_Editor(Editor)
{
}
CEditorResourceBrowser::~CEditorResourceBrowser()
{
}
//
// CEditorResourceBrowser
//
void CEditorResourceBrowser::Initialize(ZenonTreeViewWidget* TreeViewWidget)
{
m_TreeViewWidget = TreeViewWidget;
m_TreeViewWidget->SetOnSelectedItemChange(std::bind(&CEditorResourceBrowser::OnSelectTreeItem, this, std::placeholders::_1));
m_TreeViewWidget->SetOnStartDragging(std::bind(&CEditorResourceBrowser::OnStartDraggingTreeItem, this, std::placeholders::_1, std::placeholders::_2));
m_TreeViewWidget->SetOnContexMenu(std::bind(&CEditorResourceBrowser::OnContextMenuTreeItem, this, std::placeholders::_1, std::placeholders::_2));
m_TreeViewWidget->setSelectionMode(QAbstractItemView::SingleSelection);
}
void CEditorResourceBrowser::SetRootFile(std::shared_ptr<IResourceFile> RootResourceFile, ResoureFilterFunc_t ResourceFilterFunc)
{
m_TreeViewWidget->Refresh();
for (const auto& resourceFile : m_Editor.GetFileSystem().GetRootFile()->GetChilds())
{
if (auto treeViewItem = ResourceFileToTreeView(m_Editor.GetBaseManager(), m_Editor.Get3DFrame().GetScene(), resourceFile, ResourceFilterFunc))
{
m_TreeViewWidget->AddToRoot(treeViewItem);
}
}
}
void CEditorResourceBrowser::SetOnResourceSelectedCallback(OnResourceSelected_t Callback)
{
m_OnResourceSelected = Callback;
}
//
// Events
//
bool CEditorResourceBrowser::OnSelectTreeItem(const IznTreeViewItem * Item)
{
if (m_OnResourceSelected)
if (m_OnResourceSelected(Item))
return true;
return false;
}
bool CEditorResourceBrowser::OnStartDraggingTreeItem(const IznTreeViewItem * Item, CByteBuffer * Value)
{
if (Value == nullptr || Value->getSize() > 0 || Value->getPos() > 0)
throw CException("Unable to 'OnStartDraggingTreeItem', because ByteBuffer is not empty.");
auto object = Item->GetObject_();
if (object == nullptr)
return false;
//
// Node proto
//
if (Item->GetType() == ETreeViewItemType::SceneNodeProto)
{
auto objectAsModelAsSceneNodeProto = std::dynamic_pointer_cast<ISceneNode>(object);
if (objectAsModelAsSceneNodeProto == nullptr)
return false;
CreateDragDataFromSceneNodeProto(objectAsModelAsSceneNodeProto, Value);
//GetEditor().GetTools().Enable(ETool::EToolDragger);
return true;
}
//
// Model
//
else if (Item->GetType() == ETreeViewItemType::Model)
{
std::shared_ptr<IModel> objectAsModel = std::dynamic_pointer_cast<IModel>(object);
if (objectAsModel == nullptr)
return false;
CreateDragDataFromModel(objectAsModel, Value);
//GetEditor().GetTools().Enable(ETool::EToolDragger);
return true;
}
//
// Texture
//
else if (Item->GetType() == ETreeViewItemType::Texture)
{
std::shared_ptr<ITexture> objectAsTexture = std::dynamic_pointer_cast<ITexture>(object);
if (objectAsTexture == nullptr)
return false;
CreateDragDataFromTexture(objectAsTexture, Value);
//GetEditor().GetTools().Enable(ETool::EToolDragger);
return true;
}
//
// Particle system
//
else if (Item->GetType() == ETreeViewItemType::ParticleSystem)
{
std::shared_ptr<IParticleSystem> objectAsParticleSystem = std::dynamic_pointer_cast<IParticleSystem>(object);
if (objectAsParticleSystem == nullptr)
return false;
CreateDragDataFromParticleSystem(GetBaseManager(), objectAsParticleSystem, Value);
//GetEditor().GetTools().Enable(ETool::EToolDragger);
return true;
}
return false;
}
bool CEditorResourceBrowser::OnContextMenuTreeItem(const IznTreeViewItem * Item, std::shared_ptr<IPropertiesGroup> PropertiesGroup)
{
if (Item->GetType() != ETreeViewItemType::VirtualFolder)
return false;
PropertiesGroup->SetName("Create");
auto actionsGroupNEW = MakeShared(CPropertiesGroup, "New", "");
// Create ParticleSystem
{
auto createParticleSystemAction = MakeShared(CAction, "ParticlesSystem", "");
createParticleSystemAction->SetAction([this, Item]() -> bool {
auto particleSystem = CreateNewParticle();
auto particleTreeViewItem = MakeShared(CParticleSystemTreeViewItem, particleSystem);
auto itemAsVirtualFolder = dynamic_cast<const IznTreeViewItemFolder*>(Item);
auto itemAsVirtualFolderNonConst = const_cast<IznTreeViewItemFolder*>(itemAsVirtualFolder);
itemAsVirtualFolderNonConst->AddChild(particleTreeViewItem);
m_TreeViewWidget->Refresh();
return true;
});
actionsGroupNEW->AddProperty(createParticleSystemAction);
}
// Create Material
{
auto createMaterialAction = MakeShared(CAction, "Material", "");
createMaterialAction->SetAction([this, Item]() -> bool {
auto material = CreateMaterial();
auto materialTreeViewItem = MakeShared(CMaterialTreeViewItem, material);
auto itemAsVirtualFolder = dynamic_cast<const IznTreeViewItemFolder*>(Item);
auto itemAsVirtualFolderNonConst = const_cast<IznTreeViewItemFolder*>(itemAsVirtualFolder);
itemAsVirtualFolderNonConst->AddChild(materialTreeViewItem);
m_TreeViewWidget->Refresh();
return true;
});
actionsGroupNEW->AddProperty(createMaterialAction);
}
PropertiesGroup->AddProperty(actionsGroupNEW);
return true;
}
std::shared_ptr<IParticleSystem> CEditorResourceBrowser::CreateNewParticle() const
{
auto particleSystem = MakeShared(CParticleSystem, GetBaseManager());
particleSystem->SetName("NewParticleSystem");
particleSystem->SetTexture(GetBaseManager().GetManager<IznTexturesFactory>()->LoadTexture2D("star_09.png"));
return particleSystem;
}
std::shared_ptr<IMaterial> CEditorResourceBrowser::CreateMaterial() const
{
auto material = MakeShared(MaterialModel, GetBaseManager());
material->SetName("NewMaterial");
return material;
}
//
// Private
//
IBaseManager & CEditorResourceBrowser::GetBaseManager() const
{
return m_Editor.GetBaseManager();
}
| [
"alexstenfard@gmail.com"
] | alexstenfard@gmail.com |
467913c585a328c2fc946ba7aefcd52069a65473 | 66e9412cc36346a6ca45d2925520a3a06343fd72 | /source/AsioExpress/MessagePort/Tcp/private/SocketPointer.hpp | 6c7490c846bb50f5d959fd895ef0dac77113722d | [
"BSL-1.0"
] | permissive | LiveMirror/asioexpress | 6795575424a17d6e3f0a28daac3e3ff624a799c4 | 2f3453465934afdcdf4a575a2d933d86929b23c7 | refs/heads/master | 2020-03-31T22:10:38.095924 | 2018-10-11T14:53:47 | 2018-10-11T14:53:47 | 152,608,596 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | hpp | // Copyright Ross MacGregor 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)
#pragma once
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
namespace AsioExpress {
namespace MessagePort {
namespace Tcp {
typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPointer;
} // namespace Tcp
} // namespace MessagePort
} // namespace AsioExpress
| [
"rossmacgregor@2a36de45-7175-4c33-961a-326e2a3a194b"
] | rossmacgregor@2a36de45-7175-4c33-961a-326e2a3a194b |
9d4222602f580e4adaedfa312795724ed3214174 | 21b3c217e8b1ee01f766b54d1b63aca3dc390d0e | /Hard/Candy.cpp | 999628421216ce4acb41f882adbcec0c28c978c2 | [] | no_license | wbangbang/Leetcode | 211916918ce5eda613dfe0edbc342707151b233c | 0019edb38574f2082d71a5fc0cd4fe0b6f7c6c1e | refs/heads/master | 2021-01-10T02:14:58.588216 | 2016-10-09T01:43:06 | 2016-10-09T01:43:06 | 44,226,012 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 580 | cpp | class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
if(!n) return 0;
if(n == 1) return 1;
vector<int> count;
count.assign(n, 1);
for(int i = 1; i < n; i++) {
if(ratings[i] > ratings[i - 1]) count[i] = count[i - 1] + 1;
}
int sum = 0;
for(int i = n - 1; i >= 1; i--) {
if(ratings[i] < ratings[i - 1] && count[i] >= count[i - 1]) count[i - 1] = count[i] + 1;
sum += count[i];
}
sum += count[0];
return sum;
}
}; | [
"xiw274@ucsd.edu"
] | xiw274@ucsd.edu |
07fbb3d06b2008b1f468e695b5aebed54294dfae | a457238ab1657ecf52736f8fbfd83f4aa2eee3c5 | /C++/S24_CPP_Introduction_part6/S24_gift_clear.cpp | 7eabfd026e8fe75a74dda0ccd3760f8e8829812a | [] | no_license | Ernesto-Canales/FUNDA_101_Ernie | 42833750199c7fa960ed2788f985c2dce9bdce47 | 322f8af209d4415a4dd9e038b6c053199ddb37ee | refs/heads/main | 2023-06-11T05:32:57.265311 | 2021-07-02T00:27:21 | 2021-07-02T00:27:21 | 364,095,642 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | #include <iostream>
//#include <string>
int main() {
int n1 = 0;
do {
std::cout << "Ingrese -1 para terminar loop: ";
std::cin >> n1;
std::cin.clear();
std::cin.ignore(100,'\n');
} while (n1 != -1);
std::cout << "Loop end";
return 0;
} | [
"00051120@uca.edu.sv"
] | 00051120@uca.edu.sv |
11dd65cba53f139bed48867d5a6c0e55d73ed687 | c6342c170c6ec88ea71047c6ebf2256b84d7bb96 | /src/Grid.h | dfbb7d3a680555b6821e3f3a250bc5dba156bb97 | [] | no_license | toch88/OpenGl_Plot | 276729dda602387f5234071d1e3b4c0c98b39be9 | f6ff0c13e767571bc9b47e1c26ddaea080fb9329 | refs/heads/TextureModel | 2020-03-08T22:21:31.397246 | 2018-04-07T15:08:46 | 2018-04-07T15:08:46 | 128,428,612 | 0 | 0 | null | 2018-04-07T15:08:47 | 2018-04-06T17:53:05 | Makefile | UTF-8 | C++ | false | false | 322 | h | #pragma once
#include "DisplayManager.h"
#include "LineSegment.h"
#include <vector>
#include <memory>
class Grid
{
float _size;
void prepareLines();
public:
Grid(float size);
std::vector<std::shared_ptr<LineSegment>> verticalLines;
std::vector<std::shared_ptr<LineSegment>> horizontalLines;
}; | [
"tocha.mateusz@gmail.com"
] | tocha.mateusz@gmail.com |
8e9da9cfa79e18ac8c4ec98d6d461690239b8ea0 | 3037b11c061169da1561609f7d93b74f6eb91b8e | /src/TraditionalStereo/ColorPoint.h | cde7160c11789b8073d15083d5af231e59c54141 | [] | no_license | maraatech/traditional_stereo_ros | a1529d042b83b58afd0ba3606e0f978b942de2dd | 8a874e9bc70dbcdaf28e836d3310a075bfcb45bb | refs/heads/main | 2023-06-19T14:11:58.836835 | 2021-07-22T03:13:46 | 2021-07-22T03:13:46 | 309,195,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 700 | h | //--------------------------------------------------
// Defines a 3D point with a color attribute
//
// @author: Wild Boar
//--------------------------------------------------
#pragma once
#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
#include "Math3D.h"
namespace Amantis
{
class ColorPoint
{
private:
Vec3i _color;
Point3d _location;
public:
ColorPoint(const Vec3i& color, const Point3d& location) : _color(color), _location(location) {}
inline Vec3i& GetColor() { return _color; }
inline Point3d& GetLocation() { return _location; }
inline void Transform(Mat& pose) { _location = Math3D::TransformPoint(pose, _location); }
};
}
| [
"trevorgeek@gmail.com"
] | trevorgeek@gmail.com |
c0ddf36a36a0f3ac6490a31e771e34ce2f46f541 | e9e14591fdd0a3404c49377c8b37d35b49da2261 | /include/range/range.hpp | c626da0bc9682e2a1217bb00d273397784b23573 | [] | no_license | Lotrotk/range | c885bf7080ec487a8fcbe5353459a0095d3f5ac9 | c29816cb2b9ecc6b4a19432c3c8fad1d44bc9f50 | refs/heads/master | 2021-09-02T01:20:17.921401 | 2017-12-29T16:09:24 | 2017-12-29T16:09:24 | 115,666,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,757 | hpp | #pragma once
#include <algorithm>
#include <array>
#include <cstdint>
#include <stdexcept>
#include <type_traits>
#include <vector>
namespace rng
{
////////////////////////////////////////////////////////////////
//dynamic/static behavior for independent facets of iterators
//Separate : wheter or not ranges may overlap
//Type : determines size and type of splits (integral numbers or iterators)
////////////////////////////////////////////////////////////////
namespace dyn
{
class Separate
{
public:
explicit Separate(bool const separate) : _separate(separate) {}
bool separate() const { return _separate; }
private:
bool _separate;
};
template<typename T>
class Type
{
public:
using value_t = T;
using split_t = std::vector<T>;
public:
Type(size_t const size) : _size(size)
{
if(size == 0)
{
throw std::runtime_error("There must be at least one split");
}
}
size_t size() const { return _size; }
split_t split(T const &v) const { return split_t(_size, v); }
private:
size_t _size;
};
}
namespace stat
{
template<bool S>
class Separate
{
public:
static constexpr bool separate() { return S; }
};
template<size_t N, typename T>
class Type
{
static_assert(N > 0, "There must be at least one split");
public:
using value_t = T;
using split_t = std::array<T, N>;
public:
static constexpr size_t size() { return N; }
split_t split(T const &v) const { split_t res; res.fill(v); return res; }
};
}
////////////////////////////////////////////////////////////////
//Forward declarations
////////////////////////////////////////////////////////////////
template<typename T>
class range;
template<typename separate_facet, typename type_facet>
class iterable;
template<typename separate_facet, typename type_facet>
class iterator;
template<typename split_t, typename T>
bool has_empty_range(split_t const&, range<T> const&);
////////////////////////////////////////////////////////////////
//Class Definitions
////////////////////////////////////////////////////////////////
template<typename separate_facet, typename type_facet>
class iterator
{
public:
using split_t = typename type_facet::split_t;
using iterable_t = iterable<separate_facet, type_facet>;
public:
iterator(iterator &&other) = default;
iterator &operator=(iterator &&other) = default;
iterator &operator++();
split_t const &operator*() const { return _split; }
bool operator!=(iterator const &other) const { return _split != other._split; }
private:
iterator(iterable_t const &i, typename type_facet::value_t const &v) : _iterable(&i), _split(i.type_facet::split(v)) {}
private:
iterable_t const *_iterable{};
split_t _split;
private:
template<typename, typename> friend class iterable;
};
template<typename T>
class range
{
public:
constexpr range(T begin, T end) : _begin(begin), _end(end) {}
private:
T _begin;
T _end;
private:
template<typename, typename> friend class iterable;
template<typename, typename> friend class iterator;
template<typename s, typename U> friend bool has_empty_range(s const&, range<U> const&);
};
template<typename separate_facet, typename type_facet>
class iterable : private separate_facet, private type_facet
{
public:
using value_t = typename type_facet::value_t;
using range_t = range<value_t>;
using iterator_t = iterator<separate_facet, type_facet>;
public:
constexpr iterable(range_t const &r, separate_facet &&separate, type_facet &&size) : separate_facet(std::move(separate)), type_facet(std::move(size)), _range(r) {}
constexpr iterable(range_t const &r, separate_facet &&separate) : separate_facet(std::move(separate)), _range(r) {}
constexpr iterable(range_t const &r, type_facet &&size) : type_facet(std::move(size)), _range(r) {}
constexpr iterable(range_t const &r) : _range(r) {}
iterator_t begin() const;
iterator_t end() const;
private:
range_t _range;
private:
template<typename, typename> friend class iterator;
};
}
////////////////////////////////////////////////////////////////
//Implementations
////////////////////////////////////////////////////////////////
namespace rng
{
template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
auto rngdistance(T const &a, T const &b) { return b - a; }
template<typename T, typename std::enable_if<!std::is_integral<T>::value, int>::type = 0>
auto rngdistance(T const &a, T const &b) { using std::distance; return distance(a, b); }
template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
void rngadvance(T &a, size_t const d) { a += d; }
template<typename T, typename std::enable_if<!std::is_integral<T>::value, int>::type = 0>
void rngadvance(T &a, size_t const d) { using std::advance; advance(a, d); }
template<typename separate_facet, typename type_facet>
typename iterable<separate_facet, type_facet>::iterator_t iterable<separate_facet, type_facet>::begin() const
{
iterator_t res(*this, _range._begin);
if(separate_facet::separate())
{
size_t const R = rngdistance(_range._begin, _range._end);
for(size_t i=0; i<type_facet::size(); ++i)
{
if(i + 1 < R)
{
rngadvance(res._split[i], i + 1);
}
else
{
res._split[i] = _range._end;
}
}
}
return res;
}
template<typename separate_facet, typename type_facet>
typename iterable<separate_facet, type_facet>::iterator_t iterable<separate_facet, type_facet>::end() const
{
iterator_t res(*this, _range._begin);
res._split[0] = _range._end;
return res;
}
template<typename separate_facet, typename type_facet>
iterator<separate_facet, type_facet> &iterator<separate_facet, type_facet>::operator++()
{
iterator &res = *this;
size_t const N = res._iterable->type_facet::size();
size_t i = 1;
for(; i <= N; ++i)
{
if(res._split[N-i] == res._iterable->_range._end)
{
if(i == N)
{
res = _iterable->end();
return res;
}
continue;
}
break;
}
rngadvance(res._split[N-i], size_t(1));
for(size_t j = N-i+1; j<N; ++j)
{
res._split[j] = res._split[j-1];
if(res._iterable->separate_facet::separate() && res._split[j] != res._iterable->_range._end)
{
rngadvance(res._split[j], size_t(1));
}
}
return res;
}
template<typename split_t, typename T>
bool has_empty_range(split_t const &v, range<T> const &r)
{
return
v.front() == r._begin
||
std::any_of(v.begin(), v.end(), [&r](T const &t) { return t == r._end; })
||
std::adjacent_find(v.begin(), v.end()) != v.end();
}
}
| [
"lotrotk@gmail.com"
] | lotrotk@gmail.com |
b76f0df1634eb60d964096fa48cc2582b4caa365 | 8654435d89790e32f8e4c336e91f23250da0acb0 | /bullet3/examples/ThirdPartyLibs/imgui/imgui_demo.cpp | 7067f351df831653591442fdb14ff67d718393d9 | [
"Zlib",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | takamtd/deepmimic | 226ca68860e5ef206f50d77893dd19af7ac40e46 | b0820fb96ee76b9219bce429fd9b63de103ba40a | refs/heads/main | 2023-05-09T16:48:16.554243 | 2021-06-07T05:04:47 | 2021-06-07T05:04:47 | 373,762,616 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 140,958 | cpp | // dear imgui, v1.60 WIP
// (demo code)
// Message to the person tempted to delete this file when integrating ImGui into their code base:
// Don't do it! Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to.
// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow().
// During development, you can call ImGui::ShowDemoWindow() in your code to learn about various features of ImGui. Have it wired in a debug menu!
// Removing this file from your project is hindering access to documentation for everyone in your team, likely leading you to poorer usage of the library.
// Note that you can #define IMGUI_DISABLE_DEMO_WINDOWS in imconfig.h for the same effect.
// If you want to link core ImGui in your final builds but not those demo windows, #define IMGUI_DISABLE_DEMO_WINDOWS in imconfig.h and those functions will be empty.
// In other situation, when you have ImGui available you probably want this to be available for reference and execution.
// Thank you,
// -Your beloved friend, imgui_demo.cpp (that you won't delete)
// Message to beginner C/C++ programmers. About the meaning of 'static': in this demo code, we frequently we use 'static' variables inside functions.
// We do this as a way to gather code and data in the same place, just to make the demo code faster to read, faster to write, and use less code.
// A static variable persist across calls, so it is essentially like a global variable but declared inside the scope of the function.
// It also happens to be a convenient way of storing simple UI related information as long as your function doesn't need to be reentrant or used in threads.
// This might be a pattern you occasionally want to use in your code, but most of the real data you would be editing is likely to be stored outside your function.
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#include <ctype.h> // toupper, isprint
#include <math.h> // sqrtf, powf, cosf, sinf, floorf, ceilf
#include <stdio.h> // vsnprintf, sscanf, printf
#include <stdlib.h> // NULL, malloc, free, atoi
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#define snprintf _snprintf
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code)
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
#pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#if __has_warning("-Wreserved-id-macro")
#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier //
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure)
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#if (__GNUC__ >= 6)
#pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub.
#endif
#endif
// Play it nice with Windows users. Notepad in 2017 still doesn't display text data with Unix-style \n.
#ifdef _WIN32
#define IM_NEWLINE "\r\n"
#else
#define IM_NEWLINE "\n"
#endif
#define IM_MAX(_A, _B) (((_A) >= (_B)) ? (_A) : (_B))
//-----------------------------------------------------------------------------
// DEMO CODE
//-----------------------------------------------------------------------------
#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && defined(IMGUI_DISABLE_TEST_WINDOWS) && !defined(IMGUI_DISABLE_DEMO_WINDOWS) // Obsolete name since 1.53, TEST->DEMO
#define IMGUI_DISABLE_DEMO_WINDOWS
#endif
#if !defined(IMGUI_DISABLE_DEMO_WINDOWS)
static void ShowExampleAppConsole(bool* p_open);
static void ShowExampleAppLog(bool* p_open);
static void ShowExampleAppLayout(bool* p_open);
static void ShowExampleAppPropertyEditor(bool* p_open);
static void ShowExampleAppLongText(bool* p_open);
static void ShowExampleAppAutoResize(bool* p_open);
static void ShowExampleAppConstrainedResize(bool* p_open);
static void ShowExampleAppFixedOverlay(bool* p_open);
static void ShowExampleAppWindowTitles(bool* p_open);
static void ShowExampleAppCustomRendering(bool* p_open);
static void ShowExampleAppMainMenuBar();
static void ShowExampleMenuFile();
static void ShowHelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
void ImGui::ShowUserGuide()
{
ImGui::BulletText("Double-click on title bar to collapse window.");
ImGui::BulletText("Click and drag on lower right corner to resize window\n(double-click to auto fit window to its contents).");
ImGui::BulletText("Click and drag on any empty space to move window.");
ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields.");
ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text.");
if (ImGui::GetIO().FontAllowUserScaling)
ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents.");
ImGui::BulletText("Mouse Wheel to scroll.");
ImGui::BulletText("While editing text:\n");
ImGui::Indent();
ImGui::BulletText("Hold SHIFT or use mouse to select text.");
ImGui::BulletText("CTRL+Left/Right to word jump.");
ImGui::BulletText("CTRL+A or double-click to select all.");
ImGui::BulletText("CTRL+X,CTRL+C,CTRL+V to use clipboard.");
ImGui::BulletText("CTRL+Z,CTRL+Y to undo/redo.");
ImGui::BulletText("ESCAPE to revert.");
ImGui::BulletText("You can apply arithmetic operators +,*,/ on numerical values.\nUse +- to subtract.");
ImGui::Unindent();
}
// Demonstrate most ImGui features (big function!)
void ImGui::ShowDemoWindow(bool* p_open)
{
// Examples apps
static bool show_app_main_menu_bar = false;
static bool show_app_console = false;
static bool show_app_log = false;
static bool show_app_layout = false;
static bool show_app_property_editor = false;
static bool show_app_long_text = false;
static bool show_app_auto_resize = false;
static bool show_app_constrained_resize = false;
static bool show_app_fixed_overlay = false;
static bool show_app_window_titles = false;
static bool show_app_custom_rendering = false;
static bool show_app_style_editor = false;
static bool show_app_metrics = false;
static bool show_app_about = false;
if (show_app_main_menu_bar) ShowExampleAppMainMenuBar();
if (show_app_console) ShowExampleAppConsole(&show_app_console);
if (show_app_log) ShowExampleAppLog(&show_app_log);
if (show_app_layout) ShowExampleAppLayout(&show_app_layout);
if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor);
if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text);
if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize);
if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize);
if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay);
if (show_app_window_titles) ShowExampleAppWindowTitles(&show_app_window_titles);
if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering);
if (show_app_metrics)
{
ImGui::ShowMetricsWindow(&show_app_metrics);
}
if (show_app_style_editor)
{
ImGui::Begin("Style Editor", &show_app_style_editor);
ImGui::ShowStyleEditor();
ImGui::End();
}
if (show_app_about)
{
ImGui::Begin("About Dear ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::Text("Dear ImGui, %s", ImGui::GetVersion());
ImGui::Separator();
ImGui::Text("By Omar Cornut and all dear imgui contributors.");
ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information.");
ImGui::End();
}
static bool no_titlebar = false;
static bool no_scrollbar = false;
static bool no_menu = false;
static bool no_move = false;
static bool no_resize = false;
static bool no_collapse = false;
static bool no_close = false;
static bool no_nav = false;
// Demonstrate the various window flags. Typically you would just use the default.
ImGuiWindowFlags window_flags = 0;
if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar;
if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar;
if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar;
if (no_move) window_flags |= ImGuiWindowFlags_NoMove;
if (no_resize) window_flags |= ImGuiWindowFlags_NoResize;
if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse;
if (no_nav) window_flags |= ImGuiWindowFlags_NoNav;
if (no_close) p_open = NULL; // Don't pass our bool* to Begin
ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("ImGui Demo", p_open, window_flags))
{
// Early out if the window is collapsed, as an optimization.
ImGui::End();
return;
}
//ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels
ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels
ImGui::Text("dear imgui says hello. (%s)", IMGUI_VERSION);
// Menu
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("Menu"))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Examples"))
{
ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar);
ImGui::MenuItem("Console", NULL, &show_app_console);
ImGui::MenuItem("Log", NULL, &show_app_log);
ImGui::MenuItem("Simple layout", NULL, &show_app_layout);
ImGui::MenuItem("Property editor", NULL, &show_app_property_editor);
ImGui::MenuItem("Long text display", NULL, &show_app_long_text);
ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize);
ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize);
ImGui::MenuItem("Simple overlay", NULL, &show_app_fixed_overlay);
ImGui::MenuItem("Manipulating window titles", NULL, &show_app_window_titles);
ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Help"))
{
ImGui::MenuItem("Metrics", NULL, &show_app_metrics);
ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor);
ImGui::MenuItem("About Dear ImGui", NULL, &show_app_about);
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::Spacing();
if (ImGui::CollapsingHeader("Help"))
{
ImGui::TextWrapped("This window is being created by the ShowDemoWindow() function. Please refer to the code in imgui_demo.cpp for reference.\n\n");
ImGui::Text("USER GUIDE:");
ImGui::ShowUserGuide();
}
if (ImGui::CollapsingHeader("Window options"))
{
ImGui::Checkbox("No titlebar", &no_titlebar);
ImGui::SameLine(150);
ImGui::Checkbox("No scrollbar", &no_scrollbar);
ImGui::SameLine(300);
ImGui::Checkbox("No menu", &no_menu);
ImGui::Checkbox("No move", &no_move);
ImGui::SameLine(150);
ImGui::Checkbox("No resize", &no_resize);
ImGui::SameLine(300);
ImGui::Checkbox("No collapse", &no_collapse);
ImGui::Checkbox("No close", &no_close);
ImGui::SameLine(150);
ImGui::Checkbox("No nav", &no_nav);
if (ImGui::TreeNode("Style"))
{
ImGui::ShowStyleEditor();
ImGui::TreePop();
}
if (ImGui::TreeNode("Capture/Logging"))
{
ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded. You can also call ImGui::LogText() to output directly to the log without a visual output.");
ImGui::LogButtons();
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Widgets"))
{
if (ImGui::TreeNode("Basic"))
{
static int clicked = 0;
if (ImGui::Button("Button"))
clicked++;
if (clicked & 1)
{
ImGui::SameLine();
ImGui::Text("Thanks for clicking me!");
}
static bool check = true;
ImGui::Checkbox("checkbox", &check);
static int e = 0;
ImGui::RadioButton("radio a", &e, 0);
ImGui::SameLine();
ImGui::RadioButton("radio b", &e, 1);
ImGui::SameLine();
ImGui::RadioButton("radio c", &e, 2);
// Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style.
for (int i = 0; i < 7; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f));
ImGui::Button("Click");
ImGui::PopStyleColor(3);
ImGui::PopID();
}
ImGui::Text("Hover over me");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("I am a tooltip");
ImGui::SameLine();
ImGui::Text("- or me");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::Text("I am a fancy tooltip");
static float arr[] = {0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f};
ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr));
ImGui::EndTooltip();
}
// Testing ImGuiOnceUponAFrame helper.
//static ImGuiOnceUponAFrame once;
//for (int i = 0; i < 5; i++)
// if (once)
// ImGui::Text("This will be displayed only once.");
ImGui::Separator();
ImGui::LabelText("label", "Value");
{
// Simplified one-liner Combo() API, using values packed in a single constant string
static int current_item_1 = 1;
ImGui::Combo("combo", ¤t_item_1, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
//ImGui::Combo("combo w/ array of char*", ¤t_item_2_idx, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that.
// General BeginCombo() API, you have full control over your selection data and display type
const char* items[] = {"AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO", "PPPP", "QQQQQQQQQQ", "RRR", "SSSS"};
static const char* current_item_2 = NULL;
if (ImGui::BeginCombo("combo 2", current_item_2)) // The second parameter is the label previewed before opening the combo.
{
for (int n = 0; n < IM_ARRAYSIZE(items); n++)
{
bool is_selected = (current_item_2 == items[n]); // You can store your selection however you want, outside or inside your objects
if (ImGui::Selectable(items[n], is_selected))
current_item_2 = items[n];
if (is_selected)
ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch)
}
ImGui::EndCombo();
}
}
{
static char str0[128] = "Hello, world!";
static int i0 = 123;
static float f0 = 0.001f;
ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0));
ImGui::SameLine();
ShowHelpMarker(
"Hold SHIFT or use mouse to select text.\n"
"CTRL+Left/Right to word jump.\n"
"CTRL+A or double-click to select all.\n"
"CTRL+X,CTRL+C,CTRL+V clipboard.\n"
"CTRL+Z,CTRL+Y undo/redo.\n"
"ESCAPE to revert.\n");
ImGui::InputInt("input int", &i0);
ImGui::SameLine();
ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n");
ImGui::InputFloat("input float", &f0, 0.01f, 1.0f);
static float vec4a[4] = {0.10f, 0.20f, 0.30f, 0.44f};
ImGui::InputFloat3("input float3", vec4a);
}
{
static int i1 = 50, i2 = 42;
ImGui::DragInt("drag int", &i1, 1);
ImGui::SameLine();
ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value.");
ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%");
static float f1 = 1.00f, f2 = 0.0067f;
ImGui::DragFloat("drag float", &f1, 0.005f);
ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns");
}
{
static int i1 = 0;
ImGui::SliderInt("slider int", &i1, -1, 3);
ImGui::SameLine();
ShowHelpMarker("CTRL+click to input value.");
static float f1 = 0.123f, f2 = 0.0f;
ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f);
static float angle = 0.0f;
ImGui::SliderAngle("slider angle", &angle);
}
static float col1[3] = {1.0f, 0.0f, 0.2f};
static float col2[4] = {0.4f, 0.7f, 0.0f, 0.5f};
ImGui::ColorEdit3("color 1", col1);
ImGui::SameLine();
ShowHelpMarker("Click on the colored square to open a color picker.\nRight-click on the colored square to show options.\nCTRL+click on individual component to input value.\n");
ImGui::ColorEdit4("color 2", col2);
const char* listbox_items[] = {"Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon"};
static int listbox_item_current = 1;
ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
//static int listbox_item_current2 = 2;
//ImGui::PushItemWidth(-1);
//ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
//ImGui::PopItemWidth();
ImGui::TreePop();
}
if (ImGui::TreeNode("Trees"))
{
if (ImGui::TreeNode("Basic trees"))
{
for (int i = 0; i < 5; i++)
if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i))
{
ImGui::Text("blah blah");
ImGui::SameLine();
if (ImGui::SmallButton("button"))
{
};
ImGui::TreePop();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Advanced, with Selectable nodes"))
{
ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open.");
static bool align_label_with_current_x_position = false;
ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position);
ImGui::Text("Hello!");
if (align_label_with_current_x_position)
ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit.
int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc.
ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize() * 3); // Increase spacing to differentiate leaves from expanded contents.
for (int i = 0; i < 6; i++)
{
// Disable the default open on single-click behavior and pass in Selected flag according to our selection state.
ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0);
if (i < 3)
{
// Node
bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i);
if (ImGui::IsItemClicked())
node_clicked = i;
if (node_open)
{
ImGui::Text("Blah blah\nBlah Blah");
ImGui::TreePop();
}
}
else
{
// Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text().
node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet
ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i);
if (ImGui::IsItemClicked())
node_clicked = i;
}
}
if (node_clicked != -1)
{
// Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame.
if (ImGui::GetIO().KeyCtrl)
selection_mask ^= (1 << node_clicked); // CTRL+click to toggle
else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection
selection_mask = (1 << node_clicked); // Click to single-select
}
ImGui::PopStyleVar();
if (align_label_with_current_x_position)
ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
ImGui::TreePop();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Collapsing Headers"))
{
static bool closable_group = true;
ImGui::Checkbox("Enable extra group", &closable_group);
if (ImGui::CollapsingHeader("Header"))
{
ImGui::Text("IsItemHovered: %d", IsItemHovered());
for (int i = 0; i < 5; i++)
ImGui::Text("Some content %d", i);
}
if (ImGui::CollapsingHeader("Header with a close button", &closable_group))
{
ImGui::Text("IsItemHovered: %d", IsItemHovered());
for (int i = 0; i < 5; i++)
ImGui::Text("More content %d", i);
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Bullets"))
{
ImGui::BulletText("Bullet point 1");
ImGui::BulletText("Bullet point 2\nOn multiple lines");
ImGui::Bullet();
ImGui::Text("Bullet point 3 (two calls)");
ImGui::Bullet();
ImGui::SmallButton("Button");
ImGui::TreePop();
}
if (ImGui::TreeNode("Text"))
{
if (ImGui::TreeNode("Colored Text"))
{
// Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility.
ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink");
ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow");
ImGui::TextDisabled("Disabled");
ImGui::SameLine();
ShowHelpMarker("The TextDisabled color is stored in ImGuiStyle.");
ImGui::TreePop();
}
if (ImGui::TreeNode("Word Wrapping"))
{
// Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility.
ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages.");
ImGui::Spacing();
static float wrap_width = 200.0f;
ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f");
ImGui::Text("Test paragraph 1:");
ImVec2 pos = ImGui::GetCursorScreenPos();
ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255, 0, 255, 255));
ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
ImGui::Text("The lazy dog is a good dog. This paragraph is made to fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width);
ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255));
ImGui::PopTextWrapPos();
ImGui::Text("Test paragraph 2:");
pos = ImGui::GetCursorScreenPos();
ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255, 0, 255, 255));
ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh");
ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255));
ImGui::PopTextWrapPos();
ImGui::TreePop();
}
if (ImGui::TreeNode("UTF-8 Text"))
{
// UTF-8 test with Japanese characters
// (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html)
// - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8
// - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. Visual Studio save your file as 'UTF-8 without signature')
// - HOWEVER, FOR THIS DEMO FILE, BECAUSE WE WANT TO SUPPORT COMPILER, WE ARE *NOT* INCLUDING RAW UTF-8 CHARACTERS IN THIS SOURCE FILE.
// Instead we are encoding a few string with hexadecimal constants. Don't do this in your application!
// Note that characters values are preserved even by InputText() if the font cannot be displayed, so you can safely copy & paste garbled characters into another application.
ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges.");
ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)");
ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)");
static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; // "nihongo"
ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf));
ImGui::TreePop();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Images"))
{
ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!");
ImGuiIO& io = ImGui::GetIO();
// Here we are grabbing the font texture because that's the only one we have access to inside the demo code.
// Remember that ImTextureID is just storage for whatever you want it to be, it is essentially a value that will be passed to the render function inside the ImDrawCmd structure.
// If you use one of the default imgui_impl_XXXX.cpp renderer, they all have comments at the top of their file to specify what they expect to be stored in ImTextureID.
// (for example, the imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer. The imgui_impl_glfw_gl3.cpp renderer expect a GLuint OpenGL texture identifier etc.)
// If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers to ImGui::Image(), and gather width/height through your own functions, etc.
// Using ShowMetricsWindow() as a "debugger" to inspect the draw data that are being passed to your render will help you debug issues if you are confused about this.
// Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage().
ImTextureID my_tex_id = io.Fonts->TexID;
float my_tex_w = (float)io.Fonts->TexWidth;
float my_tex_h = (float)io.Fonts->TexHeight;
ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h);
ImVec2 pos = ImGui::GetCursorScreenPos();
ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128));
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
float focus_sz = 32.0f;
float focus_x = io.MousePos.x - pos.x - focus_sz * 0.5f;
if (focus_x < 0.0f)
focus_x = 0.0f;
else if (focus_x > my_tex_w - focus_sz)
focus_x = my_tex_w - focus_sz;
float focus_y = io.MousePos.y - pos.y - focus_sz * 0.5f;
if (focus_y < 0.0f)
focus_y = 0.0f;
else if (focus_y > my_tex_h - focus_sz)
focus_y = my_tex_h - focus_sz;
ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y);
ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz);
ImVec2 uv0 = ImVec2((focus_x) / my_tex_w, (focus_y) / my_tex_h);
ImVec2 uv1 = ImVec2((focus_x + focus_sz) / my_tex_w, (focus_y + focus_sz) / my_tex_h);
ImGui::Image(my_tex_id, ImVec2(128, 128), uv0, uv1, ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128));
ImGui::EndTooltip();
}
ImGui::TextWrapped("And now some textured buttons..");
static int pressed_count = 0;
for (int i = 0; i < 8; i++)
{
ImGui::PushID(i);
int frame_padding = -1 + i; // -1 = uses default padding
if (ImGui::ImageButton(my_tex_id, ImVec2(32, 32), ImVec2(0, 0), ImVec2(32.0f / my_tex_w, 32 / my_tex_h), frame_padding, ImColor(0, 0, 0, 255)))
pressed_count += 1;
ImGui::PopID();
ImGui::SameLine();
}
ImGui::NewLine();
ImGui::Text("Pressed %d times.", pressed_count);
ImGui::TreePop();
}
if (ImGui::TreeNode("Selectables"))
{
// Selectable() has 2 overloads:
// - The one taking "bool selected" as a read-only selection information. When Selectable() has been clicked is returns true and you can alter selection state accordingly.
// - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases)
// The earlier is more flexible, as in real application your selection may be stored in a different manner (in flags within objects, as an external list, etc).
if (ImGui::TreeNode("Basic"))
{
static bool selection[5] = {false, true, false, false, false};
ImGui::Selectable("1. I am selectable", &selection[0]);
ImGui::Selectable("2. I am selectable", &selection[1]);
ImGui::Text("3. I am not selectable");
ImGui::Selectable("4. I am selectable", &selection[3]);
if (ImGui::Selectable("5. I am double clickable", selection[4], ImGuiSelectableFlags_AllowDoubleClick))
if (ImGui::IsMouseDoubleClicked(0))
selection[4] = !selection[4];
ImGui::TreePop();
}
if (ImGui::TreeNode("Selection State: Single Selection"))
{
static int selected = -1;
for (int n = 0; n < 5; n++)
{
char buf[32];
sprintf(buf, "Object %d", n);
if (ImGui::Selectable(buf, selected == n))
selected = n;
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Selection State: Multiple Selection"))
{
ShowHelpMarker("Hold CTRL and click to select multiple items.");
static bool selection[5] = {false, false, false, false, false};
for (int n = 0; n < 5; n++)
{
char buf[32];
sprintf(buf, "Object %d", n);
if (ImGui::Selectable(buf, selection[n]))
{
if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held
memset(selection, 0, sizeof(selection));
selection[n] ^= 1;
}
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Rendering more text into the same line"))
{
// Using the Selectable() override that takes "bool* p_selected" parameter and toggle your booleans automatically.
static bool selected[3] = {false, false, false};
ImGui::Selectable("main.c", &selected[0]);
ImGui::SameLine(300);
ImGui::Text(" 2,345 bytes");
ImGui::Selectable("Hello.cpp", &selected[1]);
ImGui::SameLine(300);
ImGui::Text("12,345 bytes");
ImGui::Selectable("Hello.h", &selected[2]);
ImGui::SameLine(300);
ImGui::Text(" 2,345 bytes");
ImGui::TreePop();
}
if (ImGui::TreeNode("In columns"))
{
ImGui::Columns(3, NULL, false);
static bool selected[16] = {0};
for (int i = 0; i < 16; i++)
{
char label[32];
sprintf(label, "Item %d", i);
if (ImGui::Selectable(label, &selected[i]))
{
}
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::TreePop();
}
if (ImGui::TreeNode("Grid"))
{
static bool selected[16] = {true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true};
for (int i = 0; i < 16; i++)
{
ImGui::PushID(i);
if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50, 50)))
{
int x = i % 4, y = i / 4;
if (x > 0) selected[i - 1] ^= 1;
if (x < 3) selected[i + 1] ^= 1;
if (y > 0) selected[i - 4] ^= 1;
if (y < 3) selected[i + 4] ^= 1;
}
if ((i % 4) < 3) ImGui::SameLine();
ImGui::PopID();
}
ImGui::TreePop();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Filtered Text Input"))
{
static char buf1[64] = "";
ImGui::InputText("default", buf1, 64);
static char buf2[64] = "";
ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal);
static char buf3[64] = "";
ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
static char buf4[64] = "";
ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase);
static char buf5[64] = "";
ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank);
struct TextFilters
{
static int FilterImGuiLetters(ImGuiTextEditCallbackData* data)
{
if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0;
return 1;
}
};
static char buf6[64] = "";
ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters);
ImGui::Text("Password input");
static char bufpass[64] = "password123";
ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank);
ImGui::SameLine();
ShowHelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n");
ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank);
ImGui::TreePop();
}
if (ImGui::TreeNode("Multi-line Text Input"))
{
static bool read_only = false;
static char text[1024 * 16] =
"/*\n"
" The Pentium F00F bug, shorthand for F0 0F C7 C8,\n"
" the hexadecimal encoding of one offending instruction,\n"
" more formally, the invalid operand with locked CMPXCHG8B\n"
" instruction bug, is a design flaw in the majority of\n"
" Intel Pentium, Pentium MMX, and Pentium OverDrive\n"
" processors (all in the P5 microarchitecture).\n"
"*/\n\n"
"label:\n"
"\tlock cmpxchg8b eax\n";
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::Checkbox("Read-only", &read_only);
ImGui::PopStyleVar();
ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0));
ImGui::TreePop();
}
if (ImGui::TreeNode("Plots widgets"))
{
static bool animate = true;
ImGui::Checkbox("Animate", &animate);
static float arr[] = {0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f};
ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr));
// Create a dummy array of contiguous float values to plot
// Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter.
static float values[90] = {0};
static int values_offset = 0;
static float refresh_time = 0.0f;
if (!animate || refresh_time == 0.0f)
refresh_time = ImGui::GetTime();
while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 hz rate for the demo
{
static float phase = 0.0f;
values[values_offset] = cosf(phase);
values_offset = (values_offset + 1) % IM_ARRAYSIZE(values);
phase += 0.10f * values_offset;
refresh_time += 1.0f / 60.0f;
}
ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0, 80));
ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80));
// Use functions to generate output
// FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count.
struct Funcs
{
static float Sin(void*, int i) { return sinf(i * 0.1f); }
static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; }
};
static int func_type = 0, display_count = 70;
ImGui::Separator();
ImGui::PushItemWidth(100);
ImGui::Combo("func", &func_type, "Sin\0Saw\0");
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::SliderInt("Sample count", &display_count, 1, 400);
float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw;
ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));
ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));
ImGui::Separator();
// Animate a simple progress bar
static float progress = 0.0f, progress_dir = 1.0f;
if (animate)
{
progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime;
if (progress >= +1.1f)
{
progress = +1.1f;
progress_dir *= -1.0f;
}
if (progress <= -0.1f)
{
progress = -0.1f;
progress_dir *= -1.0f;
}
}
// Typically we would use ImVec2(-1.0f,0.0f) to use all available width, or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth.
ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f));
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
ImGui::Text("Progress Bar");
float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress;
char buf[32];
sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753);
ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf);
ImGui::TreePop();
}
if (ImGui::TreeNode("Color/Picker Widgets"))
{
static ImVec4 color = ImColor(114, 144, 154, 200);
static bool alpha_preview = true;
static bool alpha_half_preview = false;
static bool options_menu = true;
static bool hdr = false;
ImGui::Checkbox("With Alpha Preview", &alpha_preview);
ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview);
ImGui::Checkbox("With Options Menu", &options_menu);
ImGui::SameLine();
ShowHelpMarker("Right-click on the individual color widget to show options.");
ImGui::Checkbox("With HDR", &hdr);
ImGui::SameLine();
ShowHelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets.");
int misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);
ImGui::Text("Color widget:");
ImGui::SameLine();
ShowHelpMarker("Click on the colored square to open a color picker.\nCTRL+click on individual component to input value.\n");
ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags);
ImGui::Text("Color widget HSV with Alpha:");
ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_HSV | misc_flags);
ImGui::Text("Color widget with Float Display:");
ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags);
ImGui::Text("Color button with Picker:");
ImGui::SameLine();
ShowHelpMarker("With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\nWith the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only be used for the tooltip and picker popup.");
ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags);
ImGui::Text("Color button with Custom Picker Popup:");
// Generate a dummy palette
static bool saved_palette_inited = false;
static ImVec4 saved_palette[32];
if (!saved_palette_inited)
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
{
ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, saved_palette[n].x, saved_palette[n].y, saved_palette[n].z);
saved_palette[n].w = 1.0f; // Alpha
}
saved_palette_inited = true;
static ImVec4 backup_color;
bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags);
ImGui::SameLine();
open_popup |= ImGui::Button("Palette");
if (open_popup)
{
ImGui::OpenPopup("mypicker");
backup_color = color;
}
if (ImGui::BeginPopup("mypicker"))
{
// FIXME: Adding a drag and drop example here would be perfect!
ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!");
ImGui::Separator();
ImGui::ColorPicker4("##picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview);
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::Text("Current");
ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40));
ImGui::Text("Previous");
if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)))
color = backup_color;
ImGui::Separator();
ImGui::Text("Palette");
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
{
ImGui::PushID(n);
if ((n % 8) != 0)
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y);
if (ImGui::ColorButton("##palette", saved_palette[n], ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip, ImVec2(20, 20)))
color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha!
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3);
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4);
EndDragDropTarget();
}
ImGui::PopID();
}
ImGui::EndGroup();
ImGui::EndPopup();
}
ImGui::Text("Color button only:");
ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags, ImVec2(80, 80));
ImGui::Text("Color picker:");
static bool alpha = true;
static bool alpha_bar = true;
static bool side_preview = true;
static bool ref_color = false;
static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f);
static int inputs_mode = 2;
static int picker_mode = 0;
ImGui::Checkbox("With Alpha", &alpha);
ImGui::Checkbox("With Alpha Bar", &alpha_bar);
ImGui::Checkbox("With Side Preview", &side_preview);
if (side_preview)
{
ImGui::SameLine();
ImGui::Checkbox("With Ref Color", &ref_color);
if (ref_color)
{
ImGui::SameLine();
ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags);
}
}
ImGui::Combo("Inputs Mode", &inputs_mode, "All Inputs\0No Inputs\0RGB Input\0HSV Input\0HEX Input\0");
ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0");
ImGui::SameLine();
ShowHelpMarker("User can right-click the picker to change mode.");
ImGuiColorEditFlags flags = misc_flags;
if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4()
if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar;
if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview;
if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar;
if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel;
if (inputs_mode == 1) flags |= ImGuiColorEditFlags_NoInputs;
if (inputs_mode == 2) flags |= ImGuiColorEditFlags_RGB;
if (inputs_mode == 3) flags |= ImGuiColorEditFlags_HSV;
if (inputs_mode == 4) flags |= ImGuiColorEditFlags_HEX;
ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL);
ImGui::Text("Programmatically set defaults/options:");
ImGui::SameLine();
ShowHelpMarker("SetColorEditOptions() is designed to allow you to set boot-time default.\nWe don't have Push/Pop functions because you can force options on a per-widget basis if needed, and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid encouraging you to persistently save values that aren't forward-compatible.");
if (ImGui::Button("Uint8 + HSV"))
ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_HSV);
ImGui::SameLine();
if (ImGui::Button("Float + HDR"))
ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_RGB);
ImGui::TreePop();
}
if (ImGui::TreeNode("Range Widgets"))
{
static float begin = 10, end = 90;
static int begin_i = 100, end_i = 1000;
ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%");
ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %.0f units", "Max: %.0f units");
ImGui::TreePop();
}
if (ImGui::TreeNode("Multi-component Widgets"))
{
static float vec4f[4] = {0.10f, 0.20f, 0.30f, 0.44f};
static int vec4i[4] = {1, 5, 100, 255};
ImGui::InputFloat2("input float2", vec4f);
ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f);
ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f);
ImGui::DragInt2("drag int2", vec4i, 1, 0, 255);
ImGui::InputInt2("input int2", vec4i);
ImGui::SliderInt2("slider int2", vec4i, 0, 255);
ImGui::Spacing();
ImGui::InputFloat3("input float3", vec4f);
ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f);
ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f);
ImGui::DragInt3("drag int3", vec4i, 1, 0, 255);
ImGui::InputInt3("input int3", vec4i);
ImGui::SliderInt3("slider int3", vec4i, 0, 255);
ImGui::Spacing();
ImGui::InputFloat4("input float4", vec4f);
ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f);
ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f);
ImGui::InputInt4("input int4", vec4i);
ImGui::DragInt4("drag int4", vec4i, 1, 0, 255);
ImGui::SliderInt4("slider int4", vec4i, 0, 255);
ImGui::TreePop();
}
if (ImGui::TreeNode("Vertical Sliders"))
{
const float spacing = 4;
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing));
static int int_value = 0;
ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5);
ImGui::SameLine();
static float values[7] = {0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f};
ImGui::PushID("set1");
for (int i = 0; i < 7; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f));
ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f));
ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f));
ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f));
ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, "");
if (ImGui::IsItemActive() || ImGui::IsItemHovered())
ImGui::SetTooltip("%.3f", values[i]);
ImGui::PopStyleColor(4);
ImGui::PopID();
}
ImGui::PopID();
ImGui::SameLine();
ImGui::PushID("set2");
static float values2[4] = {0.20f, 0.80f, 0.40f, 0.25f};
const int rows = 3;
const ImVec2 small_slider_size(18, (160.0f - (rows - 1) * spacing) / rows);
for (int nx = 0; nx < 4; nx++)
{
if (nx > 0) ImGui::SameLine();
ImGui::BeginGroup();
for (int ny = 0; ny < rows; ny++)
{
ImGui::PushID(nx * rows + ny);
ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, "");
if (ImGui::IsItemActive() || ImGui::IsItemHovered())
ImGui::SetTooltip("%.3f", values2[nx]);
ImGui::PopID();
}
ImGui::EndGroup();
}
ImGui::PopID();
ImGui::SameLine();
ImGui::PushID("set3");
for (int i = 0; i < 4; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40);
ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec");
ImGui::PopStyleVar();
ImGui::PopID();
}
ImGui::PopID();
ImGui::PopStyleVar();
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Layout"))
{
if (ImGui::TreeNode("Child regions"))
{
static bool disable_mouse_wheel = false;
static bool disable_menu = false;
ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel);
ImGui::Checkbox("Disable Menu", &disable_menu);
static int line = 50;
bool goto_line = ImGui::Button("Goto");
ImGui::SameLine();
ImGui::PushItemWidth(100);
goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue);
ImGui::PopItemWidth();
// Child 1: no border, enable horizontal scrollbar
{
ImGui::BeginChild("Child1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 300), false, ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0));
for (int i = 0; i < 100; i++)
{
ImGui::Text("%04d: scrollable region", i);
if (goto_line && line == i)
ImGui::SetScrollHere();
}
if (goto_line && line >= 100)
ImGui::SetScrollHere();
ImGui::EndChild();
}
ImGui::SameLine();
// Child 2: rounded border
{
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
ImGui::BeginChild("Child2", ImVec2(0, 300), true, (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0) | (disable_menu ? 0 : ImGuiWindowFlags_MenuBar));
if (!disable_menu && ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("Menu"))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::Columns(2);
for (int i = 0; i < 100; i++)
{
if (i == 50)
ImGui::NextColumn();
char buf[32];
sprintf(buf, "%08x", i * 5731);
ImGui::Button(buf, ImVec2(-1.0f, 0.0f));
}
ImGui::EndChild();
ImGui::PopStyleVar();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Widgets Width"))
{
static float f = 0.0f;
ImGui::Text("PushItemWidth(100)");
ImGui::SameLine();
ShowHelpMarker("Fixed width.");
ImGui::PushItemWidth(100);
ImGui::DragFloat("float##1", &f);
ImGui::PopItemWidth();
ImGui::Text("PushItemWidth(GetWindowWidth() * 0.5f)");
ImGui::SameLine();
ShowHelpMarker("Half of window width.");
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
ImGui::DragFloat("float##2", &f);
ImGui::PopItemWidth();
ImGui::Text("PushItemWidth(GetContentRegionAvailWidth() * 0.5f)");
ImGui::SameLine();
ShowHelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)");
ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f);
ImGui::DragFloat("float##3", &f);
ImGui::PopItemWidth();
ImGui::Text("PushItemWidth(-100)");
ImGui::SameLine();
ShowHelpMarker("Align to right edge minus 100");
ImGui::PushItemWidth(-100);
ImGui::DragFloat("float##4", &f);
ImGui::PopItemWidth();
ImGui::Text("PushItemWidth(-1)");
ImGui::SameLine();
ShowHelpMarker("Align to right edge");
ImGui::PushItemWidth(-1);
ImGui::DragFloat("float##5", &f);
ImGui::PopItemWidth();
ImGui::TreePop();
}
if (ImGui::TreeNode("Basic Horizontal Layout"))
{
ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)");
// Text
ImGui::Text("Two items: Hello");
ImGui::SameLine();
ImGui::TextColored(ImVec4(1, 1, 0, 1), "Sailor");
// Adjust spacing
ImGui::Text("More spacing: Hello");
ImGui::SameLine(0, 20);
ImGui::TextColored(ImVec4(1, 1, 0, 1), "Sailor");
// Button
ImGui::AlignTextToFramePadding();
ImGui::Text("Normal buttons");
ImGui::SameLine();
ImGui::Button("Banana");
ImGui::SameLine();
ImGui::Button("Apple");
ImGui::SameLine();
ImGui::Button("Corniflower");
// Button
ImGui::Text("Small buttons");
ImGui::SameLine();
ImGui::SmallButton("Like this one");
ImGui::SameLine();
ImGui::Text("can fit within a text block.");
// Aligned to arbitrary position. Easy/cheap column.
ImGui::Text("Aligned");
ImGui::SameLine(150);
ImGui::Text("x=150");
ImGui::SameLine(300);
ImGui::Text("x=300");
ImGui::Text("Aligned");
ImGui::SameLine(150);
ImGui::SmallButton("x=150");
ImGui::SameLine(300);
ImGui::SmallButton("x=300");
// Checkbox
static bool c1 = false, c2 = false, c3 = false, c4 = false;
ImGui::Checkbox("My", &c1);
ImGui::SameLine();
ImGui::Checkbox("Tailor", &c2);
ImGui::SameLine();
ImGui::Checkbox("Is", &c3);
ImGui::SameLine();
ImGui::Checkbox("Rich", &c4);
// Various
static float f0 = 1.0f, f1 = 2.0f, f2 = 3.0f;
ImGui::PushItemWidth(80);
const char* items[] = {"AAAA", "BBBB", "CCCC", "DDDD"};
static int item = -1;
ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items));
ImGui::SameLine();
ImGui::SliderFloat("X", &f0, 0.0f, 5.0f);
ImGui::SameLine();
ImGui::SliderFloat("Y", &f1, 0.0f, 5.0f);
ImGui::SameLine();
ImGui::SliderFloat("Z", &f2, 0.0f, 5.0f);
ImGui::PopItemWidth();
ImGui::PushItemWidth(80);
ImGui::Text("Lists:");
static int selection[4] = {0, 1, 2, 3};
for (int i = 0; i < 4; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items));
ImGui::PopID();
//if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i);
}
ImGui::PopItemWidth();
// Dummy
ImVec2 sz(30, 30);
ImGui::Button("A", sz);
ImGui::SameLine();
ImGui::Dummy(sz);
ImGui::SameLine();
ImGui::Button("B", sz);
ImGui::TreePop();
}
if (ImGui::TreeNode("Groups"))
{
ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it.)");
ImGui::BeginGroup();
{
ImGui::BeginGroup();
ImGui::Button("AAA");
ImGui::SameLine();
ImGui::Button("BBB");
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::Button("CCC");
ImGui::Button("DDD");
ImGui::EndGroup();
ImGui::SameLine();
ImGui::Button("EEE");
ImGui::EndGroup();
if (ImGui::IsItemHovered())
ImGui::SetTooltip("First group hovered");
}
// Capture the group size and create widgets using the same size
ImVec2 size = ImGui::GetItemRectSize();
const float values[5] = {0.5f, 0.20f, 0.80f, 0.60f, 0.25f};
ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size);
ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));
ImGui::SameLine();
ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));
ImGui::EndGroup();
ImGui::SameLine();
ImGui::Button("LEVERAGE\nBUZZWORD", size);
ImGui::SameLine();
ImGui::ListBoxHeader("List", size);
ImGui::Selectable("Selected", true);
ImGui::Selectable("Not Selected", false);
ImGui::ListBoxFooter();
ImGui::TreePop();
}
if (ImGui::TreeNode("Text Baseline Alignment"))
{
ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)");
ImGui::Text("One\nTwo\nThree");
ImGui::SameLine();
ImGui::Text("Hello\nWorld");
ImGui::SameLine();
ImGui::Text("Banana");
ImGui::Text("Banana");
ImGui::SameLine();
ImGui::Text("Hello\nWorld");
ImGui::SameLine();
ImGui::Text("One\nTwo\nThree");
ImGui::Button("HOP##1");
ImGui::SameLine();
ImGui::Text("Banana");
ImGui::SameLine();
ImGui::Text("Hello\nWorld");
ImGui::SameLine();
ImGui::Text("Banana");
ImGui::Button("HOP##2");
ImGui::SameLine();
ImGui::Text("Hello\nWorld");
ImGui::SameLine();
ImGui::Text("Banana");
ImGui::Button("TEST##1");
ImGui::SameLine();
ImGui::Text("TEST");
ImGui::SameLine();
ImGui::SmallButton("TEST##2");
ImGui::AlignTextToFramePadding(); // If your line starts with text, call this to align it to upcoming widgets.
ImGui::Text("Text aligned to Widget");
ImGui::SameLine();
ImGui::Button("Widget##1");
ImGui::SameLine();
ImGui::Text("Widget");
ImGui::SameLine();
ImGui::SmallButton("Widget##2");
ImGui::SameLine();
ImGui::Button("Widget##3");
// Tree
const float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
ImGui::Button("Button##1");
ImGui::SameLine(0.0f, spacing);
if (ImGui::TreeNode("Node##1"))
{
for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i);
ImGui::TreePop();
} // Dummy tree data
ImGui::AlignTextToFramePadding(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit).
bool node_open = ImGui::TreeNode("Node##2"); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content.
ImGui::SameLine(0.0f, spacing);
ImGui::Button("Button##2");
if (node_open)
{
for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i);
ImGui::TreePop();
} // Dummy tree data
// Bullet
ImGui::Button("Button##3");
ImGui::SameLine(0.0f, spacing);
ImGui::BulletText("Bullet text");
ImGui::AlignTextToFramePadding();
ImGui::BulletText("Node");
ImGui::SameLine(0.0f, spacing);
ImGui::Button("Button##4");
ImGui::TreePop();
}
if (ImGui::TreeNode("Scrolling"))
{
ImGui::TextWrapped("(Use SetScrollHere() or SetScrollFromPosY() to scroll to a given position.)");
static bool track = true;
static int track_line = 50, scroll_to_px = 200;
ImGui::Checkbox("Track", &track);
ImGui::PushItemWidth(100);
ImGui::SameLine(130);
track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line = %.0f");
bool scroll_to = ImGui::Button("Scroll To Pos");
ImGui::SameLine(130);
scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "Y = %.0f px");
ImGui::PopItemWidth();
if (scroll_to) track = false;
for (int i = 0; i < 5; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::BeginGroup();
ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom");
ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(ImGui::GetWindowWidth() * 0.17f, 200.0f), true);
if (scroll_to)
ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_px, i * 0.25f);
for (int line = 0; line < 100; line++)
{
if (track && line == track_line)
{
ImGui::TextColored(ImColor(255, 255, 0), "Line %d", line);
ImGui::SetScrollHere(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom
}
else
{
ImGui::Text("Line %d", line);
}
}
float scroll_y = ImGui::GetScrollY(), scroll_max_y = ImGui::GetScrollMaxY();
ImGui::EndChild();
ImGui::Text("%.0f/%0.f", scroll_y, scroll_max_y);
ImGui::EndGroup();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Horizontal Scrolling"))
{
ImGui::Bullet();
ImGui::TextWrapped("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag.");
ImGui::Bullet();
ImGui::TextWrapped("You may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin().");
static int lines = 7;
ImGui::SliderInt("Lines", &lines, 1, 15);
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f));
ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar);
for (int line = 0; line < lines; line++)
{
// Display random stuff (for the sake of this trivial demo we are using basic Button+SameLine. If you want to create your own time line for a real application you may be better off
// manipulating the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets yourself. You may also want to use the lower-level ImDrawList API)
int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3);
for (int n = 0; n < num_buttons; n++)
{
if (n > 0) ImGui::SameLine();
ImGui::PushID(n + line * 1000);
char num_buf[16];
sprintf(num_buf, "%d", n);
const char* label = (!(n % 15)) ? "FizzBuzz" : (!(n % 3)) ? "Fizz" : (!(n % 5)) ? "Buzz" : num_buf;
float hue = n * 0.05f;
ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f));
ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f));
ImGui::PopStyleColor(3);
ImGui::PopID();
}
}
float scroll_x = ImGui::GetScrollX(), scroll_max_x = ImGui::GetScrollMaxX();
ImGui::EndChild();
ImGui::PopStyleVar(2);
float scroll_x_delta = 0.0f;
ImGui::SmallButton("<<");
if (ImGui::IsItemActive()) scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f;
ImGui::SameLine();
ImGui::Text("Scroll from code");
ImGui::SameLine();
ImGui::SmallButton(">>");
if (ImGui::IsItemActive()) scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f;
ImGui::SameLine();
ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x);
if (scroll_x_delta != 0.0f)
{
ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window)
ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta);
ImGui::End();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Clipping"))
{
static ImVec2 size(100, 100), offset(50, 20);
ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost.");
ImGui::DragFloat2("size", (float*)&size, 0.5f, 0.0f, 200.0f, "%.0f");
ImGui::TextWrapped("(Click and drag)");
ImVec2 pos = ImGui::GetCursorScreenPos();
ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y);
ImGui::InvisibleButton("##dummy", size);
if (ImGui::IsItemActive() && ImGui::IsMouseDragging())
{
offset.x += ImGui::GetIO().MouseDelta.x;
offset.y += ImGui::GetIO().MouseDelta.y;
}
ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x + size.x, pos.y + size.y), IM_COL32(90, 90, 120, 255));
ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize() * 2.0f, ImVec2(pos.x + offset.x, pos.y + offset.y), IM_COL32(255, 255, 255, 255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect);
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Popups & Modal windows"))
{
if (ImGui::TreeNode("Popups"))
{
ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it.");
static int selected_fish = -1;
const char* names[] = {"Bream", "Haddock", "Mackerel", "Pollock", "Tilefish"};
static bool toggles[] = {true, false, false, false, false};
// Simple selection popup
// (If you want to show the current selection inside the Button itself, you may want to build a string using the "###" operator to preserve a constant ID with a variable label)
if (ImGui::Button("Select.."))
ImGui::OpenPopup("select");
ImGui::SameLine();
ImGui::TextUnformatted(selected_fish == -1 ? "<None>" : names[selected_fish]);
if (ImGui::BeginPopup("select"))
{
ImGui::Text("Aquarium");
ImGui::Separator();
for (int i = 0; i < IM_ARRAYSIZE(names); i++)
if (ImGui::Selectable(names[i]))
selected_fish = i;
ImGui::EndPopup();
}
// Showing a menu with toggles
if (ImGui::Button("Toggle.."))
ImGui::OpenPopup("toggle");
if (ImGui::BeginPopup("toggle"))
{
for (int i = 0; i < IM_ARRAYSIZE(names); i++)
ImGui::MenuItem(names[i], "", &toggles[i]);
if (ImGui::BeginMenu("Sub-menu"))
{
ImGui::MenuItem("Click me");
ImGui::EndMenu();
}
ImGui::Separator();
ImGui::Text("Tooltip here");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("I am a tooltip over a popup");
if (ImGui::Button("Stacked Popup"))
ImGui::OpenPopup("another popup");
if (ImGui::BeginPopup("another popup"))
{
for (int i = 0; i < IM_ARRAYSIZE(names); i++)
ImGui::MenuItem(names[i], "", &toggles[i]);
if (ImGui::BeginMenu("Sub-menu"))
{
ImGui::MenuItem("Click me");
ImGui::EndMenu();
}
ImGui::EndPopup();
}
ImGui::EndPopup();
}
if (ImGui::Button("Popup Menu.."))
ImGui::OpenPopup("FilePopup");
if (ImGui::BeginPopup("FilePopup"))
{
ShowExampleMenuFile();
ImGui::EndPopup();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Context menus"))
{
// BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing:
// if (IsItemHovered() && IsMouseClicked(0))
// OpenPopup(id);
// return BeginPopup(id);
// For more advanced uses you may want to replicate and cuztomize this code. This the comments inside BeginPopupContextItem() implementation.
static float value = 0.5f;
ImGui::Text("Value = %.3f (<-- right-click here)", value);
if (ImGui::BeginPopupContextItem("item context menu"))
{
if (ImGui::Selectable("Set to zero")) value = 0.0f;
if (ImGui::Selectable("Set to PI")) value = 3.1415f;
ImGui::PushItemWidth(-1);
ImGui::DragFloat("##Value", &value, 0.1f, 0.0f, 0.0f);
ImGui::PopItemWidth();
ImGui::EndPopup();
}
static char name[32] = "Label1";
char buf[64];
sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label
ImGui::Button(buf);
if (ImGui::BeginPopupContextItem()) // When used after an item that has an ID (here the Button), we can skip providing an ID to BeginPopupContextItem().
{
ImGui::Text("Edit name:");
ImGui::InputText("##edit", name, IM_ARRAYSIZE(name));
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImGui::SameLine();
ImGui::Text("(<-- right-click here)");
ImGui::TreePop();
}
if (ImGui::TreeNode("Modals"))
{
ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window.");
if (ImGui::Button("Delete.."))
ImGui::OpenPopup("Delete?");
if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n");
ImGui::Separator();
//static int dummy_i = 0;
//ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0");
static bool dont_ask_me_next_time = false;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time);
ImGui::PopStyleVar();
if (ImGui::Button("OK", ImVec2(120, 0)))
{
ImGui::CloseCurrentPopup();
}
ImGui::SetItemDefaultFocus();
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(120, 0)))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if (ImGui::Button("Stacked modals.."))
ImGui::OpenPopup("Stacked 1");
if (ImGui::BeginPopupModal("Stacked 1"))
{
ImGui::Text("Hello from Stacked The First\nUsing style.Colors[ImGuiCol_ModalWindowDarkening] for darkening.");
static int item = 1;
ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
static float color[4] = {0.4f, 0.7f, 0.0f, 0.5f};
ImGui::ColorEdit4("color", color); // This is to test behavior of stacked regular popups over a modal
if (ImGui::Button("Add another modal.."))
ImGui::OpenPopup("Stacked 2");
if (ImGui::BeginPopupModal("Stacked 2"))
{
ImGui::Text("Hello from Stacked The Second!");
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Menus inside a regular window"))
{
ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!");
ImGui::Separator();
// NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above.
// To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here
// would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus.
ImGui::PushID("foo");
ImGui::MenuItem("Menu item", "CTRL+M");
if (ImGui::BeginMenu("Menu inside a regular window"))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
ImGui::PopID();
ImGui::Separator();
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Columns"))
{
ImGui::PushID("Columns");
// Basic columns
if (ImGui::TreeNode("Basic"))
{
ImGui::Text("Without border:");
ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border
ImGui::Separator();
for (int n = 0; n < 14; n++)
{
char label[32];
sprintf(label, "Item %d", n);
if (ImGui::Selectable(label))
{
}
//if (ImGui::Button(label, ImVec2(-1,0))) {}
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::Text("With border:");
ImGui::Columns(4, "mycolumns"); // 4-ways, with border
ImGui::Separator();
ImGui::Text("ID");
ImGui::NextColumn();
ImGui::Text("Name");
ImGui::NextColumn();
ImGui::Text("Path");
ImGui::NextColumn();
ImGui::Text("Hovered");
ImGui::NextColumn();
ImGui::Separator();
const char* names[3] = {"One", "Two", "Three"};
const char* paths[3] = {"/path/one", "/path/two", "/path/three"};
static int selected = -1;
for (int i = 0; i < 3; i++)
{
char label[32];
sprintf(label, "%04d", i);
if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns))
selected = i;
bool hovered = ImGui::IsItemHovered();
ImGui::NextColumn();
ImGui::Text(names[i]);
ImGui::NextColumn();
ImGui::Text(paths[i]);
ImGui::NextColumn();
ImGui::Text("%d", hovered);
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::TreePop();
}
// Create multiple items in a same cell before switching to next column
if (ImGui::TreeNode("Mixed items"))
{
ImGui::Columns(3, "mixed");
ImGui::Separator();
ImGui::Text("Hello");
ImGui::Button("Banana");
ImGui::NextColumn();
ImGui::Text("ImGui");
ImGui::Button("Apple");
static float foo = 1.0f;
ImGui::InputFloat("red", &foo, 0.05f, 0, 3);
ImGui::Text("An extra line here.");
ImGui::NextColumn();
ImGui::Text("Sailor");
ImGui::Button("Corniflower");
static float bar = 1.0f;
ImGui::InputFloat("blue", &bar, 0.05f, 0, 3);
ImGui::NextColumn();
if (ImGui::CollapsingHeader("Category A"))
{
ImGui::Text("Blah blah blah");
}
ImGui::NextColumn();
if (ImGui::CollapsingHeader("Category B"))
{
ImGui::Text("Blah blah blah");
}
ImGui::NextColumn();
if (ImGui::CollapsingHeader("Category C"))
{
ImGui::Text("Blah blah blah");
}
ImGui::NextColumn();
ImGui::Columns(1);
ImGui::Separator();
ImGui::TreePop();
}
// Word wrapping
if (ImGui::TreeNode("Word-wrapping"))
{
ImGui::Columns(2, "word-wrapping");
ImGui::Separator();
ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
ImGui::TextWrapped("Hello Left");
ImGui::NextColumn();
ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
ImGui::TextWrapped("Hello Right");
ImGui::Columns(1);
ImGui::Separator();
ImGui::TreePop();
}
if (ImGui::TreeNode("Borders"))
{
// NB: Future columns API should allow automatic horizontal borders.
static bool h_borders = true;
static bool v_borders = true;
ImGui::Checkbox("horizontal", &h_borders);
ImGui::SameLine();
ImGui::Checkbox("vertical", &v_borders);
ImGui::Columns(4, NULL, v_borders);
for (int i = 0; i < 4 * 3; i++)
{
if (h_borders && ImGui::GetColumnIndex() == 0)
ImGui::Separator();
ImGui::Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i);
ImGui::Text("Width %.2f\nOffset %.2f", ImGui::GetColumnWidth(), ImGui::GetColumnOffset());
ImGui::NextColumn();
}
ImGui::Columns(1);
if (h_borders)
ImGui::Separator();
ImGui::TreePop();
}
// Scrolling columns
/*
if (ImGui::TreeNode("Vertical Scrolling"))
{
ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y));
ImGui::Columns(3);
ImGui::Text("ID"); ImGui::NextColumn();
ImGui::Text("Name"); ImGui::NextColumn();
ImGui::Text("Path"); ImGui::NextColumn();
ImGui::Columns(1);
ImGui::Separator();
ImGui::EndChild();
ImGui::BeginChild("##scrollingregion", ImVec2(0, 60));
ImGui::Columns(3);
for (int i = 0; i < 10; i++)
{
ImGui::Text("%04d", i); ImGui::NextColumn();
ImGui::Text("Foobar"); ImGui::NextColumn();
ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::EndChild();
ImGui::TreePop();
}
*/
if (ImGui::TreeNode("Horizontal Scrolling"))
{
ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f));
ImGui::BeginChild("##ScrollingRegion", ImVec2(0, ImGui::GetFontSize() * 20), false, ImGuiWindowFlags_HorizontalScrollbar);
ImGui::Columns(10);
int ITEMS_COUNT = 2000;
ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list
while (clipper.Step())
{
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
for (int j = 0; j < 10; j++)
{
ImGui::Text("Line %d Column %d...", i, j);
ImGui::NextColumn();
}
}
ImGui::Columns(1);
ImGui::EndChild();
ImGui::TreePop();
}
bool node_open = ImGui::TreeNode("Tree within single cell");
ImGui::SameLine();
ShowHelpMarker("NB: Tree node must be poped before ending the cell. There's no storage of state per-cell.");
if (node_open)
{
ImGui::Columns(2, "tree items");
ImGui::Separator();
if (ImGui::TreeNode("Hello"))
{
ImGui::BulletText("Sailor");
ImGui::TreePop();
}
ImGui::NextColumn();
if (ImGui::TreeNode("Bonjour"))
{
ImGui::BulletText("Marin");
ImGui::TreePop();
}
ImGui::NextColumn();
ImGui::Columns(1);
ImGui::Separator();
ImGui::TreePop();
}
ImGui::PopID();
}
if (ImGui::CollapsingHeader("Filtering"))
{
static ImGuiTextFilter filter;
ImGui::Text(
"Filter usage:\n"
" \"\" display all lines\n"
" \"xxx\" display lines containing \"xxx\"\n"
" \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n"
" \"-xxx\" hide lines containing \"xxx\"");
filter.Draw();
const char* lines[] = {"aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world"};
for (int i = 0; i < IM_ARRAYSIZE(lines); i++)
if (filter.PassFilter(lines[i]))
ImGui::BulletText("%s", lines[i]);
}
if (ImGui::CollapsingHeader("Inputs, Navigation & Focus"))
{
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("WantCaptureMouse: %d", io.WantCaptureMouse);
ImGui::Text("WantCaptureKeyboard: %d", io.WantCaptureKeyboard);
ImGui::Text("WantTextInput: %d", io.WantTextInput);
ImGui::Text("WantMoveMouse: %d", io.WantMoveMouse);
ImGui::Text("NavActive: %d, NavVisible: %d", io.NavActive, io.NavVisible);
ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
ImGui::SameLine();
ShowHelpMarker("Request ImGui to render a mouse cursor for you in software. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).");
ImGui::CheckboxFlags("io.NavFlags: EnableGamepad", (unsigned int*)&io.NavFlags, ImGuiNavFlags_EnableGamepad);
ImGui::CheckboxFlags("io.NavFlags: EnableKeyboard", (unsigned int*)&io.NavFlags, ImGuiNavFlags_EnableKeyboard);
ImGui::CheckboxFlags("io.NavFlags: MoveMouse", (unsigned int*)&io.NavFlags, ImGuiNavFlags_MoveMouse);
ImGui::SameLine();
ShowHelpMarker("Request ImGui to move your move cursor when using gamepad/keyboard navigation. NewFrame() will change io.MousePos and set the io.WantMoveMouse flag, your backend will need to apply the new mouse position.");
if (ImGui::TreeNode("Keyboard, Mouse & Navigation State"))
{
if (ImGui::IsMousePosValid())
ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
else
ImGui::Text("Mouse pos: <INVALID>");
ImGui::Text("Mouse down:");
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
if (io.MouseDownDuration[i] >= 0.0f)
{
ImGui::SameLine();
ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]);
}
ImGui::Text("Mouse clicked:");
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
if (ImGui::IsMouseClicked(i))
{
ImGui::SameLine();
ImGui::Text("b%d", i);
}
ImGui::Text("Mouse dbl-clicked:");
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
if (ImGui::IsMouseDoubleClicked(i))
{
ImGui::SameLine();
ImGui::Text("b%d", i);
}
ImGui::Text("Mouse released:");
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
if (ImGui::IsMouseReleased(i))
{
ImGui::SameLine();
ImGui::Text("b%d", i);
}
ImGui::Text("Mouse wheel: %.1f", io.MouseWheel);
ImGui::Text("Keys down:");
for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++)
if (io.KeysDownDuration[i] >= 0.0f)
{
ImGui::SameLine();
ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]);
}
ImGui::Text("Keys pressed:");
for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++)
if (ImGui::IsKeyPressed(i))
{
ImGui::SameLine();
ImGui::Text("%d", i);
}
ImGui::Text("Keys release:");
for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++)
if (ImGui::IsKeyReleased(i))
{
ImGui::SameLine();
ImGui::Text("%d", i);
}
ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
ImGui::Text("NavInputs down:");
for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
if (io.NavInputs[i] > 0.0f)
{
ImGui::SameLine();
ImGui::Text("[%d] %.2f", i, io.NavInputs[i]);
}
ImGui::Text("NavInputs pressed:");
for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
if (io.NavInputsDownDuration[i] == 0.0f)
{
ImGui::SameLine();
ImGui::Text("[%d]", i);
}
ImGui::Text("NavInputs duration:");
for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
if (io.NavInputsDownDuration[i] >= 0.0f)
{
ImGui::SameLine();
ImGui::Text("[%d] %.2f", i, io.NavInputsDownDuration[i]);
}
ImGui::Button("Hovering me sets the\nkeyboard capture flag");
if (ImGui::IsItemHovered())
ImGui::CaptureKeyboardFromApp(true);
ImGui::SameLine();
ImGui::Button("Holding me clears the\nthe keyboard capture flag");
if (ImGui::IsItemActive())
ImGui::CaptureKeyboardFromApp(false);
ImGui::TreePop();
}
if (ImGui::TreeNode("Tabbing"))
{
ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields.");
static char buf[32] = "dummy";
ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
ImGui::InputText("3", buf, IM_ARRAYSIZE(buf));
ImGui::PushAllowKeyboardFocus(false);
ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf));
//ImGui::SameLine(); ShowHelperMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets.");
ImGui::PopAllowKeyboardFocus();
ImGui::InputText("5", buf, IM_ARRAYSIZE(buf));
ImGui::TreePop();
}
if (ImGui::TreeNode("Focus from code"))
{
bool focus_1 = ImGui::Button("Focus on 1");
ImGui::SameLine();
bool focus_2 = ImGui::Button("Focus on 2");
ImGui::SameLine();
bool focus_3 = ImGui::Button("Focus on 3");
int has_focus = 0;
static char buf[128] = "click on a button to set focus";
if (focus_1) ImGui::SetKeyboardFocusHere();
ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsItemActive()) has_focus = 1;
if (focus_2) ImGui::SetKeyboardFocusHere();
ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsItemActive()) has_focus = 2;
ImGui::PushAllowKeyboardFocus(false);
if (focus_3) ImGui::SetKeyboardFocusHere();
ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsItemActive()) has_focus = 3;
ImGui::PopAllowKeyboardFocus();
if (has_focus)
ImGui::Text("Item with focus: %d", has_focus);
else
ImGui::Text("Item with focus: <none>");
// Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item
static float f3[3] = {0.0f, 0.0f, 0.0f};
int focus_ahead = -1;
if (ImGui::Button("Focus on X")) focus_ahead = 0;
ImGui::SameLine();
if (ImGui::Button("Focus on Y")) focus_ahead = 1;
ImGui::SameLine();
if (ImGui::Button("Focus on Z")) focus_ahead = 2;
if (focus_ahead != -1) ImGui::SetKeyboardFocusHere(focus_ahead);
ImGui::SliderFloat3("Float3", &f3[0], 0.0f, 1.0f);
ImGui::TextWrapped("NB: Cursor & selection are preserved when refocusing last used item in code.");
ImGui::TreePop();
}
if (ImGui::TreeNode("Focused & Hovered Test"))
{
static bool embed_all_inside_a_child_window = false;
ImGui::Checkbox("Embed everything inside a child window (for additional testing)", &embed_all_inside_a_child_window);
if (embed_all_inside_a_child_window)
ImGui::BeginChild("embeddingchild", ImVec2(0, ImGui::GetFontSize() * 25), true);
// Testing IsWindowFocused() function with its various flags (note that the flags can be combined)
ImGui::BulletText(
"IsWindowFocused() = %d\n"
"IsWindowFocused(_ChildWindows) = %d\n"
"IsWindowFocused(_ChildWindows|_RootWindow) = %d\n"
"IsWindowFocused(_RootWindow) = %d\n"
"IsWindowFocused(_AnyWindow) = %d\n",
ImGui::IsWindowFocused(),
ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows),
ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow),
ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow),
ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow));
// Testing IsWindowHovered() function with its various flags (note that the flags can be combined)
ImGui::BulletText(
"IsWindowHovered() = %d\n"
"IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n"
"IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n"
"IsWindowHovered(_ChildWindows) = %d\n"
"IsWindowHovered(_ChildWindows|_RootWindow) = %d\n"
"IsWindowHovered(_RootWindow) = %d\n"
"IsWindowHovered(_AnyWindow) = %d\n",
ImGui::IsWindowHovered(),
ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows),
ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow),
ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow),
ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow));
// Testing IsItemHovered() function (because BulletText is an item itself and that would affect the output of IsItemHovered, we pass all lines in a single items to shorten the code)
ImGui::Button("ITEM");
ImGui::BulletText(
"IsItemHovered() = %d\n"
"IsItemHovered(_AllowWhenBlockedByPopup) = %d\n"
"IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n"
"IsItemHovered(_AllowWhenOverlapped) = %d\n"
"IsItemhovered(_RectOnly) = %d\n",
ImGui::IsItemHovered(),
ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlapped),
ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly));
ImGui::BeginChild("child", ImVec2(0, 50), true);
ImGui::Text("This is another child window for testing IsWindowHovered() flags.");
ImGui::EndChild();
if (embed_all_inside_a_child_window)
EndChild();
ImGui::TreePop();
}
if (ImGui::TreeNode("Dragging"))
{
ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget.");
for (int button = 0; button < 3; button++)
ImGui::Text("IsMouseDragging(%d):\n w/ default threshold: %d,\n w/ zero threshold: %d\n w/ large threshold: %d",
button, ImGui::IsMouseDragging(button), ImGui::IsMouseDragging(button, 0.0f), ImGui::IsMouseDragging(button, 20.0f));
ImGui::Button("Drag Me");
if (ImGui::IsItemActive())
{
// Draw a line between the button and the mouse cursor
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRectFullScreen();
draw_list->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f);
draw_list->PopClipRect();
// Drag operations gets "unlocked" when the mouse has moved past a certain threshold (the default threshold is stored in io.MouseDragThreshold)
// You can request a lower or higher threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta()
ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f);
ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0);
ImVec2 mouse_delta = io.MouseDelta;
ImGui::SameLine();
ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f), MouseDelta (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y, mouse_delta.x, mouse_delta.y);
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Mouse cursors"))
{
const char* mouse_cursors_names[] = {"Arrow", "TextInput", "Move", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE"};
IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_Count_);
ImGui::Text("Current mouse cursor = %d: %s", ImGui::GetMouseCursor(), mouse_cursors_names[ImGui::GetMouseCursor()]);
ImGui::Text("Hover to see mouse cursors:");
ImGui::SameLine();
ShowHelpMarker("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, otherwise your backend needs to handle it.");
for (int i = 0; i < ImGuiMouseCursor_Count_; i++)
{
char label[32];
sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]);
ImGui::Bullet();
ImGui::Selectable(label, false);
if (ImGui::IsItemHovered() || ImGui::IsItemFocused())
ImGui::SetMouseCursor(i);
}
ImGui::TreePop();
}
}
ImGui::End();
}
// Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options.
// Here we use the simplified Combo() api that packs items into a single literal string. Useful for quick combo boxes where the choices are known locally.
bool ImGui::ShowStyleSelector(const char* label)
{
static int style_idx = -1;
if (ImGui::Combo(label, &style_idx, "Classic\0Dark\0Light\0"))
{
switch (style_idx)
{
case 0:
ImGui::StyleColorsClassic();
break;
case 1:
ImGui::StyleColorsDark();
break;
case 2:
ImGui::StyleColorsLight();
break;
}
return true;
}
return false;
}
// Demo helper function to select among loaded fonts.
// Here we use the regular BeginCombo()/EndCombo() api which is more the more flexible one.
void ImGui::ShowFontSelector(const char* label)
{
ImGuiIO& io = ImGui::GetIO();
ImFont* font_current = ImGui::GetFont();
if (ImGui::BeginCombo(label, font_current->GetDebugName()))
{
for (int n = 0; n < io.Fonts->Fonts.Size; n++)
if (ImGui::Selectable(io.Fonts->Fonts[n]->GetDebugName(), io.Fonts->Fonts[n] == font_current))
io.FontDefault = io.Fonts->Fonts[n];
ImGui::EndCombo();
}
ImGui::SameLine();
ShowHelpMarker(
"- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n"
"- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
"- Read FAQ and documentation in misc/fonts/ for more details.\n"
"- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
}
void ImGui::ShowStyleEditor(ImGuiStyle* ref)
{
// You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to an internally stored reference)
ImGuiStyle& style = ImGui::GetStyle();
static ImGuiStyle ref_saved_style;
// Default to using internal storage as reference
static bool init = true;
if (init && ref == NULL)
ref_saved_style = style;
init = false;
if (ref == NULL)
ref = &ref_saved_style;
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f);
if (ImGui::ShowStyleSelector("Colors##Selector"))
ref_saved_style = style;
ImGui::ShowFontSelector("Fonts##Selector");
// Simplified Settings
if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"))
style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding
{
bool window_border = (style.WindowBorderSize > 0.0f);
if (ImGui::Checkbox("WindowBorder", &window_border)) style.WindowBorderSize = window_border ? 1.0f : 0.0f;
}
ImGui::SameLine();
{
bool frame_border = (style.FrameBorderSize > 0.0f);
if (ImGui::Checkbox("FrameBorder", &frame_border)) style.FrameBorderSize = frame_border ? 1.0f : 0.0f;
}
ImGui::SameLine();
{
bool popup_border = (style.PopupBorderSize > 0.0f);
if (ImGui::Checkbox("PopupBorder", &popup_border)) style.PopupBorderSize = popup_border ? 1.0f : 0.0f;
}
// Save/Revert button
if (ImGui::Button("Save Ref"))
*ref = ref_saved_style = style;
ImGui::SameLine();
if (ImGui::Button("Revert Ref"))
style = *ref;
ImGui::SameLine();
ShowHelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. Use \"Export Colors\" below to save them somewhere.");
if (ImGui::TreeNode("Rendering"))
{
ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines);
ImGui::SameLine();
ShowHelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.");
ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill);
ImGui::PushItemWidth(100);
ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, NULL, 2.0f);
if (style.CurveTessellationTol < 0.0f) style.CurveTessellationTol = 0.10f;
ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero.
ImGui::PopItemWidth();
ImGui::TreePop();
}
if (ImGui::TreeNode("Settings"))
{
ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 16.0f, "%.0f");
ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f");
ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f");
ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f");
ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f");
ImGui::Text("BorderSize");
ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::Text("Rounding");
ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 14.0f, "%.0f");
ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 16.0f, "%.0f");
ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f");
ImGui::Text("Alignment");
ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f");
ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f");
ImGui::SameLine();
ShowHelpMarker("Alignment applies when a button is larger than its text content.");
ImGui::TreePop();
}
if (ImGui::TreeNode("Colors"))
{
static int output_dest = 0;
static bool output_only_modified = true;
if (ImGui::Button("Export Unsaved"))
{
if (output_dest == 0)
ImGui::LogToClipboard();
else
ImGui::LogToTTY();
ImGui::LogText("ImVec4* colors = ImGui::GetStyle().Colors;" IM_NEWLINE);
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
const ImVec4& col = style.Colors[i];
const char* name = ImGui::GetStyleColorName(i);
if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0)
ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
}
ImGui::LogFinish();
}
ImGui::SameLine();
ImGui::PushItemWidth(120);
ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0");
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::Checkbox("Only Modified Colors", &output_only_modified);
ImGui::Text("Tip: Left-click on colored square to open color picker,\nRight-click to open edit options menu.");
static ImGuiTextFilter filter;
filter.Draw("Filter colors", 200);
static ImGuiColorEditFlags alpha_flags = 0;
ImGui::RadioButton("Opaque", &alpha_flags, 0);
ImGui::SameLine();
ImGui::RadioButton("Alpha", &alpha_flags, ImGuiColorEditFlags_AlphaPreview);
ImGui::SameLine();
ImGui::RadioButton("Both", &alpha_flags, ImGuiColorEditFlags_AlphaPreviewHalf);
ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened);
ImGui::PushItemWidth(-160);
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
const char* name = ImGui::GetStyleColorName(i);
if (!filter.PassFilter(name))
continue;
ImGui::PushID(i);
ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags);
if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0)
{
// Tips: in a real user application, you may want to merge and use an icon font into the main font, so instead of "Save"/"Revert" you'd use icons.
// Read the FAQ and misc/fonts/README.txt about using icon fonts. It's really easy and super convenient!
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);
if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i];
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);
if (ImGui::Button("Revert")) style.Colors[i] = ref->Colors[i];
}
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);
ImGui::TextUnformatted(name);
ImGui::PopID();
}
ImGui::PopItemWidth();
ImGui::EndChild();
ImGui::TreePop();
}
bool fonts_opened = ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size);
if (fonts_opened)
{
ImFontAtlas* atlas = ImGui::GetIO().Fonts;
if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
{
ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128));
ImGui::TreePop();
}
ImGui::PushItemWidth(100);
for (int i = 0; i < atlas->Fonts.Size; i++)
{
ImFont* font = atlas->Fonts[i];
ImGui::PushID(font);
bool font_details_opened = ImGui::TreeNode(font, "Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size);
ImGui::SameLine();
if (ImGui::SmallButton("Set as default")) ImGui::GetIO().FontDefault = font;
if (font_details_opened)
{
ImGui::PushFont(font);
ImGui::Text("The quick brown fox jumps over the lazy dog");
ImGui::PopFont();
ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font
ImGui::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, 0);
ImGui::SameLine();
ShowHelpMarker("Note than the default embedded font is NOT meant to be scaled.\n\nFont are currently rendered into bitmaps at a given size at the time of building the atlas. You may oversample them to get some flexibility with scaling. You can also render at multiple sizes and select which one to use at runtime.\n\n(Glimmer of hope: the atlas system should hopefully be rewritten in the future to make scaling more natural and automatic.)");
ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar);
ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)sqrtf((float)font->MetricsTotalSurface), (int)sqrtf((float)font->MetricsTotalSurface));
for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
{
ImFontConfig* cfg = &font->ConfigData[config_i];
ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH);
}
if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
{
// Display all glyphs of the fonts in separate pages of 256 characters
const ImFontGlyph* glyph_fallback = font->FallbackGlyph; // Forcefully/dodgily make FindGlyph() return NULL on fallback, which isn't the default behavior.
font->FallbackGlyph = NULL;
for (int base = 0; base < 0x10000; base += 256)
{
int count = 0;
for (int n = 0; n < 256; n++)
count += font->FindGlyph((ImWchar)(base + n)) ? 1 : 0;
if (count > 0 && ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
{
float cell_spacing = style.ItemSpacing.y;
ImVec2 cell_size(font->FontSize * 1, font->FontSize * 1);
ImVec2 base_pos = ImGui::GetCursorScreenPos();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
for (int n = 0; n < 256; n++)
{
ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size.x + cell_spacing), base_pos.y + (n / 16) * (cell_size.y + cell_spacing));
ImVec2 cell_p2(cell_p1.x + cell_size.x, cell_p1.y + cell_size.y);
const ImFontGlyph* glyph = font->FindGlyph((ImWchar)(base + n));
;
draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
font->RenderChar(draw_list, cell_size.x, cell_p1, ImGui::GetColorU32(ImGuiCol_Text), (ImWchar)(base + n)); // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available to generate a string.
if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2))
{
ImGui::BeginTooltip();
ImGui::Text("Codepoint: U+%04X", base + n);
ImGui::Separator();
ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX);
ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
ImGui::EndTooltip();
}
}
ImGui::Dummy(ImVec2((cell_size.x + cell_spacing) * 16, (cell_size.y + cell_spacing) * 16));
ImGui::TreePop();
}
}
font->FallbackGlyph = glyph_fallback;
ImGui::TreePop();
}
ImGui::TreePop();
}
ImGui::PopID();
}
static float window_scale = 1.0f;
ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this window
ImGui::DragFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale everything
ImGui::PopItemWidth();
ImGui::SetWindowFontScale(window_scale);
ImGui::TreePop();
}
ImGui::PopItemWidth();
}
// Demonstrate creating a fullscreen menu bar and populating it.
static void ShowExampleAppMainMenuBar()
{
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("File"))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Edit"))
{
if (ImGui::MenuItem("Undo", "CTRL+Z"))
{
}
if (ImGui::MenuItem("Redo", "CTRL+Y", false, false))
{
} // Disabled item
ImGui::Separator();
if (ImGui::MenuItem("Cut", "CTRL+X"))
{
}
if (ImGui::MenuItem("Copy", "CTRL+C"))
{
}
if (ImGui::MenuItem("Paste", "CTRL+V"))
{
}
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
static void ShowExampleMenuFile()
{
ImGui::MenuItem("(dummy menu)", NULL, false, false);
if (ImGui::MenuItem("New"))
{
}
if (ImGui::MenuItem("Open", "Ctrl+O"))
{
}
if (ImGui::BeginMenu("Open Recent"))
{
ImGui::MenuItem("fish_hat.c");
ImGui::MenuItem("fish_hat.inl");
ImGui::MenuItem("fish_hat.h");
if (ImGui::BeginMenu("More.."))
{
ImGui::MenuItem("Hello");
ImGui::MenuItem("Sailor");
if (ImGui::BeginMenu("Recurse.."))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
ImGui::EndMenu();
}
ImGui::EndMenu();
}
if (ImGui::MenuItem("Save", "Ctrl+S"))
{
}
if (ImGui::MenuItem("Save As.."))
{
}
ImGui::Separator();
if (ImGui::BeginMenu("Options"))
{
static bool enabled = true;
ImGui::MenuItem("Enabled", "", &enabled);
ImGui::BeginChild("child", ImVec2(0, 60), true);
for (int i = 0; i < 10; i++)
ImGui::Text("Scrolling Text %d", i);
ImGui::EndChild();
static float f = 0.5f;
static int n = 0;
static bool b = true;
ImGui::SliderFloat("Value", &f, 0.0f, 1.0f);
ImGui::InputFloat("Input", &f, 0.1f);
ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0");
ImGui::Checkbox("Check", &b);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Colors"))
{
float sz = ImGui::GetTextLineHeight();
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
const char* name = ImGui::GetStyleColorName((ImGuiCol)i);
ImVec2 p = ImGui::GetCursorScreenPos();
ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + sz, p.y + sz), ImGui::GetColorU32((ImGuiCol)i));
ImGui::Dummy(ImVec2(sz, sz));
ImGui::SameLine();
ImGui::MenuItem(name);
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Disabled", false)) // Disabled
{
IM_ASSERT(0);
}
if (ImGui::MenuItem("Checked", NULL, true))
{
}
if (ImGui::MenuItem("Quit", "Alt+F4"))
{
}
}
// Demonstrate creating a window which gets auto-resized according to its content.
static void ShowExampleAppAutoResize(bool* p_open)
{
if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::End();
return;
}
static int lines = 10;
ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop.");
ImGui::SliderInt("Number of lines", &lines, 1, 20);
for (int i = 0; i < lines; i++)
ImGui::Text("%*sThis is line %d", i * 4, "", i); // Pad with space to extend size horizontally
ImGui::End();
}
// Demonstrate creating a window with custom resize constraints.
static void ShowExampleAppConstrainedResize(bool* p_open)
{
struct CustomConstraints // Helper functions to demonstrate programmatic constraints
{
static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); }
static void Step(ImGuiSizeCallbackData* data)
{
float step = (float)(int)(intptr_t)data->UserData;
data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step);
}
};
static bool auto_resize = false;
static int type = 0;
static int display_lines = 10;
if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only
if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only
if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100
if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)); // Width 400-500
if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, 500)); // Height 400-500
if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square
if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100); // Fixed Step
ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0;
if (ImGui::Begin("Example: Constrained Resize", p_open, flags))
{
const char* desc[] =
{
"Resize vertical only",
"Resize horizontal only",
"Width > 100, Height > 100",
"Width 400-500",
"Height 400-500",
"Custom: Always Square",
"Custom: Fixed Steps (100)",
};
if (ImGui::Button("200x200"))
{
ImGui::SetWindowSize(ImVec2(200, 200));
}
ImGui::SameLine();
if (ImGui::Button("500x500"))
{
ImGui::SetWindowSize(ImVec2(500, 500));
}
ImGui::SameLine();
if (ImGui::Button("800x200"))
{
ImGui::SetWindowSize(ImVec2(800, 200));
}
ImGui::PushItemWidth(200);
ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc));
ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100);
ImGui::PopItemWidth();
ImGui::Checkbox("Auto-resize", &auto_resize);
for (int i = 0; i < display_lines; i++)
ImGui::Text("%*sHello, sailor! Making this line long enough for the example.", i * 4, "");
}
ImGui::End();
}
// Demonstrate creating a simple static window with no decoration + a context-menu to choose which corner of the screen to use.
static void ShowExampleAppFixedOverlay(bool* p_open)
{
const float DISTANCE = 10.0f;
static int corner = 0;
ImVec2 window_pos = ImVec2((corner & 1) ? ImGui::GetIO().DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? ImGui::GetIO().DisplaySize.y - DISTANCE : DISTANCE);
ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f);
ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
ImGui::SetNextWindowBgAlpha(0.3f); // Transparent background
if (ImGui::Begin("Example: Fixed Overlay", p_open, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav))
{
ImGui::Text("Simple overlay\nin the corner of the screen.\n(right-click to change position)");
ImGui::Separator();
ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y);
if (ImGui::BeginPopupContextWindow())
{
if (ImGui::MenuItem("Top-left", NULL, corner == 0)) corner = 0;
if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1;
if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2;
if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3;
if (p_open && ImGui::MenuItem("Close")) *p_open = false;
ImGui::EndPopup();
}
ImGui::End();
}
}
// Demonstrate using "##" and "###" in identifiers to manipulate ID generation.
// This apply to regular items as well. Read FAQ section "How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs." for details.
static void ShowExampleAppWindowTitles(bool*)
{
// By default, Windows are uniquely identified by their title.
// You can use the "##" and "###" markers to manipulate the display/ID.
// Using "##" to display same title but have unique identifier.
ImGui::SetNextWindowPos(ImVec2(100, 100), ImGuiCond_FirstUseEver);
ImGui::Begin("Same title as another window##1");
ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.");
ImGui::End();
ImGui::SetNextWindowPos(ImVec2(100, 200), ImGuiCond_FirstUseEver);
ImGui::Begin("Same title as another window##2");
ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.");
ImGui::End();
// Using "###" to display a changing title but keep a static identifier "AnimatedTitle"
char buf[128];
sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime() / 0.25f) & 3], ImGui::GetFrameCount());
ImGui::SetNextWindowPos(ImVec2(100, 300), ImGuiCond_FirstUseEver);
ImGui::Begin(buf);
ImGui::Text("This window has a changing title.");
ImGui::End();
}
// Demonstrate using the low-level ImDrawList to draw custom shapes.
static void ShowExampleAppCustomRendering(bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(350, 560), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Custom rendering", p_open))
{
ImGui::End();
return;
}
// Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc.
// Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4.
// ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types)
// In this example we are not using the maths operators!
ImDrawList* draw_list = ImGui::GetWindowDrawList();
// Primitives
ImGui::Text("Primitives");
static float sz = 36.0f;
static ImVec4 col = ImVec4(1.0f, 1.0f, 0.4f, 1.0f);
ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f");
ImGui::ColorEdit3("Color", &col.x);
{
const ImVec2 p = ImGui::GetCursorScreenPos();
const ImU32 col32 = ImColor(col);
float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f;
for (int n = 0; n < 2; n++)
{
float thickness = (n == 0) ? 1.0f : 4.0f;
draw_list->AddCircle(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col32, 20, thickness);
x += sz + spacing;
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 0.0f, ImDrawCornerFlags_All, thickness);
x += sz + spacing;
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_All, thickness);
x += sz + spacing;
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight, thickness);
x += sz + spacing;
draw_list->AddTriangle(ImVec2(x + sz * 0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32, thickness);
x += sz + spacing;
draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col32, thickness);
x += sz + spacing;
draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, thickness);
x += sz + spacing;
draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col32, thickness);
x += spacing;
draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x + sz * 1.3f, y + sz * 0.3f), ImVec2(x + sz - sz * 1.3f, y + sz - sz * 0.3f), ImVec2(x + sz, y + sz), col32, thickness);
x = p.x + 4;
y += sz + spacing;
}
draw_list->AddCircleFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col32, 32);
x += sz + spacing;
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32);
x += sz + spacing;
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f);
x += sz + spacing;
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight);
x += sz + spacing;
draw_list->AddTriangleFilled(ImVec2(x + sz * 0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32);
x += sz + spacing;
draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255));
ImGui::Dummy(ImVec2((sz + spacing) * 8, (sz + spacing) * 3));
}
ImGui::Separator();
{
static ImVector<ImVec2> points;
static bool adding_line = false;
ImGui::Text("Canvas example");
if (ImGui::Button("Clear")) points.clear();
if (points.Size >= 2)
{
ImGui::SameLine();
if (ImGui::Button("Undo"))
{
points.pop_back();
points.pop_back();
}
}
ImGui::Text("Left-click and drag to add lines,\nRight-click to undo");
// Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered()
// However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos().
// If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max).
ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
if (canvas_size.x < 50.0f) canvas_size.x = 50.0f;
if (canvas_size.y < 50.0f) canvas_size.y = 50.0f;
draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(50, 50, 50, 255), IM_COL32(50, 50, 60, 255), IM_COL32(60, 60, 70, 255), IM_COL32(50, 50, 60, 255));
draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(255, 255, 255, 255));
bool adding_preview = false;
ImGui::InvisibleButton("canvas", canvas_size);
ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y);
if (adding_line)
{
adding_preview = true;
points.push_back(mouse_pos_in_canvas);
if (!ImGui::IsMouseDown(0))
adding_line = adding_preview = false;
}
if (ImGui::IsItemHovered())
{
if (!adding_line && ImGui::IsMouseClicked(0))
{
points.push_back(mouse_pos_in_canvas);
adding_line = true;
}
if (ImGui::IsMouseClicked(1) && !points.empty())
{
adding_line = adding_preview = false;
points.pop_back();
points.pop_back();
}
}
draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), true); // clip lines within the canvas (if we resize it, etc.)
for (int i = 0; i < points.Size - 1; i += 2)
draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i + 1].x, canvas_pos.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f);
draw_list->PopClipRect();
if (adding_preview)
points.pop_back();
}
ImGui::End();
}
// Demonstrating creating a simple console window, with scrolling, filtering, completion and history.
// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions.
struct ExampleAppConsole
{
char InputBuf[256];
ImVector<char*> Items;
bool ScrollToBottom;
ImVector<char*> History;
int HistoryPos; // -1: new line, 0..History.Size-1 browsing history.
ImVector<const char*> Commands;
ExampleAppConsole()
{
ClearLog();
memset(InputBuf, 0, sizeof(InputBuf));
HistoryPos = -1;
Commands.push_back("HELP");
Commands.push_back("HISTORY");
Commands.push_back("CLEAR");
Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches.
AddLog("Welcome to ImGui!");
}
~ExampleAppConsole()
{
ClearLog();
for (int i = 0; i < History.Size; i++)
free(History[i]);
}
// Portable helpers
static int Stricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1)
{
str1++;
str2++;
}
return d;
}
static int Strnicmp(const char* str1, const char* str2, int n)
{
int d = 0;
while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1)
{
str1++;
str2++;
n--;
}
return d;
}
static char* Strdup(const char* str)
{
size_t len = strlen(str) + 1;
void* buff = malloc(len);
return (char*)memcpy(buff, (const void*)str, len);
}
void ClearLog()
{
for (int i = 0; i < Items.Size; i++)
free(Items[i]);
Items.clear();
ScrollToBottom = true;
}
void AddLog(const char* fmt, ...) IM_FMTARGS(2)
{
// FIXME-OPT
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args);
buf[IM_ARRAYSIZE(buf) - 1] = 0;
va_end(args);
Items.push_back(Strdup(buf));
ScrollToBottom = true;
}
void Draw(const char* title, bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (!ImGui::Begin(title, p_open))
{
ImGui::End();
return;
}
// As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. So e.g. IsItemHovered() will return true when hovering the title bar.
// Here we create a context menu only available from the title bar.
if (ImGui::BeginPopupContextItem())
{
if (ImGui::MenuItem("Close"))
*p_open = false;
ImGui::EndPopup();
}
ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc.");
ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion.");
// TODO: display items starting from the bottom
if (ImGui::SmallButton("Add Dummy Text"))
{
AddLog("%d some text", Items.Size);
AddLog("some more text");
AddLog("display very important message here!");
}
ImGui::SameLine();
if (ImGui::SmallButton("Add Dummy Error"))
{
AddLog("[error] something went wrong");
}
ImGui::SameLine();
if (ImGui::SmallButton("Clear"))
{
ClearLog();
}
ImGui::SameLine();
bool copy_to_clipboard = ImGui::SmallButton("Copy");
ImGui::SameLine();
if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true;
//static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); }
ImGui::Separator();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
static ImGuiTextFilter filter;
filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180);
ImGui::PopStyleVar();
ImGui::Separator();
const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); // 1 separator, 1 input text
ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); // Leave room for 1 separator + 1 InputText
if (ImGui::BeginPopupContextWindow())
{
if (ImGui::Selectable("Clear")) ClearLog();
ImGui::EndPopup();
}
// Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());
// NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items.
// You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements.
// To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with:
// ImGuiListClipper clipper(Items.Size);
// while (clipper.Step())
// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
// However take note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list.
// A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter,
// and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code!
// If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list.
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing
if (copy_to_clipboard)
ImGui::LogToClipboard();
ImVec4 col_default_text = ImGui::GetStyleColorVec4(ImGuiCol_Text);
for (int i = 0; i < Items.Size; i++)
{
const char* item = Items[i];
if (!filter.PassFilter(item))
continue;
ImVec4 col = col_default_text;
if (strstr(item, "[error]"))
col = ImColor(1.0f, 0.4f, 0.4f, 1.0f);
else if (strncmp(item, "# ", 2) == 0)
col = ImColor(1.0f, 0.78f, 0.58f, 1.0f);
ImGui::PushStyleColor(ImGuiCol_Text, col);
ImGui::TextUnformatted(item);
ImGui::PopStyleColor();
}
if (copy_to_clipboard)
ImGui::LogFinish();
if (ScrollToBottom)
ImGui::SetScrollHere();
ScrollToBottom = false;
ImGui::PopStyleVar();
ImGui::EndChild();
ImGui::Separator();
// Command-line
bool reclaim_focus = false;
if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this))
{
char* input_end = InputBuf + strlen(InputBuf);
while (input_end > InputBuf && input_end[-1] == ' ')
{
input_end--;
}
*input_end = 0;
if (InputBuf[0])
ExecCommand(InputBuf);
strcpy(InputBuf, "");
reclaim_focus = true;
}
// Demonstrate keeping focus on the input box
ImGui::SetItemDefaultFocus();
if (reclaim_focus)
ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
ImGui::End();
}
void ExecCommand(const char* command_line)
{
AddLog("# %s\n", command_line);
// Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal.
HistoryPos = -1;
for (int i = History.Size - 1; i >= 0; i--)
if (Stricmp(History[i], command_line) == 0)
{
free(History[i]);
History.erase(History.begin() + i);
break;
}
History.push_back(Strdup(command_line));
// Process command
if (Stricmp(command_line, "CLEAR") == 0)
{
ClearLog();
}
else if (Stricmp(command_line, "HELP") == 0)
{
AddLog("Commands:");
for (int i = 0; i < Commands.Size; i++)
AddLog("- %s", Commands[i]);
}
else if (Stricmp(command_line, "HISTORY") == 0)
{
int first = History.Size - 10;
for (int i = first > 0 ? first : 0; i < History.Size; i++)
AddLog("%3d: %s\n", i, History[i]);
}
else
{
AddLog("Unknown command: '%s'\n", command_line);
}
}
static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks
{
ExampleAppConsole* console = (ExampleAppConsole*)data->UserData;
return console->TextEditCallback(data);
}
int TextEditCallback(ImGuiTextEditCallbackData* data)
{
//AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd);
switch (data->EventFlag)
{
case ImGuiInputTextFlags_CallbackCompletion:
{
// Example of TEXT COMPLETION
// Locate beginning of current word
const char* word_end = data->Buf + data->CursorPos;
const char* word_start = word_end;
while (word_start > data->Buf)
{
const char c = word_start[-1];
if (c == ' ' || c == '\t' || c == ',' || c == ';')
break;
word_start--;
}
// Build a list of candidates
ImVector<const char*> candidates;
for (int i = 0; i < Commands.Size; i++)
if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0)
candidates.push_back(Commands[i]);
if (candidates.Size == 0)
{
// No match
AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start);
}
else if (candidates.Size == 1)
{
// Single match. Delete the beginning of the word and replace it entirely so we've got nice casing
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0]);
data->InsertChars(data->CursorPos, " ");
}
else
{
// Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY"
int match_len = (int)(word_end - word_start);
for (;;)
{
int c = 0;
bool all_candidates_matches = true;
for (int i = 0; i < candidates.Size && all_candidates_matches; i++)
if (i == 0)
c = toupper(candidates[i][match_len]);
else if (c == 0 || c != toupper(candidates[i][match_len]))
all_candidates_matches = false;
if (!all_candidates_matches)
break;
match_len++;
}
if (match_len > 0)
{
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
}
// List matches
AddLog("Possible matches:\n");
for (int i = 0; i < candidates.Size; i++)
AddLog("- %s\n", candidates[i]);
}
break;
}
case ImGuiInputTextFlags_CallbackHistory:
{
// Example of HISTORY
const int prev_history_pos = HistoryPos;
if (data->EventKey == ImGuiKey_UpArrow)
{
if (HistoryPos == -1)
HistoryPos = History.Size - 1;
else if (HistoryPos > 0)
HistoryPos--;
}
else if (data->EventKey == ImGuiKey_DownArrow)
{
if (HistoryPos != -1)
if (++HistoryPos >= History.Size)
HistoryPos = -1;
}
// A better implementation would preserve the data on the current input line along with cursor position.
if (prev_history_pos != HistoryPos)
{
data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : "");
data->BufDirty = true;
}
}
}
return 0;
}
};
static void ShowExampleAppConsole(bool* p_open)
{
static ExampleAppConsole console;
console.Draw("Example: Console", p_open);
}
// Usage:
// static ExampleAppLog my_log;
// my_log.AddLog("Hello %d world\n", 123);
// my_log.Draw("title");
struct ExampleAppLog
{
ImGuiTextBuffer Buf;
ImGuiTextFilter Filter;
ImVector<int> LineOffsets; // Index to lines offset
bool ScrollToBottom;
void Clear()
{
Buf.clear();
LineOffsets.clear();
}
void AddLog(const char* fmt, ...) IM_FMTARGS(2)
{
int old_size = Buf.size();
va_list args;
va_start(args, fmt);
Buf.appendfv(fmt, args);
va_end(args);
for (int new_size = Buf.size(); old_size < new_size; old_size++)
if (Buf[old_size] == '\n')
LineOffsets.push_back(old_size);
ScrollToBottom = true;
}
void Draw(const char* title, bool* p_open = NULL)
{
ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver);
ImGui::Begin(title, p_open);
if (ImGui::Button("Clear")) Clear();
ImGui::SameLine();
bool copy = ImGui::Button("Copy");
ImGui::SameLine();
Filter.Draw("Filter", -100.0f);
ImGui::Separator();
ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
if (copy) ImGui::LogToClipboard();
if (Filter.IsActive())
{
const char* buf_begin = Buf.begin();
const char* line = buf_begin;
for (int line_no = 0; line != NULL; line_no++)
{
const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL;
if (Filter.PassFilter(line, line_end))
ImGui::TextUnformatted(line, line_end);
line = line_end && line_end[1] ? line_end + 1 : NULL;
}
}
else
{
ImGui::TextUnformatted(Buf.begin());
}
if (ScrollToBottom)
ImGui::SetScrollHere(1.0f);
ScrollToBottom = false;
ImGui::EndChild();
ImGui::End();
}
};
// Demonstrate creating a simple log window with basic filtering.
static void ShowExampleAppLog(bool* p_open)
{
static ExampleAppLog log;
// Demo: add random items (unless Ctrl is held)
static float last_time = -1.0f;
float time = ImGui::GetTime();
if (time - last_time >= 0.20f && !ImGui::GetIO().KeyCtrl)
{
const char* random_words[] = {"system", "info", "warning", "error", "fatal", "notice", "log"};
log.AddLog("[%s] Hello, time is %.1f, frame count is %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, ImGui::GetFrameCount());
last_time = time;
}
log.Draw("Example: Log", p_open);
}
// Demonstrate create a window with multiple child windows.
static void ShowExampleAppLayout(bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Example: Layout", p_open, ImGuiWindowFlags_MenuBar))
{
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Close")) *p_open = false;
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
// left
static int selected = 0;
ImGui::BeginChild("left pane", ImVec2(150, 0), true);
for (int i = 0; i < 100; i++)
{
char label[128];
sprintf(label, "MyObject %d", i);
if (ImGui::Selectable(label, selected == i))
selected = i;
}
ImGui::EndChild();
ImGui::SameLine();
// right
ImGui::BeginGroup();
ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us
ImGui::Text("MyObject: %d", selected);
ImGui::Separator();
ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
ImGui::EndChild();
if (ImGui::Button("Revert"))
{
}
ImGui::SameLine();
if (ImGui::Button("Save"))
{
}
ImGui::EndGroup();
}
ImGui::End();
}
// Demonstrate create a simple property editor.
static void ShowExampleAppPropertyEditor(bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Property editor", p_open))
{
ImGui::End();
return;
}
ShowHelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API.");
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2));
ImGui::Columns(2);
ImGui::Separator();
struct funcs
{
static void ShowDummyObject(const char* prefix, int uid)
{
ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID.
ImGui::AlignTextToFramePadding(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high.
bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid);
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("my sailor is rich");
ImGui::NextColumn();
if (node_open)
{
static float dummy_members[8] = {0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f};
for (int i = 0; i < 8; i++)
{
ImGui::PushID(i); // Use field index as identifier.
if (i < 2)
{
ShowDummyObject("Child", 424242);
}
else
{
ImGui::AlignTextToFramePadding();
// Here we use a Selectable (instead of Text) to highlight on hover
//ImGui::Text("Field_%d", i);
char label[32];
sprintf(label, "Field_%d", i);
ImGui::Bullet();
ImGui::Selectable(label);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
if (i >= 5)
ImGui::InputFloat("##value", &dummy_members[i], 1.0f);
else
ImGui::DragFloat("##value", &dummy_members[i], 0.01f);
ImGui::PopItemWidth();
ImGui::NextColumn();
}
ImGui::PopID();
}
ImGui::TreePop();
}
ImGui::PopID();
}
};
// Iterate dummy objects with dummy members (all the same data)
for (int obj_i = 0; obj_i < 3; obj_i++)
funcs::ShowDummyObject("Object", obj_i);
ImGui::Columns(1);
ImGui::Separator();
ImGui::PopStyleVar();
ImGui::End();
}
// Demonstrate/test rendering huge amount of text, and the incidence of clipping.
static void ShowExampleAppLongText(bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Long text display", p_open))
{
ImGui::End();
return;
}
static int test_type = 0;
static ImGuiTextBuffer log;
static int lines = 0;
ImGui::Text("Printing unusually long amount of text.");
ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped (slow)\0");
ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size());
if (ImGui::Button("Clear"))
{
log.clear();
lines = 0;
}
ImGui::SameLine();
if (ImGui::Button("Add 1000 lines"))
{
for (int i = 0; i < 1000; i++)
log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i);
lines += 1000;
}
ImGui::BeginChild("Log");
switch (test_type)
{
case 0:
// Single call to TextUnformatted() with a big buffer
ImGui::TextUnformatted(log.begin(), log.end());
break;
case 1:
{
// Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper.
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
ImGuiListClipper clipper(lines);
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
ImGui::PopStyleVar();
break;
}
case 2:
// Multiple calls to Text(), not clipped (slow)
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
for (int i = 0; i < lines; i++)
ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
ImGui::PopStyleVar();
break;
}
ImGui::EndChild();
ImGui::End();
}
// End of Demo code
#else
void ImGui::ShowDemoWindow(bool*) {}
void ImGui::ShowUserGuide() {}
void ImGui::ShowStyleEditor(ImGuiStyle*) {}
#endif
| [
"m.tym29101998@gmail.com"
] | m.tym29101998@gmail.com |
96c08b03a30c644d622e7d2ae8091de6f98a7cb8 | adc7f57c01c2033f99376c8410c494df6d0cdd49 | /mapEditor/src/MapEditorWindow.cpp | 6c217ea68a6b2ed423a38dd1f1ee8ad416a06058 | [
"MIT"
] | permissive | ren19890419/urchinEngine | 6f9ae95db44dc35dc0b4b8b2dafd15ed2f5d1cf4 | 0fa03dcdd6b750df9b32e544caf694eab3135d68 | refs/heads/master | 2022-11-24T03:03:32.517112 | 2020-07-22T18:44:29 | 2020-07-22T18:44:29 | 287,976,459 | 1 | 0 | null | 2020-08-16T15:58:41 | 2020-08-16T15:58:40 | null | UTF-8 | C++ | false | false | 16,246 | cpp | #include "MapEditorWindow.h"
#include "widget/dialog/NewDialog.h"
#include "widget/dialog/NotSavedDialog.h"
#include "panel/objects/ObjectTableView.h"
#include "panel/objects/bodyshape/BodyCompoundShapeWidget.h"
#include "panel/objects/bodyshape/support/LocalizedShapeTableView.h"
#include "panel/lights/LightTableView.h"
#include "panel/sounds/SoundTableView.h"
#include "StateSaveHelper.h"
#include <stdexcept>
#include <QApplication>
#include <QMenuBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QFileDialog>
#include <utility>
#include <QtCore/QStandardPaths>
namespace urchin
{
//static
const std::string MapEditorWindow::WINDOW_TITLE = "Urchin - Map Editor";
MapEditorWindow::MapEditorWindow(std::string mapEditorPath) :
statusBarController(StatusBarController(this)),
saveAction(nullptr),
saveAsAction(nullptr),
closeAction(nullptr),
mapEditorPath(std::move(mapEditorPath)),
sceneController(nullptr),
sceneDisplayerWidget(nullptr),
scenePanelWidget(nullptr)
{
this->setAttribute(Qt::WA_DeleteOnClose);
this->setWindowTitle(QString::fromStdString(WINDOW_TITLE));
this->resize(1200, 675);
auto *centralWidget = new QWidget(this);
auto *horizontalLayout = new QHBoxLayout(centralWidget);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(0, 0, 0, 0);
setupMenu();
statusBarController.clearState();
setupSceneDisplayerWidget(centralWidget, horizontalLayout);
setupSceneControllerWidget(centralWidget, horizontalLayout);
this->setCentralWidget(centralWidget);
}
MapEditorWindow::~MapEditorWindow()
{
delete sceneController;
}
void MapEditorWindow::setupMenu()
{
auto *menu = new QMenuBar(this);
auto *fileMenu = new QMenu("File");
auto *newAction = new QAction("New...", this);
newAction->setShortcut(QKeySequence("Ctrl+N"));
fileMenu->addAction(newAction);
connect(newAction, SIGNAL(triggered()), this, SLOT(showNewDialog()));
auto *openAction = new QAction("Open...", this);
openAction->setShortcut(QKeySequence("Ctrl+O"));
fileMenu->addAction(openAction);
connect(openAction, SIGNAL(triggered()), this, SLOT(showOpenDialog()));
saveAction = new QAction("Save", this);
saveAction->setEnabled(false);
saveAction->setShortcut(QKeySequence("Ctrl+S"));
fileMenu->addAction(saveAction);
connect(saveAction, SIGNAL(triggered()), this, SLOT(executeSaveAction()));
saveAsAction = new QAction("Save as...", this);
saveAsAction->setEnabled(false);
saveAsAction->setShortcut(QKeySequence("Ctrl+Shift+S"));
fileMenu->addAction(saveAsAction);
connect(saveAsAction, SIGNAL(triggered()), this, SLOT(showSaveAsDialog()));
closeAction = new QAction("Close", this);
closeAction->setEnabled(false);
closeAction->setShortcut(QKeySequence("Ctrl+W"));
fileMenu->addAction(closeAction);
connect(closeAction, SIGNAL(triggered()), this, SLOT(executeCloseAction()));
fileMenu->addSeparator();
auto *exitAction = new QAction("Exit", this);
fileMenu->addAction(exitAction);
connect(exitAction, SIGNAL(triggered()), this, SLOT(executeExitAction()));
auto *viewMenu = new QMenu("View");
auto *viewObjectMenu = new QMenu("Object");
viewMenu->addMenu(viewObjectMenu);
auto *viewPhysicsShapeAction = new QAction("Physics Shape", this);
viewPhysicsShapeAction->setEnabled(false);
viewPhysicsShapeAction->setCheckable(true);
viewPhysicsShapeAction->setChecked(true);
viewObjectMenu->addAction(viewPhysicsShapeAction);
viewActions[SceneDisplayer::MODEL_PHYSICS] = viewPhysicsShapeAction;
connect(viewPhysicsShapeAction, SIGNAL(triggered()), this, SLOT(executeViewPropertiesChangeAction()));
auto *viewLightMenu = new QMenu("Light");
viewMenu->addMenu(viewLightMenu);
auto *viewLightScopeAction = new QAction("Light Scope", this);
viewLightScopeAction->setEnabled(false);
viewLightScopeAction->setCheckable(true);
viewLightScopeAction->setChecked(true);
viewLightMenu->addAction(viewLightScopeAction);
viewActions[SceneDisplayer::LIGHT_SCOPE] = viewLightScopeAction;
connect(viewLightScopeAction, SIGNAL(triggered()), this, SLOT(executeViewPropertiesChangeAction()));
auto *viewSoundMenu = new QMenu("Sound");
viewMenu->addMenu(viewSoundMenu);
auto *viewSoundTriggerAction = new QAction("Sound Trigger", this);
viewSoundTriggerAction->setEnabled(false);
viewSoundTriggerAction->setCheckable(true);
viewSoundTriggerAction->setChecked(true);
viewSoundMenu->addAction(viewSoundTriggerAction);
viewActions[SceneDisplayer::SOUND_TRIGGER] = viewSoundTriggerAction;
connect(viewSoundTriggerAction, SIGNAL(triggered()), this, SLOT(executeViewPropertiesChangeAction()));
auto *viewAIMenu = new QMenu("AI");
viewMenu->addMenu(viewAIMenu);
auto *viewNavMeshAction = new QAction("Navigation Mesh", this);
viewNavMeshAction->setEnabled(false);
viewNavMeshAction->setCheckable(true);
viewNavMeshAction->setChecked(true);
viewAIMenu->addAction(viewNavMeshAction);
viewActions[SceneDisplayer::NAV_MESH] = viewNavMeshAction;
connect(viewNavMeshAction, SIGNAL(triggered()), this, SLOT(executeViewPropertiesChangeAction()));
menu->addMenu(fileMenu);
menu->addMenu(viewMenu);
this->setMenuBar(menu);
}
void MapEditorWindow::setupSceneDisplayerWidget(QWidget *centralWidget, QHBoxLayout *horizontalLayout)
{
sceneDisplayerWidget = new SceneDisplayerWidget(centralWidget, statusBarController, mapEditorPath);
sceneDisplayerWidget->setMouseTracking(true);
sceneDisplayerWidget->setFocusPolicy(Qt::FocusPolicy::ClickFocus);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(sceneDisplayerWidget->sizePolicy().hasHeightForWidth());
sceneDisplayerWidget->setSizePolicy(sizePolicy);
sceneDisplayerWidget->show();
executeViewPropertiesChangeAction();
horizontalLayout->addWidget(sceneDisplayerWidget);
}
void MapEditorWindow::setupSceneControllerWidget(QWidget *centralWidget, QHBoxLayout *horizontalLayout)
{
scenePanelWidget = new ScenePanelWidget(centralWidget);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(scenePanelWidget->sizePolicy().hasHeightForWidth());
scenePanelWidget->setSizePolicy(sizePolicy);
scenePanelWidget->setMaximumSize(QSize(380, 16777215));
scenePanelWidget->getObjectPanelWidget()->addObserver(this, ObjectPanelWidget::OBJECT_BODY_SHAPE_WIDGET_CREATED);
scenePanelWidget->getObjectPanelWidget()->getObjectTableView()->addObserver(this, ObjectTableView::OBJECT_SELECTION_CHANGED);
scenePanelWidget->getLightPanelWidget()->getLightTableView()->addObserver(this, LightTableView::LIGHT_SELECTION_CHANGED);
scenePanelWidget->getSoundPanelWidget()->getSoundTableView()->addObserver(this, SoundTableView::SOUND_SELECTION_CHANGED);
scenePanelWidget->addObserver(this, ScenePanelWidget::TAB_SELECTED);
horizontalLayout->addWidget(scenePanelWidget);
sceneDisplayerWidget->addObserver(scenePanelWidget->getObjectPanelWidget(), SceneDisplayerWidget::BODY_PICKED);
}
QString MapEditorWindow::getPreferredMapPath()
{
std::string savedPreferredMapPath = StateSaveHelper::instance()->retrieveState("preferred.map.path", "./");
return QString::fromStdString(savedPreferredMapPath);
}
void MapEditorWindow::savePreferredMapPath(const std::string &preferredMapPath)
{
StateSaveHelper::instance()->saveState("preferred.map.path", preferredMapPath);
}
void MapEditorWindow::notify(Observable *observable, int notificationType)
{
if(dynamic_cast<ScenePanelWidget *>(observable))
{
if(notificationType == ScenePanelWidget::TAB_SELECTED)
{
executeViewPropertiesChangeAction();
}
}else if(auto *objectTableView = dynamic_cast<ObjectTableView *>(observable))
{
if(notificationType==ObjectTableView::OBJECT_SELECTION_CHANGED)
{
sceneDisplayerWidget->setHighlightSceneObject(objectTableView->getSelectedSceneObject());
}
}else if(auto *lightTableView = dynamic_cast<LightTableView *>(observable))
{
if(notificationType==LightTableView::LIGHT_SELECTION_CHANGED)
{
sceneDisplayerWidget->setHighlightSceneLight(lightTableView->getSelectedSceneLight());
}
}else if(auto *soundTableView = dynamic_cast<SoundTableView *>(observable))
{
if(notificationType==SoundTableView::SOUND_SELECTION_CHANGED)
{
sceneDisplayerWidget->setHighlightSceneSound(soundTableView->getSelectedSceneSound());
}
}else if(dynamic_cast<AbstractController *>(observable))
{
if(notificationType==AbstractController::CHANGES_DONE)
{
refreshWindowTitle();
}
}else
{
handleCompoundShapeSelectionChange(observable, notificationType);
}
}
void MapEditorWindow::handleCompoundShapeSelectionChange(Observable *observable, int notificationType)
{
if(auto *objectControllerWidget = dynamic_cast<ObjectPanelWidget *>(observable))
{
if(notificationType == ObjectPanelWidget::OBJECT_BODY_SHAPE_WIDGET_CREATED)
{
BodyShapeWidget *bodyShapeWidget = objectControllerWidget->getBodyShapeWidget();
if (auto *bodyCompoundShapeWidget = dynamic_cast<BodyCompoundShapeWidget *>(bodyShapeWidget))
{
bodyCompoundShapeWidget->getLocalizedShapeTableView()->addObserver(this, LocalizedShapeTableView::OBJECT_COMPOUND_SHAPE_SELECTION_CHANGED);
}
}
}else if(auto *localizedShapeTableView = dynamic_cast<LocalizedShapeTableView *>(observable))
{
if(notificationType==LocalizedShapeTableView::OBJECT_COMPOUND_SHAPE_SELECTION_CHANGED)
{
sceneDisplayerWidget->setHighlightCompoundShapeComponent(localizedShapeTableView->getSelectedLocalizedShape());
}
}
}
void MapEditorWindow::showNewDialog()
{
if(checkCurrentMapSaved())
{
NewDialog newDialog(this);
newDialog.exec();
if(newDialog.result()==QDialog::Accepted)
{
loadMap(newDialog.getFilename(), newDialog.getRelativeWorkingDirectory());
sceneController->forceModified();
}
}
}
void MapEditorWindow::showOpenDialog()
{
if(checkCurrentMapSaved())
{
QString filename = QFileDialog::getOpenFileName(this, tr("Open file"), getPreferredMapPath(), "XML file (*.xml)", nullptr, QFileDialog::DontUseNativeDialog);
if(!filename.isNull())
{
std::string mapFilename = filename.toUtf8().constData();
std::string relativeWorkingDirectory = MapHandler::getRelativeWorkingDirectory(mapFilename);
loadMap(mapFilename, relativeWorkingDirectory);
}
}
}
void MapEditorWindow::loadMap(const std::string &mapFilename, const std::string &relativeWorkingDirectory)
{
sceneController = new SceneController();
sceneDisplayerWidget->loadMap(sceneController, mapFilename, relativeWorkingDirectory);
scenePanelWidget->loadMap(sceneController);
sceneController->addObserverOnAllControllers(this, AbstractController::CHANGES_DONE);
sceneDisplayerWidget->addObserverObjectMoveController(scenePanelWidget->getObjectPanelWidget(), ObjectMoveController::OBJECT_MOVED);
updateMapFilename(mapFilename);
updateInterfaceState();
}
void MapEditorWindow::executeSaveAction()
{
sceneDisplayerWidget->saveState(mapFilename);
if(sceneController)
{
sceneController->saveMapOnFile(mapFilename);
}
updateInterfaceState();
}
void MapEditorWindow::showSaveAsDialog()
{
QString filename = QFileDialog::getSaveFileName(this, tr("Save file"), getPreferredMapPath(), "XML file (*.xml)", nullptr, QFileDialog::DontUseNativeDialog);
if(!filename.isNull())
{
std::string filenameString = filename.toUtf8().constData();
std::string fileExtension = FileHandler::getFileExtension(filenameString);
if(!StringUtil::insensitiveEquals(fileExtension, ".xml"))
{
filenameString += ".xml";
}
sceneDisplayerWidget->saveState(filenameString);
if(sceneController)
{
sceneController->saveMapOnFile(filenameString);
}
updateMapFilename(filenameString);
updateInterfaceState();
}
}
bool MapEditorWindow::executeCloseAction()
{
bool canProceed = false;
if(checkCurrentMapSaved())
{
sceneDisplayerWidget->closeMap();
scenePanelWidget->closeMap();
updateMapFilename("");
updateInterfaceState();
delete sceneController;
sceneController = nullptr;
canProceed = true;
}
return canProceed;
}
void MapEditorWindow::executeExitAction()
{
if(executeCloseAction())
{
QApplication::quit();
}
}
void MapEditorWindow::closeEvent(QCloseEvent *event)
{
if(executeCloseAction())
{
close();
QApplication::quit();
}else
{
event->ignore();
}
}
bool MapEditorWindow::checkCurrentMapSaved()
{
bool canProceed = true;
if(sceneController != nullptr && sceneController->isModified())
{
NotSavedDialog notSavedDialog(this);
notSavedDialog.exec();
if(notSavedDialog.result()==QDialog::Accepted && notSavedDialog.needSave())
{
executeSaveAction();
}else if(notSavedDialog.result()==QDialog::Rejected)
{
canProceed = false;
}
}
return canProceed;
}
void MapEditorWindow::updateInterfaceState()
{
bool hasMapOpen = sceneController != nullptr;
saveAction->setEnabled(hasMapOpen);
saveAsAction->setEnabled(hasMapOpen);
closeAction->setEnabled(hasMapOpen);
for(auto &viewAction : viewActions)
{
viewAction.second->setEnabled(hasMapOpen);
}
refreshWindowTitle();
}
void MapEditorWindow::updateMapFilename(const std::string &mapFilename)
{
this->mapFilename = mapFilename;
if(!mapFilename.empty())
{
std::string preferredMapPathString = FileHandler::getDirectoryFrom(mapFilename);
savePreferredMapPath(preferredMapPathString);
}
}
void MapEditorWindow::refreshWindowTitle()
{
if(mapFilename.empty())
{
this->setWindowTitle(QString::fromStdString(WINDOW_TITLE));
} else
{
if(sceneController && sceneController->isModified())
{
this->setWindowTitle(QString::fromStdString("*" + WINDOW_TITLE + " (" + mapFilename + ")"));
} else
{
this->setWindowTitle(QString::fromStdString(WINDOW_TITLE + " (" + mapFilename + ")"));
}
}
}
void MapEditorWindow::executeViewPropertiesChangeAction()
{
for(int i=0; i<SceneDisplayer::LAST_VIEW_PROPERTIES; ++i)
{
auto viewProperties = static_cast<SceneDisplayer::ViewProperties>(i);
bool isViewChecked = viewActions[viewProperties]->isChecked();
bool isCorrespondingTabSelected = (scenePanelWidget==nullptr && i==0)
|| (scenePanelWidget!=nullptr && getConcernedTabFor(viewProperties)==scenePanelWidget->getTabSelected());
sceneDisplayerWidget->setViewProperties(viewProperties, isViewChecked && isCorrespondingTabSelected);
}
}
ScenePanelWidget::TabName MapEditorWindow::getConcernedTabFor(SceneDisplayer::ViewProperties viewProperties)
{
if(SceneDisplayer::MODEL_PHYSICS==viewProperties)
{
return ScenePanelWidget::OBJECTS;
}
if(SceneDisplayer::LIGHT_SCOPE==viewProperties)
{
return ScenePanelWidget::LIGHTS;
}
if(SceneDisplayer::SOUND_TRIGGER==viewProperties)
{
return ScenePanelWidget::SOUNDS;
}
if(SceneDisplayer::NAV_MESH==viewProperties)
{
return ScenePanelWidget::AI;
}
throw std::runtime_error("Impossible to find concerned tab for properties: " + std::to_string(viewProperties));
}
}
| [
"petitg1987@gmail.com"
] | petitg1987@gmail.com |
fdf247922cb602a7549209282146ef8192408f8b | 0625c78476f8b6cee821d978de5ff7923dfcbe2c | /LCD_Backpack/LCD_Backpack.ino | ceb07a6714710359b21e68f0ec5256a67cf87bec | [] | no_license | mhernan80/Intermediate_Arduino | 02d2ac86796c853c32fb5c2bd70b527145b3e195 | b6670058d4cdd25c59b64a3713dca79bf8083407 | refs/heads/master | 2021-01-02T11:20:28.003531 | 2020-02-12T20:00:44 | 2020-02-12T20:00:44 | 239,599,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | ino | # include <Wire.h>
# include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F,16,2);//LCD Backpack.ino
int led = 13;
void setup() {
// put your setup code here, to run once:
lcd.init();
lcd.backlight();
lcd.begin (16,2); // for 16 x 2 LCD module
}
void loop() {
delay(1000);
int time = millis();
lcd.setCursor(1, 2);
lcd.print(time/1000); // wait for a second
}
| [
"mhernan80@ccs.local"
] | mhernan80@ccs.local |
d61aa8d8c51ea2e07a5da9676cc9f645c35479ca | f981ae929651ada228fed2dcd183b62b140b2327 | /Util/OSM2ODR/src/utils/geom/AbstractPoly.h | c43f8c1f284a43715325ef56191d121c10826d43 | [
"EPL-2.0",
"CC-BY-4.0",
"MIT",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | supavit-siriwan/carla | 33e34dd9dec997a489092f03491997a479184bfa | bdcb04b9c39c2de2b0f9e654350217898b49dbb7 | refs/heads/master | 2021-07-10T19:15:14.856303 | 2020-11-19T05:51:10 | 2020-11-19T05:51:10 | 213,990,039 | 1 | 0 | MIT | 2020-11-19T05:51:12 | 2019-10-09T18:09:34 | null | UTF-8 | C++ | false | false | 2,198 | h | /****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file AbstractPoly.h
/// @author Daniel Krajzewicz
/// @author Michael Behrisch
/// @date Sept 2002
///
// The base class for polygons
/****************************************************************************/
#pragma once
#include <config.h>
#include "Position.h"
// ===========================================================================
// class definitions
// ===========================================================================
/**
*
*/
class AbstractPoly {
public:
/// @brief constructor
AbstractPoly() { }
/// @brief copy constructor
AbstractPoly(const AbstractPoly&) { }
/// @brief destructor
virtual ~AbstractPoly() { }
/// @brief Returns whether the AbstractPoly the given coordinate
virtual bool around(const Position& p, double offset = 0) const = 0;
/// @brief Returns whether the AbstractPoly overlaps with the given polygon
virtual bool overlapsWith(const AbstractPoly& poly, double offset = 0) const = 0;
/// @brief Returns whether the AbstractPoly is partially within the given polygon
virtual bool partialWithin(const AbstractPoly& poly, double offset = 0) const = 0;
/// @brief Returns whether the AbstractPoly crosses the given line
virtual bool crosses(const Position& p1, const Position& p2) const = 0;
};
| [
"bernatx@gmail.com"
] | bernatx@gmail.com |
356afeaee5c7f0148bf5eaa8519df23b076c95d9 | db3688f06b75c75d68fc1b8aeb8bf3ac26e4ab14 | /givensQR.hpp | 0f8b4a277c726ec01c3527daff6e62586eac98bb | [] | no_license | Lucaszw/JunctionSIM | 4f5e9d3e465d7488d3f1412202cbedb5365b0d60 | 678dc9fba2d642b16527a2fcabd40aeea75debcd | refs/heads/master | 2021-01-01T15:36:46.726887 | 2014-12-13T11:17:53 | 2014-12-13T11:17:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,867 | hpp | #pragma once
#include "matrix.hpp"
#include <stdexcept>
#include <math.h>
#include <algorithm>
namespace mathalgo
{
using namespace std;
template<typename T>
class Givens
{
public:
Givens() : m_oJ(2,2), m_oQ(1,1), m_oR(1,1)
{
}
/*
Calculate the inverse of a matrix using the QR decomposition.
param:
A matrix to inverse
*/
const matrix<T> Inverse( matrix<T>& oMatrix )
{
if ( oMatrix.cols() != oMatrix.rows() )
{
throw domain_error( "matrix has to be square" );
}
matrix<T> oIdentity = matrix<T>::identity( oMatrix.rows() );
Decompose( oMatrix );
return Solve( oIdentity );
}
/*
Performs QR factorization using Givens rotations.
*/
void Decompose( matrix<T>& oMatrix )
{
int nRows = oMatrix.rows();
int nCols = oMatrix.cols();
if ( nRows == nCols )
{
nCols--;
}
else if ( nRows < nCols )
{
nCols = nRows - 1;
}
m_oQ = matrix<T>::identity(nRows);
m_oR = oMatrix;
for ( int j = 0; j < nCols; j++ )
{
for ( int i = j + 1; i < nRows; i++ )
{
GivensRotation( m_oR(j,j), m_oR(i,j) );
PreMultiplyGivens( m_oR, j, i );
PreMultiplyGivens( m_oQ, j, i );
}
}
m_oQ = m_oQ.transpose();
}
/*
Find the solution for a matrix.
http://en.wikipedia.org/wiki/QR_decomposition#Using_for_solution_to_linear_inverse_problems
*/
matrix<T> Solve( matrix<T>& oMatrix )
{
matrix<T> oQtM( m_oQ.transpose() * oMatrix );
int nCols = m_oR.cols();
matrix<T> oS( 1, nCols );
for (int i = nCols-1; i >= 0; i-- )
{
oS(0,i) = oQtM(i, 0);
for ( int j = i + 1; j < nCols; j++ )
{
oS(0,i) -= oS(0,j) * m_oR(i, j);
}
oS(0,i) /= m_oR(i, i);
}
return oS;
}
const matrix<T>& GetQ()
{
return m_oQ;
}
const matrix<T>& GetR()
{
return m_oR;
}
private:
/*
Givens rotation is a rotation in the plane spanned by two coordinates axes.
http://en.wikipedia.org/wiki/Givens_rotation
*/
void GivensRotation( T a, T b )
{
T t,s,c;
if (b == 0)
{
c = (a >=0)?1:-1;
s = 0;
}
else if (a == 0)
{
c = 0;
s = (b >=0)?-1:1;
}
else if (abs(b) > abs(a))
{
t = a/b;
s = -1/sqrt(1+t*t);
c = -s*t;
}
else
{
t = b/a;
c = 1/sqrt(1+t*t);
s = -c*t;
}
m_oJ(0,0) = c; m_oJ(0,1) = -s;
m_oJ(1,0) = s; m_oJ(1,1) = c;
}
/*
Get the premultiplication of a given matrix
by the Givens rotation.
*/
void PreMultiplyGivens( matrix<T>& oMatrix, int i, int j )
{
int nRowSize = oMatrix.cols();
for ( int nRow = 0; nRow < nRowSize; nRow++ )
{
double nTemp = oMatrix(i,nRow) * m_oJ(0,0) + oMatrix(j,nRow) * m_oJ(0,1);
oMatrix(j,nRow) = oMatrix(i,nRow) * m_oJ(1,0) + oMatrix(j,nRow) * m_oJ(1,1);
oMatrix(i,nRow) = nTemp;
}
}
private:
matrix<T> m_oQ, m_oR, m_oJ;
};
} | [
"lucas.zeer@gmail.com"
] | lucas.zeer@gmail.com |
0d424557577779ae748c18230a7687cd3ceb7ab2 | 38229dd980b5752e8a53f9ef5e701ba6ab69c356 | /cplusplus/boost/rgb_to_jpeg.cpp | 63fbdc9b202ac66ba19781e24210c895989b0128 | [] | no_license | xs233/mytest | ebefd4c6e84a78b50e26e61d4aebf6cb82e21aa0 | b9f0d88bdfde30cce81da5004cf5270c2272a4f7 | refs/heads/master | 2021-09-13T11:48:03.164360 | 2018-04-29T10:20:52 | 2018-04-29T10:20:52 | 114,317,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | cpp | #include <boost/gil/extension/io/jpeg_io.hpp>
const unsigned width = 320;
const unsigned height = 200;
// Raw data.
unsigned char r[width * height]; // red
unsigned char g[width * height]; // green
unsigned char b[width * height]; // blue
int main()
{
boost::gil::rgb8c_planar_view_t view = boost::gil::planar_rgb_view(width, height, r, g, b, width);
boost::gil::jpeg_write_view("out.jpg", view);
return 0;
} | [
"sheng.xu@impower-tech.com"
] | sheng.xu@impower-tech.com |
2a4407917e6743a2ff09fc88b548e3249fd98099 | 243d6e544994c1a3f5ea8565edc988fd755c8392 | /traffic-generator/src/TrafficGenerator.cpp | adf5d06521f6d76e5b9802553460a012284f3a75 | [
"MIT"
] | permissive | mariobadr/synfull-isca | 1070a0e1fc8c668eaa4239b289ff955859b5173f | 21f7dafde928ad84e3607662dfcfa5914cd41cc5 | refs/heads/master | 2021-01-19T10:16:49.659993 | 2019-05-16T13:35:55 | 2019-05-16T13:35:55 | 87,848,655 | 7 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 12,769 | cpp | /*
Copyright (c) 2014, Mario Badr
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* TrafficGenerator.cpp
*
* Created on: 2013-01-13
* Author: mario
*/
#include <iostream>
#include <list>
#include <math.h>
#include "assert.h"
#include <map>
#include <list>
#include <set>
#include "socketstream.h"
#include "messages.h"
#include "Global.h"
#include "PacketQueue.h"
using namespace std;
//Set this to 0 to debug without connecting to booksim
#define CONNECT 1
SocketStream m_channel;
static unsigned long long next_interval;
static unsigned long long next_hinterval;
static unsigned long long cycle;
int state = 1;
int lastState = 1;
int lastHState = 1;
int messageId = 0;
//Steady state
map<int, map<int, int> > steadyState;
map<int, int> hSteadyState;
map<int, double> acceptable_mse;
double acceptable_hmse;
struct transaction_t {
int source;
int dest;
int invs_sent;
int acks_received;
bool data_received;
bool unblock_received;
bool Completed() {
return (invs_sent == acks_received) && data_received && unblock_received;
}
transaction_t() : source(-1), dest(-1), invs_sent(0), acks_received(0),
data_received(false), unblock_received(false) {}
};
map<int, InjectReqMsg> inTransitPackets;
map<int, transaction_t> inTransitTransactions;
PacketQueue packet_queue;
void TranslateIndex(int index, int& source, int& destination) {
source = (int) index / 32; //Truncate remainder
destination = index - (source * 32);
}
void printPacket(InjectReqMsg msg) {
cout << msg.id << " ";
cout << cycle << " ";
cout << msg.source << " ";
cout << msg.dest << " ";
cout << msg.packetSize << " ";
cout << msg.msgType << " ";
cout << msg.coType << " ";
cout << msg.address << " ";
cout << state;
cout << endl;
}
void connect() {
#if CONNECT
// connect to network simulator
assert(m_channel.connect(NS_HOST, NS_PORT) == 0);
// send request to initialize
InitializeReqMsg req;
InitializeResMsg res;
m_channel << req >> res;
#endif
}
void exit() {
#if CONNECT
// Notify network we are quitting
QuitReqMsg req;
QuitResMsg res;
m_channel << req >> res;
#endif
}
void sendPacket(InjectReqMsg& req) {
req.id = messageId;
if((int) req.address == -1) {
req.address = messageId;
inTransitTransactions[req.address].source = req.source;
inTransitTransactions[req.address].dest = req.dest;
inTransitTransactions[req.address].invs_sent = 0;
inTransitTransactions[req.address].acks_received = 0;
}
messageId++;
inTransitPackets[req.id] = req;
//printPacket(req);
#if CONNECT
InjectResMsg res;
m_channel << req >> res;
#endif
}
double calculate_mse(vector<double> predict, vector<double> actual) {
if(predict.size() != actual.size()) {
return -1;
}
double sum = 0;
for(unsigned int i = 0; i < predict.size(); i++) {
sum += (predict[i] - actual[i]) * (predict[i] - actual[i]);
}
return ((double) sum / predict.size());
}
bool InHSteadyState(int numCycles) {
vector<double> predict;
int sum = 0;
for (map<int, int>::iterator it=hSteadyState.begin();
it!=hSteadyState.end(); ++it) {
double value = it->second;
sum+= value;
predict.push_back(value);
}
for(unsigned int i = 0; i < predict.size(); i++) {
predict[i] = ((double) predict[i] / sum);
}
double mse = calculate_mse(predict, g_hierSState);
if(mse >= 0 && mse < acceptable_hmse && cycle > numCycles*0.3) {
return true;
}
if(cycle > numCycles*0.7) {
return true;
}
return false;
}
void QueuePacket(int source, int destination, int msgType, int coType,
int packetSize, int time, int address) {
InjectReqMsg packet;
packet.source = source;
packet.dest = destination;
packet.cl = 0;
packet.network = 0;
packet.packetSize = packetSize;
packet.msgType = msgType;
packet.coType = coType;
packet.address = address;
packet_queue.Enqueue(packet, time);
}
void UniformInject(int writes, int reads, int ccrs, int dcrs) {
int source, destination;
UniformDistribution uni_dist(0, g_resolution/2 -1);
int delta = 0;
for(int i = 0; i < writes; i++) {
delta = uni_dist.Generate() * 2;
source = g_writeSpat[g_hierClass][state].Generate();
source = source * 2;
destination = g_writeDest[g_hierClass][state][source].Generate();
destination = destination * 2 + 1;
QueuePacket(source, destination, REQUEST, WRITE, CONTROL_SIZE,
cycle + delta, -1);
}
for(int i = 0; i < reads; i++) {
delta = uni_dist.Generate() * 2;
source = g_readSpat[g_hierClass][state].Generate();
source = source * 2;
destination = g_readDest[g_hierClass][state][source].Generate();
destination = destination * 2 + 1;
QueuePacket(source, destination, REQUEST, READ, CONTROL_SIZE,
cycle + delta, -1);
}
for(int i = 0; i < ccrs; i++) {
delta = uni_dist.Generate() * 2;
source = g_ccrSpat[g_hierClass][state].Generate();
source = source * 2;
destination = g_ccrDest[g_hierClass][state][source].Generate();
destination = destination * 2 + 1;
QueuePacket(source, destination, REQUEST, PUTC, CONTROL_SIZE,
cycle + delta, -1);
}
for(int i = 0; i < dcrs; i++) {
delta = uni_dist.Generate() * 2;
source = g_dcrSpat[g_hierClass][state].Generate();
source = source * 2;
destination = g_dcrDest[g_hierClass][state][source].Generate();
destination = destination * 2 + 1;
QueuePacket(source, destination, REQUEST, PUTD, DATA_SIZE,
cycle + delta, -1);
}
}
//Volumes
void InitiateMessages() {
int writes = g_writes[g_hierClass][state].Generate();
int reads = g_reads[g_hierClass][state].Generate();
int ccrs = g_ccrs[g_hierClass][state].Generate();
int dcrs = g_dcrs[g_hierClass][state].Generate();
UniformInject(writes, reads, ccrs, dcrs);
}
void Inject() {
list<InjectReqMsg> packets = packet_queue.DeQueue(cycle);
list<InjectReqMsg>::iterator it;
for(it = packets.begin(); it != packets.end(); ++it) {
sendPacket(*it);
}
packet_queue.CleanUp(cycle);
}
void react(EjectResMsg ePacket) {
map<int, InjectReqMsg>::iterator it = inTransitPackets.find(ePacket.id);
if(it == inTransitPackets.end()) {
cerr << "Error: couldn't find in transit packet " << ePacket.id << endl;
exit(-1);
}
InjectReqMsg request = it->second;
InjectReqMsg response;
inTransitPackets.erase(it);
map<int, transaction_t>::iterator trans = inTransitTransactions.find(request.address);
if(request.msgType == REQUEST &&
(request.coType == WRITE || request.coType == READ)) {
//Handle Read/Write Requests
if((int) request.address == request.id) {
//This is an initiating request. Should we forward it or go to
//memory?
bool isForwarded = g_toForward[g_hierClass][request.dest][request.coType].Generate() == 0;
if(isForwarded) {
int destination = g_forwardDest[g_hierClass][state][request.dest].Generate();
destination = destination*2;
if(destination % 2 != 0) {
cerr << "Error: Invalid destination for forwarded request." << endl;
exit();
}
QueuePacket(request.dest, destination, REQUEST, request.coType,
CONTROL_SIZE, cycle + 1, request.address);
if(request.coType == WRITE) {
//How many invalidates to send
int numInv = g_numInv[g_hierClass][state][request.dest].Generate();
int s = state;
if(numInv <= 0) {
return;
}
//Ensure invalidate destinations are unique (i.e. no two
//invalidate messages to the same destination)
set<int> destinations;
destinations.insert(destination); //Request already forwarded here
while(destinations.size() != (unsigned int) numInv) {
int dest = g_invDest[g_hierClass][s][request.dest].Generate();
dest = dest*2;
destinations.insert(dest);
}
for(set<int>::iterator it = destinations.begin();
it != destinations.end(); ++it) {
QueuePacket(request.dest, *it, REQUEST, INV,
CONTROL_SIZE, cycle + 1, request.address);
trans->second.invs_sent++;
}
}
} else {
//Access memory, queue up a data response for the future
QueuePacket(request.dest, request.source, RESPONSE, DATA,
DATA_SIZE, cycle + 80, request.address);
}
return;
} else {
//This is not an initiating request, so it's a forwarded request
//Respond with Data
QueuePacket(request.dest,
trans->second.source, RESPONSE,
DATA, DATA_SIZE, cycle + 1, request.address);
}
} else if(request.msgType == REQUEST &&
(request.coType == PUTC || request.coType == PUTD)) {
//Respond with WB_ACK
QueuePacket(request.dest, request.source, RESPONSE, WB_ACK,
CONTROL_SIZE, cycle + 1, request.address);
} else if(request.msgType == REQUEST && request.coType == INV) {
//Respond with Ack
QueuePacket(request.dest, trans->second.source,
RESPONSE, ACK, CONTROL_SIZE, cycle + 1, request.address);
} else if(request.msgType == RESPONSE && request.coType == DATA) {
trans->second.data_received = true;
//Send unblock
QueuePacket(inTransitTransactions[request.address].source,
inTransitTransactions[request.address].dest, RESPONSE, UNBLOCK,
CONTROL_SIZE, cycle + 1, request.address);
} else if(request.msgType == RESPONSE && request.coType == ACK) {
trans->second.acks_received++;
} else if(request.msgType == RESPONSE && request.coType == UNBLOCK) {
trans->second.unblock_received = true;
}
if(trans->second.Completed()) {
inTransitTransactions.erase(trans);
}
}
void Eject() {
#if CONNECT
EjectReqMsg req; //The request to the network
EjectResMsg res; //The response from the network
bool hasRequests = true; //Whether there are more requests from the network
//Loop through all the network's messages
while(hasRequests) {
m_channel << req >> res;
if(res.id >= 0) {
//Add responses to list
if(res.id > -1) {
react(res);
}
}
//Check if there are more messages from the network
hasRequests = res.remainingRequests;
}
#endif
}
void reset_ss() {
for (std::map<int,int>::iterator it=steadyState[g_hierClass].begin();
it!=steadyState[g_hierClass].end(); ++it) {
it->second = 0;
}
state = 1;
}
void Run(unsigned int numCycles, bool ssExit) {
next_interval = 0;
next_hinterval = 0;
//Calculate an acceptable MSE for the Markovian Steady-State
double sensitivity = 1.04;
vector<double> predict;
for (unsigned int i = 0; i < g_hierSState.size(); i++) {
predict.push_back(((double) g_hierSState[i] * sensitivity));
}
acceptable_hmse = calculate_mse(predict, g_hierSState);
//Connect to network simulator
connect();
//Iterate through each cycle and inject packets
for(cycle = 0; cycle < numCycles; ++cycle) {
if(cycle >= next_hinterval) {
next_hinterval += g_timeSpan;
hSteadyState[g_hierClass]++;
if(cycle != 0) {
lastHState = g_hierClass;
g_hierClass = g_hierState[g_hierClass].Generate() + 1;
reset_ss();
}
if(InHSteadyState(numCycles) && ssExit) {
cout << "Ending simulation at steady state: " << cycle << endl;
break;
}
cout << "Current hierarchical state: " << g_hierClass << endl;
}
if(cycle >= next_interval) {
next_interval += g_resolution;
//Track state history for markovian steady state
steadyState[g_hierClass][state]++;
if(cycle != 0) {
//Update state
lastState = state;
state = g_states1[g_hierClass][state].Generate() + 1;
}
//Queue up initiating messages for injection
InitiateMessages();
}
//Inject all of this cycles' messages into the network
Inject();
//Eject from network
Eject();
//Step the network
#if CONNECT
StepReqMsg req;
StepResMsg res;
m_channel << req >> res;
#endif
}
//Close the connection
exit();
}
| [
"mario.badr@outlook.com"
] | mario.badr@outlook.com |
5606027722bb504574ec11c30f298fdafebebb03 | 544c73ec661e27a6d640c976fe3c3e4a0b531e62 | /MuTauTreelizer/plugins/JetIdEmbedder.cc | 88e28bc89a7b4b8ab00aa484b5cbee6fad6ac66f | [] | no_license | gracehaza/MuMuTauTauTreeMaker | 5ee7f29fbe47b1d62c6e4114f8bef462464ae11c | 285cc95c29b9657f52bc4b63b4e8254a4db004a4 | refs/heads/master | 2021-10-20T12:44:58.017444 | 2021-07-14T10:48:35 | 2021-07-14T10:48:35 | 184,313,483 | 0 | 0 | null | 2019-04-30T18:39:34 | 2019-04-30T18:39:34 | null | UTF-8 | C++ | false | false | 11,498 | cc | #include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "DataFormats/PatCandidates/interface/Jet.h"
class JetIdEmbedder : public edm::stream::EDProducer<> {
public:
JetIdEmbedder(const edm::ParameterSet& pset);
virtual ~JetIdEmbedder(){}
void produce(edm::Event& evt, const edm::EventSetup& es);
private:
std::string puDisc_;
edm::EDGetTokenT<edm::View<pat::Jet> > srcToken_;
edm::EDGetTokenT<edm::ValueMap<float>> ditau2017v1Token_;
edm::EDGetTokenT<edm::ValueMap<float>> ditau2017MDv1Token_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_boostedToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_boosted_massdecoToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_boosted_nolepton_charmToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_boosted_nolepton_charm_massdecoToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_boosted_nolepton_massdecoToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_boosted_noleptonToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_massdecoToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTauToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_nolepton_charm_massdecoToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_nolepton_charmToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_nolepton_massdecoToken_;
edm::EDGetTokenT<edm::ValueMap<float>> DeepDiTau_noleptonToken_;
};
JetIdEmbedder::JetIdEmbedder(const edm::ParameterSet& pset):
puDisc_(pset.exists("discriminator") ? pset.getParameter<std::string>("discriminator") : "pileupJetId:fullDiscriminant"),
srcToken_(consumes<edm::View<pat::Jet> >(pset.getParameter<edm::InputTag>("slimmedJetTag")))
{
if (pset.exists("ditau2017v1")) { ditau2017v1Token_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("ditau2017v1")); }
if (pset.exists("ditau2017MDv1")) { ditau2017MDv1Token_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("ditau2017MDv1")); }
if (pset.exists("DeepDiTauboostednoleptoncharm")) { DeepDiTau_boosted_nolepton_charmToken_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("DeepDiTauboostednoleptoncharm")); }
if (pset.exists("DeepDiTauboostednoleptoncharmmassdeco")) { DeepDiTau_boosted_nolepton_charm_massdecoToken_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("DeepDiTauboostednoleptoncharmmassdeco")); }
if (pset.exists("DeepDiTauboostednoleptonmassdeco")) { DeepDiTau_boosted_nolepton_massdecoToken_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("DeepDiTauboostednoleptonmassdeco")); }
if (pset.exists("DeepDiTauboostednolepton")) { DeepDiTau_boosted_noleptonToken_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("DeepDiTauboostednolepton")); }
if (pset.exists("DeepDiTaunoleptoncharmmassdeco")) { DeepDiTau_nolepton_charm_massdecoToken_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("DeepDiTaunoleptoncharmmassdeco")); }
if (pset.exists("DeepDiTaunoleptoncharm")) { DeepDiTau_nolepton_charmToken_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("DeepDiTaunoleptoncharm")); }
if (pset.exists("DeepDiTaunoleptonmassdeco")) { DeepDiTau_nolepton_massdecoToken_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("DeepDiTaunoleptonmassdeco")); }
if (pset.exists("DeepDiTaunolepton")) { DeepDiTau_noleptonToken_ = consumes<edm::ValueMap<float> >(pset.getParameter<edm::InputTag>("DeepDiTaunolepton")); }
produces<pat::JetCollection>();
}
void JetIdEmbedder::produce(edm::Event& evt, const edm::EventSetup& es) {
std::unique_ptr<pat::JetCollection> output(new pat::JetCollection);
edm::Handle<edm::View<pat::Jet> > input;
evt.getByToken(srcToken_, input);
edm::Handle<edm::ValueMap<float> > ditau2017v1;
bool ditau2017v1Valid = evt.getByToken(ditau2017v1Token_, ditau2017v1);
edm::Handle<edm::ValueMap<float> > ditau2017MDv1;
bool ditau2017MDv1Valid = evt.getByToken(ditau2017MDv1Token_, ditau2017MDv1);
edm::Handle<edm::ValueMap<float> > DeepDiTauboostednoleptoncharm;
bool DeepDiTau_boosted_nolepton_charmValid = evt.getByToken(DeepDiTau_boosted_nolepton_charmToken_, DeepDiTauboostednoleptoncharm);
edm::Handle<edm::ValueMap<float> > DeepDiTauboostednoleptoncharmmassdeco;
bool DeepDiTau_boosted_nolepton_charm_massdecoValid = evt.getByToken(DeepDiTau_boosted_nolepton_charm_massdecoToken_, DeepDiTauboostednoleptoncharmmassdeco);
edm::Handle<edm::ValueMap<float> > DeepDiTauboostednoleptonmassdeco;
bool DeepDiTau_boosted_nolepton_massdecoValid = evt.getByToken(DeepDiTau_boosted_nolepton_massdecoToken_, DeepDiTauboostednoleptonmassdeco);
edm::Handle<edm::ValueMap<float> > DeepDiTauboostednolepton;
bool DeepDiTau_boosted_noleptonValid = evt.getByToken(DeepDiTau_boosted_noleptonToken_, DeepDiTauboostednolepton);
edm::Handle<edm::ValueMap<float> > DeepDiTaunoleptoncharmmassdeco;
bool DeepDiTau_nolepton_charm_massdecoValid = evt.getByToken(DeepDiTau_nolepton_charm_massdecoToken_, DeepDiTaunoleptoncharmmassdeco);
edm::Handle<edm::ValueMap<float> > DeepDiTaunoleptoncharm;
bool DeepDiTau_nolepton_charmValid = evt.getByToken(DeepDiTau_nolepton_charmToken_, DeepDiTaunoleptoncharm);
edm::Handle<edm::ValueMap<float> > DeepDiTaunoleptonmassdeco;
bool DeepDiTau_nolepton_massdecoValid = evt.getByToken(DeepDiTau_nolepton_massdecoToken_, DeepDiTaunoleptonmassdeco);
edm::Handle<edm::ValueMap<float> > DeepDiTaunolepton;
bool DeepDiTau_noleptonValid = evt.getByToken(DeepDiTau_noleptonToken_, DeepDiTaunolepton);
output->reserve(input->size());
for (size_t i = 0; i < input->size(); ++i) {
pat::Jet jet = input->at(i);
// https://twiki.cern.ch/twiki/bin/view/CMS/JetID
bool loose = true;
bool tight = true;
bool tightLepVeto = true;
if (std::abs(jet.eta()) <= 2.7) {
if (jet.neutralHadronEnergyFraction() >= 0.99) {
loose = false;
}
if (jet.neutralHadronEnergyFraction() >= 0.90) {
tight = false;
tightLepVeto = false;
}
if (jet.neutralEmEnergyFraction() >= 0.99) {
loose = false;
}
if (jet.neutralEmEnergyFraction() >= 0.90) {
tight = false;
tightLepVeto = false;
}
if (jet.chargedMultiplicity()+jet.neutralMultiplicity() <= 1){
loose = false;
tight = false;
tightLepVeto = false;
}
if (jet.muonEnergyFraction() >= 0.8)
{
tightLepVeto = false;
}
if (std::abs(jet.eta()) < 2.4) {
if (jet.chargedHadronEnergyFraction() <= 0) {
loose = false;
tight = false;
tightLepVeto = false;
}
if (jet.chargedHadronMultiplicity() <= 0) {
loose = false;
tight = false;
tightLepVeto = false;
}
if (jet.chargedEmEnergyFraction() >= 0.99) {
loose = false;
tight = false;
}
if (jet.chargedEmEnergyFraction() >= 0.90) {
tightLepVeto = false;
}
}
}
if (std::abs(jet.eta()) > 2.7 && std::abs(jet.eta()) <= 3.0) {
if (jet.neutralEmEnergyFraction() >= 0.90) {
loose = false;
tight = false;
}
if (jet.neutralMultiplicity()<=2) {
loose = false;
tight = false;
}
}
if (std::abs(jet.eta()) > 3.0) {
if (jet.neutralEmEnergyFraction() >= 0.90) {
loose = false;
tight = false;
}
if (jet.neutralMultiplicity()<=10) {
loose = false;
tight = false;
}
}
jet.addUserInt("idLoose", loose);
jet.addUserInt("idTight", tight);
jet.addUserInt("idTightLepVeto", tightLepVeto);
// Pileup discriminant
bool passPU = true;
float jpumva = jet.userFloat(puDisc_);
if(jet.pt() > 20)
{
if(fabs(jet.eta()) > 3.)
{
if(jpumva <= -0.45) passPU = false;
}
else if(fabs(jet.eta()) > 2.75)
{
if(jpumva <= -0.55) passPU = false;
}
else if(fabs(jet.eta()) > 2.5)
{
if(jpumva <= -0.6) passPU = false;
}
else if(jpumva <= -0.63) passPU = false;
}
else
{
if(fabs(jet.eta()) > 3.)
{
if(jpumva <= -0.95) passPU = false;
}
else if(fabs(jet.eta()) > 2.75)
{
if(jpumva <= -0.94) passPU = false;
}
else if(fabs(jet.eta()) > 2.5)
{
if(jpumva <= -0.96) passPU = false;
}
else if(jpumva <= -0.95) passPU = false;
}
jet.addUserInt("puID", passPU);
float ditau2017v1Value = 0;
float ditau2017MDv1Value = 0;
float DeepDiTau_boosted_nolepton_charmValue = 0;
float DeepDiTau_boosted_nolepton_charm_massdecoValue = 0;
float DeepDiTau_boosted_nolepton_massdecoValue = 0;
float DeepDiTau_boosted_noleptonValue = 0;
float DeepDiTau_nolepton_charm_massdecoValue = 0;
float DeepDiTau_nolepton_charmValue = 0;
float DeepDiTau_nolepton_massdecoValue = 0;
float DeepDiTau_noleptonValue = 0;
edm::Ref<edm::View<pat::Jet> > jRef(input,i);
if (ditau2017v1Valid) ditau2017v1Value = (*ditau2017v1)[jRef];
if (ditau2017MDv1Valid) ditau2017MDv1Value = (*ditau2017MDv1)[jRef];
if (DeepDiTau_boosted_nolepton_charmValid) DeepDiTau_boosted_nolepton_charmValue = (*DeepDiTauboostednoleptoncharm)[jRef];
if (DeepDiTau_boosted_nolepton_charm_massdecoValid) DeepDiTau_boosted_nolepton_charm_massdecoValue = (*DeepDiTauboostednoleptoncharmmassdeco)[jRef];
if (DeepDiTau_boosted_nolepton_massdecoValid) DeepDiTau_boosted_nolepton_massdecoValue = (*DeepDiTauboostednoleptonmassdeco)[jRef];
if (DeepDiTau_boosted_noleptonValid) DeepDiTau_boosted_noleptonValue = (*DeepDiTauboostednolepton)[jRef];
if (DeepDiTau_nolepton_charm_massdecoValid) DeepDiTau_nolepton_charm_massdecoValue = (*DeepDiTaunoleptoncharmmassdeco)[jRef];
if (DeepDiTau_nolepton_charmValid) DeepDiTau_nolepton_charmValue = (*DeepDiTaunoleptoncharm)[jRef];
if (DeepDiTau_nolepton_massdecoValid) DeepDiTau_nolepton_massdecoValue = (*DeepDiTaunoleptonmassdeco)[jRef];
if (DeepDiTau_noleptonValid) DeepDiTau_noleptonValue = (*DeepDiTaunolepton)[jRef];
jet.addUserFloat("ditau2017v1",ditau2017v1Value);
jet.addUserFloat("ditau2017MDv1",ditau2017MDv1Value);
jet.addUserFloat("DeepDiTau_boosted_nolepton_charm",DeepDiTau_boosted_nolepton_charmValue);
jet.addUserFloat("DeepDiTau_boosted_nolepton_charm_massdeco",DeepDiTau_boosted_nolepton_charm_massdecoValue);
jet.addUserFloat("DeepDiTau_boosted_nolepton_massdeco",DeepDiTau_boosted_nolepton_massdecoValue);
jet.addUserFloat("DeepDiTau_boosted_nolepton",DeepDiTau_boosted_noleptonValue);
jet.addUserFloat("DeepDiTau_nolepton_charm_massdeco",DeepDiTau_nolepton_charm_massdecoValue);
jet.addUserFloat("DeepDiTau_nolepton_charm",DeepDiTau_nolepton_charmValue);
jet.addUserFloat("DeepDiTau_nolepton_massdeco",DeepDiTau_nolepton_massdecoValue);
jet.addUserFloat("DeepDiTau_nolepton",DeepDiTau_noleptonValue);
output->push_back(jet);
}
evt.put(std::move(output));
}
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(JetIdEmbedder);
| [
"gmhaza@ucdavis.edu"
] | gmhaza@ucdavis.edu |
f6a5b4f9fbd10887a5c617af20b98f30c515f255 | 5deab316a4ab518e3a409ab69885d372f4d45706 | /RCP/October2020/E.cpp | 53a6a6d1add31ac90b491fcdcd36edf0aebf3599 | [] | no_license | af-orozcog/competitiveProgramming | 9c01937b321b74f3d6b24e1b8d67974cad841e17 | 5bbfbd4da9155a7d1ad372298941a04489207ff5 | refs/heads/master | 2023-04-28T11:44:04.320533 | 2021-05-19T19:04:30 | 2021-05-19T19:04:30 | 203,208,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,854 | cpp | //#pragma GCC optimize("O3")
//(UNCOMMENT WHEN HAVING LOTS OF RECURSIONS)\
#pragma comment(linker, "/stack:200000000")
//(UNCOMMENT WHEN NEEDED)\
#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")\
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define MAX 100005
#define ff first
#define ss second
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
err(++it, args...);
}
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
int nums[MAX];
pdd get_recta(double x1, double x2, double y1, double y2) {
double m = (y2-y1)/(x2-x1);
double b = y1-m*x1;
return {m,b};
}
double eval_inv(pdd f, double y){
return (y-f.ss)/f.ff;
}
double eval (pdd f, double x, double xi, double xd, double my){
if(x>=(xi-1e-6) && x<=(xd+1e-6)) return f.ff*x+f.ss;
return my;
}
double inter(pdd f1, pdd f2){
return (f2.ss-f1.ss)/(f1.ff-f2.ff);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//freopen("1.in", "r", stdin);
int t, n, a, b, m;
int x1,x2,x3,x4;
int y1, y2, y3, y4;
cin>>x1>>y1>>x2>>y2;
pdd f1 = get_recta(x1, x2, y1, y2);
cin>>x3>>y3>>x4>>y4;
pdd f2 = get_recta(x3, x4, y3, y4);
int my = min(y2, y4);
double dx = abs(eval_inv(f1, my)-eval_inv(f2, my));
double dy = my-eval(f1, inter(f1, f2), max(x1, x4), min(x2, x3), my);
if(dy>my) dy = 0;
cout<<fixed<<setprecision(9)<<(dy*dx)/2.0<<"\n";
}
| [
"af.orozcog@uniandes.edu.co"
] | af.orozcog@uniandes.edu.co |
f4003f913dbd24436ae4c7821a6dfe249a2762e5 | ecd7d2120a0e99c17defdb11ffabc8b237df576c | /cf1315A.cpp | eaf2858599c94ecdc779d20c964341eab3487899 | [] | no_license | emanlaicepsa/codes | 246735d9b04945ba3511f2bb2f20581abb405ddc | da2fdee786433708251cc8c4fc472e21354a6bc4 | refs/heads/master | 2021-05-20T08:51:38.902467 | 2020-04-01T14:58:51 | 2020-04-01T14:58:51 | 252,206,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | cpp | #include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);cin.tie(0);
#define fi first
#define se second
#define reset(n,k) memset((n),k,sizeof(n))
#define all(n) n.begin(),n.end()
#define pb push_back
using namespace std;
using ll=long long;
using pii=pair<int,int>;
int main(){
IOS;
ll t,a,b,c,d;
cin>>t;
while(t--){
cin>>a>>b>>c>>d;
ll ans = 0;
ans = max((a-c-1)*b,ans);
ans = max(c*b,ans);
ans = max(a*d,ans);
ans = max((b-d-1)*a,ans);
cout<<ans<<'\n';
}
}
| [
"kevin118033@gmail.com"
] | kevin118033@gmail.com |
815f1b8867ca0970617e9c3edc22a3d4aa13f07d | 5d1003e596524182f126611b837b56a91ef0b1b7 | /Ardomos/thermo.cpp | f278c089350a4478d9ea81b307c2a402bbae014a | [] | no_license | hsaturn/Domosat | 3d39c5e94f686b0c00174ee403f44e6914c046b6 | 46231d297a79fdb3bce01223ab93215485e014b4 | refs/heads/master | 2021-01-13T03:32:36.512359 | 2017-01-11T16:38:55 | 2017-01-11T16:38:55 | 77,529,811 | 0 | 0 | null | 2016-12-29T10:50:34 | 2016-12-28T12:01:31 | Java | UTF-8 | C++ | false | false | 6,864 | cpp | // Flags=1001
#include <Arduino.h>
// From images/thermo.png, , 21x60 bytes: 668
// rgb16 rgbmode 1 indexed 4bits offset(0,30)
const uint8_t thermo[] PROGMEM={0xad,0x29,0x15,0x3c,0x0,0x1e,0x0,0x20,0x52,0x48,0x94,0x70,0xad,0x54,0x6b,0x4d,0xff,0xde,0xef,0x3d,0xd6,0x9a,0xce,0x39,0xe6,0xff,0xc6,0x3d,0x63,0x39,0x8c,0x3a,0x8,0x38,0x3a,0x16,0x0,0x0,0x11,0x11,0x23,0x44,0x44,0x44,0x44,0x45,0x11,0x11,0x11,0x11,0x46,0x66,0x66,0x77,0x77,0x88,0x89,0x51,0x11,0x11,0x86,0x66,0x66,0x67,0x77,0x78,0x88,0x88,0x51,0x11,0x46,0x66,0x66,0x66,0x77,0x78,0x88,0x88,0x98,0x51,0x26,0x66,0x66,0x67,0x67,0x77,0x78,0x88,0x99,0x89,0x13,0x66,0x66,0x66,0x66,0x66,0x67,0x78,0x88,0x89,0x82,0x96,0x66,0x66,0x66,0x66,0x66,0x67,0x88,0x88,0x99,0x59,0x66,0x66,0x66,0x66,0x66,0x66,0x88,0x88,0x89,0x85,0x96,0x78,0x88,0x76,0x66,0x66,0x67,0x88,0x88,0x99,0x39,0x69,0x44,0x49,0x66,0x66,0x66,0x78,0x88,0x98,0x93,0x96,0x66,0x78,0x76,0x66,0x66,0x67,0x88,0x89,0x89,0x37,0x66,0x68,0x49,0x66,0x66,0x66,0x78,0x88,0x98,0x93,0x86,0x66,0x79,0x76,0x66,0x66,0x67,0x88,0x89,0x89,0x38,0x68,0x99,0x48,0x66,0x66,0x66,0x78,0x88,0x98,0x93,0x86,0x89,0x99,0x86,0x66,0x66,0x67,0x88,0x89,0x89,0x38,0x66,0x68,0x49,0x66,0x66,0x66,0x78,0x88,0x98,0x93,0x96,0x66,0x79,0x96,0x76,0x66,0x67,0x88,0x88,0x99,0x39,0x69,0x44,0x49,0x66,0x66,0x67,0x88,0x88,0x89,0x93,0x46,0x89,0x99,0x86,0x77,0xa6,0x77,0x88,0x89,0x89,0x34,0x66,0x68,0x34,0x6b,0xcc,0xcb,0x88,0x88,0x89,0x83,0x46,0x66,0x78,0x7a,0xde,0xee,0xda,0x88,0x88,0x98,0x34,0x69,0x43,0x49,0x7d,0xee,0xed,0xa8,0x88,0x89,0x83,0x46,0x78,0x88,0x7a,0xde,0xee,0xca,0x88,0x88,0x98,0x34,0x66,0x68,0x49,0x7d,0xee,0xed,0xa8,0x88,0x88,0x93,0x46,0x66,0x79,0x8a,0xde,0xee,0xca,0x88,0x88,0x98,0x34,0x67,0x88,0x98,0xad,0xee,0xec,0xa9,0x49,0x49,0x93,0x46,0x94,0x44,0x9a,0xde,0xee,0xca,0x43,0x33,0x49,0x34,0x66,0x66,0x67,0xad,0xee,0xec,0x88,0x89,0x99,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xca,0x32,0x49,0x88,0x34,0x66,0x66,0x66,0xad,0xee,0xec,0x88,0x88,0x88,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xca,0x35,0x55,0x39,0x34,0x66,0x66,0x66,0xad,0xee,0xec,0xb8,0x88,0x88,0x83,0x46,0x66,0x66,0x6a,0xde,0xee,0xca,0x35,0x49,0x89,0x34,0x66,0x66,0x67,0xad,0xee,0xec,0xa8,0x89,0x99,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x45,0x55,0x39,0x44,0x66,0x66,0x67,0xad,0xee,0xec,0xb8,0x99,0x88,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x43,0x49,0x89,0x44,0x66,0x66,0x66,0xad,0xee,0xec,0xb9,0x99,0x99,0x94,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x94,0x44,0x49,0x44,0x66,0x66,0x66,0xad,0xee,0xec,0xbb,0x43,0x44,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x94,0x98,0x89,0x44,0x66,0x66,0x67,0xad,0xee,0xec,0xb4,0x39,0x88,0x94,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x94,0x44,0x49,0x44,0x66,0x66,0x66,0xad,0xee,0xec,0xb4,0x33,0x34,0x94,0x46,0x66,0x66,0x6a,0xde,0xee,0xfb,0x78,0x88,0x89,0x44,0x66,0x66,0x67,0xac,0xee,0xef,0xd8,0x88,0x88,0x94,0x96,0x66,0x66,0xac,0xee,0xee,0xef,0xba,0x88,0x99,0x49,0x66,0x66,0x7d,0xfe,0xee,0xee,0xec,0xb8,0x89,0x94,0x96,0x66,0x6a,0xce,0xee,0xee,0xee,0xed,0x88,0x89,0x49,0x66,0x66,0xbf,0xee,0xee,0xee,0xee,0xdb,0x88,0x94,0x96,0x66,0x6b,0xfe,0xee,0xee,0xee,0xfd,0x88,0x89,0x49,0x66,0x66,0x7d,0xee,0xee,0xee,0xef,0xb8,0x88,0x94,0x36,0x66,0x66,0xbf,0xee,0xee,0xee,0xdb,0x89,0x84,0x45,0x66,0x66,0x67,0xdf,0xee,0xef,0xcb,0x88,0x98,0x94,0x16,0x66,0x66,0x67,0xbd,0xdd,0xba,0x88,0x88,0x88,0x31,0x46,0x66,0x66,0x77,0x77,0x87,0x88,0x88,0x89,0x92,0x11,0x66,0x66,0x67,0x77,0x77,0x78,0x88,0x89,0x83,0x11,0x12,0x66,0x66,0x77,0x77,0x77,0x88,0x88,0x83,0x11,0x11,0x12,0x96,0x66,0x67,0x77,0x77,0x88,0x85,0x11,0x11,0x11,0x11,0x15,0x55,0x55,0x55,0x55,0x21,0x11,0x11};
// const uint8_t thermo[]={0xad,0x29,0x15,0x3c,0x0,0x1e,0x0,0x20,0x52,0x48,0x94,0x70,0xad,0x54,0x6b,0x4d,0xff,0xde,0xef,0x3d,0xd6,0x9a,0xce,0x39,0xe6,0xff,0xc6,0x3d,0x63,0x39,0x8c,0x3a,0x8,0x38,0x3a,0x16,0x0,0x0,0x11,0x11,0x23,0x44,0x44,0x44,0x44,0x45,0x11,0x11,0x11,0x11,0x46,0x66,0x66,0x77,0x77,0x88,0x89,0x51,0x11,0x11,0x86,0x66,0x66,0x67,0x77,0x78,0x88,0x88,0x51,0x11,0x46,0x66,0x66,0x66,0x77,0x78,0x88,0x88,0x98,0x51,0x26,0x66,0x66,0x67,0x67,0x77,0x78,0x88,0x99,0x89,0x13,0x66,0x66,0x66,0x66,0x66,0x67,0x78,0x88,0x89,0x82,0x96,0x66,0x66,0x66,0x66,0x66,0x67,0x88,0x88,0x99,0x59,0x66,0x66,0x66,0x66,0x66,0x66,0x88,0x88,0x89,0x85,0x96,0x78,0x88,0x76,0x66,0x66,0x67,0x88,0x88,0x99,0x39,0x69,0x44,0x49,0x66,0x66,0x66,0x78,0x88,0x98,0x93,0x96,0x66,0x78,0x76,0x66,0x66,0x67,0x88,0x89,0x89,0x37,0x66,0x68,0x49,0x66,0x66,0x66,0x78,0x88,0x98,0x93,0x86,0x66,0x79,0x76,0x66,0x66,0x67,0x88,0x89,0x89,0x38,0x68,0x99,0x48,0x66,0x66,0x66,0x78,0x88,0x98,0x93,0x86,0x89,0x99,0x86,0x66,0x66,0x67,0x88,0x89,0x89,0x38,0x66,0x68,0x49,0x66,0x66,0x66,0x78,0x88,0x98,0x93,0x96,0x66,0x79,0x96,0x76,0x66,0x67,0x88,0x88,0x99,0x39,0x69,0x44,0x49,0x66,0x66,0x67,0x88,0x88,0x89,0x93,0x46,0x89,0x99,0x86,0x77,0xa6,0x77,0x88,0x89,0x89,0x34,0x66,0x68,0x34,0x6b,0xcc,0xcb,0x88,0x88,0x89,0x83,0x46,0x66,0x78,0x7a,0xde,0xee,0xda,0x88,0x88,0x98,0x34,0x69,0x43,0x49,0x7d,0xee,0xed,0xa8,0x88,0x89,0x83,0x46,0x78,0x88,0x7a,0xde,0xee,0xca,0x88,0x88,0x98,0x34,0x66,0x68,0x49,0x7d,0xee,0xed,0xa8,0x88,0x88,0x93,0x46,0x66,0x79,0x8a,0xde,0xee,0xca,0x88,0x88,0x98,0x34,0x67,0x88,0x98,0xad,0xee,0xec,0xa9,0x49,0x49,0x93,0x46,0x94,0x44,0x9a,0xde,0xee,0xca,0x43,0x33,0x49,0x34,0x66,0x66,0x67,0xad,0xee,0xec,0x88,0x89,0x99,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xca,0x32,0x49,0x88,0x34,0x66,0x66,0x66,0xad,0xee,0xec,0x88,0x88,0x88,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xca,0x35,0x55,0x39,0x34,0x66,0x66,0x66,0xad,0xee,0xec,0xb8,0x88,0x88,0x83,0x46,0x66,0x66,0x6a,0xde,0xee,0xca,0x35,0x49,0x89,0x34,0x66,0x66,0x67,0xad,0xee,0xec,0xa8,0x89,0x99,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x45,0x55,0x39,0x44,0x66,0x66,0x67,0xad,0xee,0xec,0xb8,0x99,0x88,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x43,0x49,0x89,0x44,0x66,0x66,0x66,0xad,0xee,0xec,0xb9,0x99,0x99,0x94,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x94,0x44,0x49,0x44,0x66,0x66,0x66,0xad,0xee,0xec,0xbb,0x43,0x44,0x93,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x94,0x98,0x89,0x44,0x66,0x66,0x67,0xad,0xee,0xec,0xb4,0x39,0x88,0x94,0x46,0x66,0x66,0x6a,0xde,0xee,0xcb,0x94,0x44,0x49,0x44,0x66,0x66,0x66,0xad,0xee,0xec,0xb4,0x33,0x34,0x94,0x46,0x66,0x66,0x6a,0xde,0xee,0xfb,0x78,0x88,0x89,0x44,0x66,0x66,0x67,0xac,0xee,0xef,0xd8,0x88,0x88,0x94,0x96,0x66,0x66,0xac,0xee,0xee,0xef,0xba,0x88,0x99,0x49,0x66,0x66,0x7d,0xfe,0xee,0xee,0xec,0xb8,0x89,0x94,0x96,0x66,0x6a,0xce,0xee,0xee,0xee,0xed,0x88,0x89,0x49,0x66,0x66,0xbf,0xee,0xee,0xee,0xee,0xdb,0x88,0x94,0x96,0x66,0x6b,0xfe,0xee,0xee,0xee,0xfd,0x88,0x89,0x49,0x66,0x66,0x7d,0xee,0xee,0xee,0xef,0xb8,0x88,0x94,0x36,0x66,0x66,0xbf,0xee,0xee,0xee,0xdb,0x89,0x84,0x45,0x66,0x66,0x67,0xdf,0xee,0xef,0xcb,0x88,0x98,0x94,0x16,0x66,0x66,0x67,0xbd,0xdd,0xba,0x88,0x88,0x88,0x31,0x46,0x66,0x66,0x77,0x77,0x87,0x88,0x88,0x89,0x92,0x11,0x66,0x66,0x67,0x77,0x77,0x78,0x88,0x89,0x83,0x11,0x12,0x66,0x66,0x77,0x77,0x77,0x88,0x88,0x83,0x11,0x11,0x12,0x96,0x66,0x67,0x77,0x77,0x88,0x85,0x11,0x11,0x11,0x11,0x15,0x55,0x55,0x55,0x55,0x21,0x11,0x11};
| [
"hsaturn@gmail.com"
] | hsaturn@gmail.com |
83f7fdff8727644b095f848bdfa54f684b7d4bae | 59dc5d428e102bf72eb7245dbbe7a47a66728378 | /tools/xml/GenerateCMake.h | cfbab13e75975e336ab4071ae74c9dc34b637c54 | [] | no_license | HarinarayanKrishnan/VisIt26RC_Trunk | 6716769694d1a309f994056209171f67e5131642 | 581a0825d81169572b48dd80c1946131c03d0858 | refs/heads/master | 2016-09-06T07:14:00.094983 | 2013-05-15T14:36:48 | 2013-05-15T14:36:48 | 7,009,345 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,059 | h | /*****************************************************************************
*
* Copyright (c) 2000 - 2012, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is part of VisIt. For details, see https://visit.llnl.gov/. The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* 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 disclaimer below.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the disclaimer (as noted below) in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the LLNS/LLNL nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
* LLC, THE U.S. DEPARTMENT OF ENERGY 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.
*
*****************************************************************************/
#ifndef GENERATE_CMAKE_H
#define GENERATE_CMAKE_H
#include <QTextStream>
#include "Field.h"
#include <visit-config.h> // for the plugin extension.
#include "Plugin.h"
// ****************************************************************************
// File: GenerateCMake
//
// Purpose:
// Contains a set of classes which override the default implementation
// to create cmake input for the plugin.
//
// Note: This file overrides --
// Plugin
//
// Programmer: Brad Whitlock,
// Creation: Thu Jan 29 13:44:46 PST 2009
//
// Modifications:
// Brad Whitlock, Fri Nov 6 11:15:11 PST 2009
// Handle serial and parallel engine libs.
//
// Brad Whitlock, Mon Nov 23 15:19:10 PST 2009
// I added server components and engine only builds.
//
// David Camp, Thu Jan 14 17:56:29 PST 2010
// Added the ADD_TARGET_DEFINITIONS function to define ENGINE for plots.
//
// Kathleen Bonnell, Tue Jan 26 20:32:55 MST 2010
// Remove setting of LIBRARY_OUTPUT_PATH, (set by parent instead). Add
// call to VISIT_PLUGIN_TARGET_PREFIX macro.
//
// Brad Whitlock, Wed Feb 10 16:36:00 PST 2010
// I made all of the database plugins use the ADD_TARGET_DEFINITIONS
// function.
//
// Eric Brugger, Wed Feb 24 13:00:54 PST 2010
// I modified the database plugins to list the include paths specified
// in the xml file before the VTK include paths.
//
// Eric Brugger, Fri Feb 26 09:47:00 PST 2010
// I modified the database plugins to list the include paths specified
// in the xml file before any of the VisIt include paths. I also modified
// the database plugins to also treat all flags in CXXFLAGS that start
// with "-I" as include paths.
//
// Kathleen Bonnell, Fri May 21 14:15:23 MST 2010
// Add DLL_NETCDF, _CGNSDLL EXODUSII_BUILD_SHARED_LIBS defines for
// windows projects linking with NETCDF, CGNS or EXODUSII.
//
// Kathleen Bonnell, Thu May 27 14:59:13 MST 2010
// Add some more defines for HDF4, discovered as necessary when compiling
// with Visual Studio 9.
//
// Kathleen Bonnell, Fri Sep 24 11:25:32 MST 2010
// Add ENGINE target definition for operators if they contain
// engine-specific code.
//
// Kathleen Bonnell, Tue Nov 16 16:26:47 PST 2010
// Remove logic for mesa. Add newline after each extraInclude for
// legibility in the CMakeLists.txt files.
//
// David Camp, Wed Nov 17 14:54:02 PST 2010
// Added the LIBS libraries to the Plot and Operators, did the samething
// the database code was doing. Also added the link dirs from the ldflags.
//
// Kathleen Bonnell, Fri Sep 24 11:25:32 MST 2010
// Fix windows issues with viewer and gui libs building against an
// installed version of VisIt. Convert Windows paths to CMake paths
// since we are creating a CMake file.
//
// Kathleen Bonnell, Tue Jan 4 08:38:03 PST 2011
// Fix CGNS dll define, due to update of cgns library.
// Add call to VISIT_PLUGIN_TARGET_FOLDER for project grouping in VS.
//
// Eric Brugger, Fri Jan 7 13:38:59 PST 2011
// I replaced the BOXLIB2D and BOXLIB3D variables with just BOXLIB.
//
// Kathleen Bonnell, Tue Jan 11 17:06:21 MST 2011
// Removed setting EXODUSII_BUILD_SHARED_LIBS definition.
//
// Kathleen Bonnell, Thu Jan 13 17:54:38 MST 2011
// Only use VISIT_PLUGIN_TARGET_FOLDER if building from dev.
//
// Brad Whitlock, Wed Feb 23 15:24:48 PST 2011
// Enable Fortran language compilation if the user added Fortran code to the
// list of files.
//
// Kathleen Biagas, Fri Nov 18 10:09:26 MST 2011
// Add plugin name to VISIT_PLUGIN_TARGET_FOLDER args. Eases building/
// debugging individual plugins with Visual Studio when grouped by name.
//
// Kathleen Biagas, Tue Nov 22 14:39:51 PST 2011
// Remove VISIT_PLUGIN_TARGET_PREFIX in favor of VISIT_PLUGIN_TARGET_RUNTIME.
//
// Kathleen Biagas, Mon Jun 18 10:49:07 MST 2012
// Set VISIT_ARCHIVE_DIR on windows to be /lib. Change minimum CMake
// version to 2.8.8.
//
// Kathleen Biagas, Mon Jul 30 15:40:10 MST 2012
// No longer add definition _HDF5USEDLL_ for hdf5 based plugins, as this
// is now predefined in an hdf5 header.
//
// ****************************************************************************
class CMakeGeneratorPlugin : public Plugin
{
public:
CMakeGeneratorPlugin(const QString &n,const QString &l,const QString &t,
const QString &vt,const QString &dt, const QString &v, const QString &ifile,
bool hw, bool ho, bool onlyengine, bool noengine) :
Plugin(n,l,t,vt,dt,v,ifile,hw,ho,onlyengine,noengine)
{
defaultgfiles.clear();
defaultsfiles.clear();
defaultvfiles.clear();
defaultmfiles.clear();
defaultefiles.clear();
defaultwfiles.clear();
if (type == "database")
{
QString filter = QString("avt") + name + "FileFormat.C";
defaultmfiles.push_back(filter);
defaultefiles.push_back(filter);
if (haswriter)
defaultefiles.push_back(QString("avt") + name + "Writer.C");
if (hasoptions)
{
QString options = QString("avt") + name + QString("Options.C");
defaultmfiles.push_back(options);
defaultefiles.push_back(options);
}
}
else if (type == "plot")
{
QString filter = QString("avt") + name + "Filter.C";
defaultvfiles.push_back(filter);
defaultefiles.push_back(filter);
QString widgets = QString("Qvis") + name + "PlotWindow.h";
defaultwfiles.push_back(widgets);
}
else if (type == "operator")
{
QString filter = QString("avt") + name + "Filter.C";
defaultefiles.push_back(filter);
}
}
virtual ~CMakeGeneratorPlugin()
{
}
void
GetFilesWith(const QString &name, const std::vector<QString> &input,
std::set<QString> &output)
{
for(size_t i = 0; i < input.size(); ++i)
{
if(input[i].indexOf(name) != -1)
output.insert(input[i]);
}
}
QString
ConvertDollarParenthesis(const QString &s) const
{
QString retval(s);
retval = retval.replace("$(", "${");
retval = retval.replace(")", "}");
return retval;
}
QString
ToString(const std::vector<QString> &vec, bool withNewline=false) const
{
QString s;
if (withNewline)
{
for(size_t i = 0; i < vec.size(); ++i)
s += (ConvertDollarParenthesis(vec[i]) + "\n");
}
else
{
for(size_t i = 0; i < vec.size(); ++i)
s += (ConvertDollarParenthesis(vec[i]) + " ");
}
return s;
}
QString
VisItIncludeDir() const
{
return using_dev ? "${VISIT_INCLUDE_DIR}" : "${VISIT_INCLUDE_DIR}/visit";
}
#ifdef _WIN32
QString
ToCMakePath(const QString &s) const
{
char exppath[MAX_PATH];
ExpandEnvironmentStrings(s.toStdString().c_str(), exppath, MAX_PATH);
QString retval(exppath);
retval = retval.replace("\\", "/");
return retval;
}
#endif
void WriteCMake_PlotOperator_Includes(QTextStream &out, bool isOperator)
{
// take any ${} from the CXXFLAGS to mean a variable that contains
// include directories.
std::vector<QString> extraIncludes;
for (size_t i=0; i<cxxflags.size(); i++)
{
if(cxxflags[i].startsWith("${"))
extraIncludes.push_back(cxxflags[i]);
else if(cxxflags[i].startsWith("$("))
extraIncludes.push_back(ConvertDollarParenthesis(cxxflags[i]));
}
// Includes
out << "INCLUDE_DIRECTORIES(" << endl;
out << "${CMAKE_CURRENT_SOURCE_DIR}" << endl;
out << "${VISIT_COMMON_INCLUDES}" << endl;
out << VisItIncludeDir() << "/avt/DBAtts/MetaData" << endl;
out << VisItIncludeDir() << "/avt/DBAtts/SIL" << endl;
out << VisItIncludeDir() << "/avt/Database/Database" << endl;
if(isOperator)
{
out << VisItIncludeDir() << "/avt/Expressions/Abstract" << endl;
out << VisItIncludeDir() << "/avt/Expressions/CMFE" << endl;
out << VisItIncludeDir() << "/avt/Expressions/Conditional" << endl;
out << VisItIncludeDir() << "/avt/Expressions/Derivations" << endl;
out << VisItIncludeDir() << "/avt/Expressions/General" << endl;
out << VisItIncludeDir() << "/avt/Expressions/ImageProcessing" << endl;
out << VisItIncludeDir() << "/avt/Expressions/Management" << endl;
out << VisItIncludeDir() << "/avt/Expressions/Math" << endl;
out << VisItIncludeDir() << "/avt/Expressions/MeshQuality" << endl;
out << VisItIncludeDir() << "/avt/Expressions/TimeIterators" << endl;
}
out << VisItIncludeDir() << "/avt/FileWriter" << endl;
out << VisItIncludeDir() << "/avt/Filters" << endl;
out << VisItIncludeDir() << "/avt/IVP" << endl;
out << VisItIncludeDir() << "/avt/Math" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/AbstractFilters" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/Data" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/Pipeline" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/Sinks" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/Sources" << endl;
out << VisItIncludeDir() << "/avt/Plotter" << endl;
out << VisItIncludeDir() << "/avt/QtVisWindow" << endl;
out << VisItIncludeDir() << "/avt/View" << endl;
out << VisItIncludeDir() << "/avt/VisWindow/Colleagues" << endl;
out << VisItIncludeDir() << "/avt/VisWindow/Interactors" << endl;
out << VisItIncludeDir() << "/avt/VisWindow/Proxies" << endl;
out << VisItIncludeDir() << "/avt/VisWindow/Tools" << endl;
out << VisItIncludeDir() << "/avt/VisWindow/VisWindow" << endl;
out << VisItIncludeDir() << "/gui" << endl;
if(isOperator)
{
out << VisItIncludeDir() << "/mdserver/proxy" << endl;
out << VisItIncludeDir() << "/mdserver/rpc" << endl;
}
out << VisItIncludeDir() << "/viewer/main" << endl;
out << VisItIncludeDir() << "/viewer/proxy" << endl;
out << VisItIncludeDir() << "/viewer/rpc" << endl;
out << VisItIncludeDir() << "/winutil" << endl;
out << VisItIncludeDir() << "/visit_vtk/full" << endl;
out << VisItIncludeDir() << "/visit_vtk/lightweight" << endl;
out << "${QT_INCLUDE_DIR}" << endl;
out << "${QT_QTCORE_INCLUDE_DIR}" << endl;
out << "${QT_QTGUI_INCLUDE_DIR}" << endl;
out << "${VTK_INCLUDE_DIRS} " << endl;
out << "${PYTHON_INCLUDE_PATH} " << endl;
out << VisItIncludeDir() << "/visitpy/visitpy " << endl;
if(extraIncludes.size() > 0)
out << ToString(extraIncludes, true);
out << ")" << endl;
}
bool CustomFilesUseFortran(const std::vector<QString> &files) const
{
const char *ext[] = {".f", ".f77", ".f90", ".f95", ".for",
".F", ".F77", ".F90", ".F95", ".FOR"};
for(size_t i = 0; i < files.size(); ++i)
{
for(int j = 0; j < 10; ++j)
{
if(files[i].endsWith(ext[j]))
return true;
}
}
return false;
}
void WriteCMake_Plot(QTextStream &out,
const QString &guilibname,
const QString &viewerlibname)
{
bool useFortran = false;
out << "PROJECT(" << name<< ")" << endl;
out << endl;
if (using_dev)
{
out << "INCLUDE(${VISIT_SOURCE_DIR}/CMake/PluginMacros.cmake)" <<endl;
out << endl;
}
out << "SET(COMMON_SOURCES" << endl;
out << name << "PluginInfo.C" << endl;
out << name << "CommonPluginInfo.C" << endl;
out << atts->name << ".C" << endl;
out << ")" << endl;
out << endl;
out << "SET(LIBI_SOURCES " << endl;
out << name << "PluginInfo.C" << endl;
out << ")" << endl;
out << endl;
// libG sources
out << "SET(LIBG_SOURCES" << endl;
out << name << "GUIPluginInfo.C" << endl;
out << "Qvis" << name << "PlotWindow.C" << endl;
out << "${COMMON_SOURCES}" << endl;
if (customgfiles)
{
useFortran |= CustomFilesUseFortran(gfiles);
for (size_t i=0; i<gfiles.size(); i++)
out << gfiles[i] << endl;
}
else
for (size_t i=0; i<defaultgfiles.size(); i++)
out << defaultgfiles[i] << endl;
out << ")" << endl;
out << "SET(LIBG_MOC_SOURCES" << endl;
out << "Qvis" << name << "PlotWindow.h" << endl;
if (customwfiles)
for (size_t i=0; i<wfiles.size(); i++)
out << wfiles[i] << endl;
out << ")" << endl;
out << endl;
// libV sources
out << "SET(LIBV_SOURCES" << endl;
out << name<<"ViewerPluginInfo.C" << endl;
out << "avt"<<name<<"Plot.C" << endl;
if (customvfiles)
{
useFortran |= CustomFilesUseFortran(vfiles);
for (size_t i=0; i<vfiles.size(); i++)
out << vfiles[i] << endl;
}
else
for (size_t i=0; i<defaultvfiles.size(); i++)
out << defaultvfiles[i] << endl;
out << "${COMMON_SOURCES}" << endl;
out << ")" << endl;
if (customvwfiles)
{
out << "SET(LIBV_MOC_SOURCES" << endl;
for (size_t i=0; i<vwfiles.size(); i++)
out << vwfiles[i] << endl;
out << ")" << endl;
}
out << endl;
// libE sources
out << "SET(LIBE_SOURCES" << endl;
out << name<<"EnginePluginInfo.C" << endl;
out << "avt"<<name<<"Plot.C" << endl;
if (customefiles)
{
useFortran |= CustomFilesUseFortran(efiles);
for (size_t i=0; i<efiles.size(); i++)
out << efiles[i] << endl;
}
else
for (size_t i=0; i<defaultefiles.size(); i++)
out << defaultefiles[i] << endl;
out << "${COMMON_SOURCES}" << endl;
out << ")" << endl;
out << endl;
if(useFortran)
{
out << "ENABLE_LANGUAGE(Fortran)" << endl;
}
// Special rules for OpenGL sources.
std::set<QString> openglFiles;
GetFilesWith("OpenGL", customvfiles ? vfiles : defaultvfiles, openglFiles);
GetFilesWith("OpenGL", customefiles ? efiles : defaultefiles, openglFiles);
if(openglFiles.size() > 0)
{
out << "IF (NOT WIN32)" << endl;
out << " SET_SOURCE_FILES_PROPERTIES(";
for(std::set<QString>::iterator it = openglFiles.begin();
it != openglFiles.end(); ++it)
{
out << *it << " ";
}
out << "\n PROPERTIES" << endl;
out << " COMPILE_FLAGS \"-I ${OPENGL_INCLUDE_DIR}\"" << endl;
out << " )" << endl;
out << "ENDIF (NOT WIN32)" << endl;
}
WriteCMake_PlotOperator_Includes(out, false);
// Pass other CXXFLAGS
for (size_t i=0; i<cxxflags.size(); i++)
{
if(!cxxflags[i].startsWith("${") && !cxxflags[i].startsWith("$("))
out << "ADD_DEFINITIONS(\"" << cxxflags[i] << "\")" << endl;
}
out << endl;
#if 0
if (installpublic)
out << "SET(LIBRARY_OUTPUT_PATH " << visitplugdirpub << ")" << endl;
else if (installprivate)
out << "SET(LIBRARY_OUTPUT_PATH " << visitplugdirpri << ")" << endl;
else
#endif
out << endl;
// Extract extra link directories from LDFLAGS if they have ${},$(),-L
std::vector<QString> linkDirs;
for (size_t i=0; i<ldflags.size(); i++)
{
if(ldflags[i].startsWith("${") || ldflags[i].startsWith("$("))
linkDirs.push_back(ldflags[i]);
else if(ldflags[i].startsWith("-L"))
linkDirs.push_back(ldflags[i].right(ldflags[i].size()-2));
}
out << "LINK_DIRECTORIES(${VISIT_LIBRARY_DIR} ${QT_LIBRARY_DIR} ${GLEW_LIBRARY_DIR} ${VTK_LIBRARY_DIRS} " << ToString(linkDirs) << ")" << endl;
out << endl;
out << "ADD_LIBRARY(I"<<name<<"Plot ${LIBI_SOURCES})" << endl;
out << "TARGET_LINK_LIBRARIES(I"<<name<<"Plot visitcommon)" << endl;
out << "SET(INSTALLTARGETS I"<<name<<"Plot)" << endl;
out << endl;
out << "IF(NOT VISIT_SERVER_COMPONENTS_ONLY AND NOT VISIT_ENGINE_ONLY AND NOT VISIT_DBIO_ONLY)" << endl;
out << " QT_WRAP_CPP(G" << name << "Plot LIBG_SOURCES ${LIBG_MOC_SOURCES})" << endl;
out << " ADD_LIBRARY(G"<<name<<"Plot ${LIBG_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(G" << name << "Plot visitcommon "
<< guilibname << " " << ToString(libs) << ToString(glibs)
<< ")" << endl;
out << endl;
if (customvwfiles)
out << " QT_WRAP_CPP(V" << name << "Plot LIBV_SOURCES ${LIBV_MOC_SOURCES})" << endl;
out << " ADD_LIBRARY(V"<<name<<"Plot ${LIBV_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(V" << name << "Plot visitcommon "
<< viewerlibname << " " << ToString(libs) << ToString(vlibs)
<< ")" << endl;
out << endl;
out << " SET(INSTALLTARGETS ${INSTALLTARGETS} G"<<name<<"Plot V"<<name<<"Plot)" << endl;
out << endl;
// libS sources
out << " IF(VISIT_PYTHON_SCRIPTING)" << endl;
out << " SET(LIBS_SOURCES" << endl;
out << " " << name<<"ScriptingPluginInfo.C" << endl;
out << " Py"<<atts->name<<".C" << endl;
if (customsfiles)
for (size_t i=0; i<sfiles.size(); i++)
out << " " << sfiles[i] << endl;
else
for (size_t i=0; i<defaultsfiles.size(); i++)
out << " " << defaultsfiles[i] << endl;
out << " ${COMMON_SOURCES}" << endl;
out << " )" << endl;
out << " ADD_LIBRARY(S"<<name<<"Plot ${LIBS_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(S" << name
<< "Plot visitcommon visitpy ${PYTHON_LIBRARY})" << endl;
out << " SET(INSTALLTARGETS ${INSTALLTARGETS} S" << name
<< "Plot)" << endl;
out << " ENDIF(VISIT_PYTHON_SCRIPTING)" << endl;
out << endl;
// Java sources
out << " IF(VISIT_JAVA)" << endl;
out << " ADD_CUSTOM_TARGET(Java"<<name<<" ALL ${CMAKE_Java_COMPILER} ${CMAKE_Java_FLAGS} -d ${VISIT_BINARY_DIR}/java -classpath ${VISIT_BINARY_DIR}/java ";
if(customjfiles)
{
for(size_t i = 0; i < jfiles.size(); ++i)
out << jfiles[i] << " ";
}
out << atts->name<<".java)" << endl;
out << " ADD_DEPENDENCIES(Java"<<name<<" JavaClient)" << endl;
out << " ENDIF(VISIT_JAVA)" << endl;
out << "ENDIF(NOT VISIT_SERVER_COMPONENTS_ONLY AND NOT VISIT_ENGINE_ONLY AND NOT VISIT_DBIO_ONLY)" << endl;
out << endl;
out << "ADD_LIBRARY(E"<<name<<"Plot_ser ${LIBE_SOURCES})" << endl;
out << "TARGET_LINK_LIBRARIES(E"<<name<<"Plot_ser visitcommon avtplotter_ser avtpipeline_ser " << ToString(libs) << ToString(elibsSer) << ")" << endl;
out << "SET(INSTALLTARGETS ${INSTALLTARGETS} E"<<name<<"Plot_ser)" << endl;
out << "ADD_TARGET_DEFINITIONS(E"<<name<<"Plot_ser ENGINE)" << endl;
out << endl;
out << "IF(VISIT_PARALLEL)" << endl;
out << " ADD_PARALLEL_LIBRARY(E"<<name<<"Plot_par ${LIBE_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(E"<<name<<"Plot_par visitcommon avtplotter_par avtpipeline_par " << ToString(libs) << ToString(elibsPar) << ")" << endl;
out << " SET(INSTALLTARGETS ${INSTALLTARGETS} E"<<name<<"Plot_par)" << endl;
out << " ADD_TARGET_DEFINITIONS(E"<<name<<"Plot_par ENGINE)" << endl;
out << "ENDIF(VISIT_PARALLEL)" << endl;
out << endl;
out << "VISIT_INSTALL_PLOT_PLUGINS(${INSTALLTARGETS})" << endl;
out << "VISIT_PLUGIN_TARGET_RTOD(plots ${INSTALLTARGETS})" << endl;
if (using_dev)
out << "VISIT_PLUGIN_TARGET_FOLDER(plots " << name
<< " ${INSTALLTARGETS})" << endl;
out << endl;
}
void WriteCMake_Operator(QTextStream &out,
const QString guilibname,
const QString viewerlibname)
{
bool useFortran = false;
out << "PROJECT(" << name<< ")" << endl;
out << endl;
if (using_dev)
{
out << "INCLUDE(${VISIT_SOURCE_DIR}/CMake/PluginMacros.cmake)" <<endl;
out << endl;
}
out << "SET(COMMON_SOURCES" << endl;
out << name << "PluginInfo.C" << endl;
out << name << "CommonPluginInfo.C" << endl;
out << atts->name << ".C" << endl;
out << ")" << endl;
out << endl;
out << "SET(LIBI_SOURCES " << endl;
out << name << "PluginInfo.C" << endl;
out << ")" << endl;
out << endl;
// libG sources
out << "SET(LIBG_SOURCES" << endl;
out << name << "GUIPluginInfo.C" << endl;
out << "Qvis" << name << "Window.C" << endl;
out << "${COMMON_SOURCES}" << endl;
if (customgfiles)
{
useFortran |= CustomFilesUseFortran(gfiles);
for (size_t i=0; i<gfiles.size(); i++)
out << gfiles[i] << endl;
}
else
for (size_t i=0; i<defaultgfiles.size(); i++)
out << defaultgfiles[i] << endl;
out << ")" << endl;
out << "SET(LIBG_MOC_SOURCES" << endl;
out << "Qvis" << name << "Window.h" << endl;
if (customwfiles)
for (size_t i=0; i<wfiles.size(); i++)
out << wfiles[i] << endl;
out << ")" << endl;
out << endl;
// libV sources
out << "SET(LIBV_SOURCES" << endl;
out << name<<"ViewerPluginInfo.C" << endl;
if (customvfiles)
{
useFortran |= CustomFilesUseFortran(vfiles);
for (size_t i=0; i<vfiles.size(); i++)
out << vfiles[i] << endl;
}
else
for (size_t i=0; i<defaultvfiles.size(); i++)
out << defaultvfiles[i] << endl;
out << "${COMMON_SOURCES}" << endl;
out << ")" << endl;
if (customvwfiles)
{
out << "SET(LIBV_MOC_SOURCES" << endl;
for (size_t i=0; i<vwfiles.size(); i++)
out << vwfiles[i] << endl;
out << ")" << endl;
}
out << endl;
// libE sources
out << "SET(LIBE_SOURCES" << endl;
out << name<<"EnginePluginInfo.C" << endl;
if (customefiles)
{
useFortran |= CustomFilesUseFortran(efiles);
for (size_t i=0; i<efiles.size(); i++)
out << efiles[i] << endl;
}
else
for (size_t i=0; i<defaultefiles.size(); i++)
out << defaultefiles[i] << endl;
out << "${COMMON_SOURCES}" << endl;
out << ")" << endl;
out << endl;
if(useFortran)
{
out << "ENABLE_LANGUAGE(Fortran)" << endl;
}
WriteCMake_PlotOperator_Includes(out, true);
// Pass other CXXFLAGS
for (size_t i=0; i<cxxflags.size(); i++)
{
if(!cxxflags[i].startsWith("${") && !cxxflags[i].startsWith("$("))
out << "ADD_DEFINITIONS(\"" << cxxflags[i] << "\")" << endl;
}
out << endl;
#if 0
if (installpublic)
out << "SET(LIBRARY_OUTPUT_PATH " << visitplugdirpub << ")" << endl;
else if (installprivate)
out << "SET(LIBRARY_OUTPUT_PATH " << visitplugdirpri << ")" << endl;
else
#endif
out << endl;
// Extract extra link directories from LDFLAGS if they have ${},$(),-L
std::vector<QString> linkDirs;
for (size_t i=0; i<ldflags.size(); i++)
{
if(ldflags[i].startsWith("${") || ldflags[i].startsWith("$("))
linkDirs.push_back(ldflags[i]);
else if(ldflags[i].startsWith("-L"))
linkDirs.push_back(ldflags[i].right(ldflags[i].size()-2));
}
out << "LINK_DIRECTORIES(${VISIT_LIBRARY_DIR} ${QT_LIBRARY_DIR} ${GLEW_LIBRARY_DIR} ${VTK_LIBRARY_DIRS} " << ToString(linkDirs) << ")" << endl;
out << endl;
out << "ADD_LIBRARY(I"<<name<<"Operator ${LIBI_SOURCES})" << endl;
out << "TARGET_LINK_LIBRARIES(I"<<name<<"Operator visitcommon)" << endl;
out << "SET(INSTALLTARGETS I"<<name<<"Operator)" << endl;
out << endl;
out << "IF(NOT VISIT_SERVER_COMPONENTS_ONLY AND NOT VISIT_ENGINE_ONLY AND NOT VISIT_DBIO_ONLY)" << endl;
out << " QT_WRAP_CPP(G"<<name<<"Operator LIBG_SOURCES ${LIBG_MOC_SOURCES})" << endl;
out << " ADD_LIBRARY(G"<<name<<"Operator ${LIBG_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(G" << name << "Operator visitcommon "
<< guilibname << " " << ToString(libs) << ToString(glibs)
<< ")" << endl;
out << endl;
if (customvwfiles)
out << " QT_WRAP_CPP(V"<<name<<"Operator LIBV_SOURCES ${LIBV_MOC_SOURCES})" << endl;
out << " ADD_LIBRARY(V"<<name<<"Operator ${LIBV_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(V" << name << "Operator visitcommon "
<< viewerlibname << " " << ToString(libs) << ToString(vlibs)
<< ")" << endl;
out << " SET(INSTALLTARGETS ${INSTALLTARGETS} G"<<name<<"Operator V"<<name<<"Operator)" << endl;
out << endl;
// libS sources
out << " IF(VISIT_PYTHON_SCRIPTING)" << endl;
out << " SET(LIBS_SOURCES" << endl;
out << " " << name<<"ScriptingPluginInfo.C" << endl;
out << " Py"<<atts->name<<".C" << endl;
if (customsfiles)
for (size_t i=0; i<sfiles.size(); i++)
out << " " << sfiles[i] << endl;
else
for (size_t i=0; i<defaultsfiles.size(); i++)
out << " " << defaultsfiles[i] << endl;
out << " ${COMMON_SOURCES}" << endl;
out << " )" << endl;
out << " ADD_LIBRARY(S"<<name<<"Operator ${LIBS_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(S"<<name<<"Operator visitcommon visitpy ${PYTHON_LIBRARY})" << endl;
out << " SET(INSTALLTARGETS ${INSTALLTARGETS} S"<<name<<"Operator)" << endl;
out << " ENDIF(VISIT_PYTHON_SCRIPTING)" << endl;
out << endl;
// Java sources
out << " IF(VISIT_JAVA)" << endl;
out << " ADD_CUSTOM_TARGET(Java"<<name<<" ALL ${CMAKE_Java_COMPILER} ${CMAKE_Java_FLAGS} -d ${VISIT_BINARY_DIR}/java -classpath ${VISIT_BINARY_DIR}/java ";
if(customjfiles)
{
for(size_t i = 0; i < jfiles.size(); ++i)
out << jfiles[i] << " ";
}
out << atts->name<<".java)" << endl;
out << " ADD_DEPENDENCIES(Java"<<name<<" JavaClient)" << endl;
out << " ENDIF(VISIT_JAVA)" << endl;
out << "ENDIF(NOT VISIT_SERVER_COMPONENTS_ONLY AND NOT VISIT_ENGINE_ONLY AND NOT VISIT_DBIO_ONLY)" << endl;
out << endl;
out << "ADD_LIBRARY(E"<<name<<"Operator_ser ${LIBE_SOURCES})" << endl;
out << "TARGET_LINK_LIBRARIES(E"<<name<<"Operator_ser visitcommon avtexpressions_ser avtfilters_ser avtpipeline_ser " << ToString(libs) << ToString(elibsSer) << ")" << endl;
out << "SET(INSTALLTARGETS ${INSTALLTARGETS} E"<<name<<"Operator_ser)" << endl;
if (hasEngineSpecificCode)
out << "ADD_TARGET_DEFINITIONS(E"<<name<<"Operator_ser ENGINE)" << endl;
out << endl;
out << "IF(VISIT_PARALLEL)" << endl;
out << " ADD_PARALLEL_LIBRARY(E"<<name<<"Operator_par ${LIBE_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(E"<<name<<"Operator_par visitcommon avtexpressions_par avtfilters_par avtpipeline_par " << ToString(libs) << ToString(elibsPar) << ")" << endl;
out << " SET(INSTALLTARGETS ${INSTALLTARGETS} E"<<name<<"Operator_par)" << endl;
if (hasEngineSpecificCode)
out << " ADD_TARGET_DEFINITIONS(E"<<name<<"Operator_par ENGINE)" << endl;
out << "ENDIF(VISIT_PARALLEL)" << endl;
out << endl;
out << "VISIT_INSTALL_OPERATOR_PLUGINS(${INSTALLTARGETS})" << endl;
out << "VISIT_PLUGIN_TARGET_RTOD(operators ${INSTALLTARGETS})" << endl;
if (using_dev)
out << "VISIT_PLUGIN_TARGET_FOLDER(operators " << name
<< " ${INSTALLTARGETS})" << endl;
out << endl;
}
void WriteCMake_Database(QTextStream &out)
{
bool useFortran = false;
out << "PROJECT("<<name<<")" << endl;
out << endl;
if (using_dev)
{
out << "INCLUDE(${VISIT_SOURCE_DIR}/CMake/PluginMacros.cmake)" <<endl;
out << endl;
}
out << "SET(COMMON_SOURCES" << endl;
out << ""<<name<<"PluginInfo.C" << endl;
out << ""<<name<<"CommonPluginInfo.C" << endl;
out << ")" << endl;
out << endl;
out << "SET(LIBI_SOURCES " << endl;
out << ""<<name<<"PluginInfo.C" << endl;
out << ")" << endl;
out << endl;
if(!onlyEnginePlugin)
{
out << "SET(LIBM_SOURCES" << endl;
out << ""<<name<<"MDServerPluginInfo.C" << endl;
out << "${COMMON_SOURCES}" << endl;
if (custommfiles)
{
useFortran |= CustomFilesUseFortran(mfiles);
for (size_t i=0; i<mfiles.size(); i++)
out << mfiles[i] << endl;
}
else
for (size_t i=0; i<defaultmfiles.size(); i++)
out << defaultmfiles[i] << endl;
out << ")" << endl;
if (customwmfiles)
{
useFortran |= CustomFilesUseFortran(wmfiles);
out << "IF(WIN32)" << endl;
out << " SET(LIBM_WIN32_SOURCES" << endl;
for (size_t i=0; i<wmfiles.size(); i++)
out << " " << wmfiles[i] << endl;
out << " )" << endl;
for (size_t i=0; i<wmfiles.size(); i++)
{
if(wmfiles[i].endsWith(".c"))
{
out << " SET_SOURCE_FILES_PROPERTIES("
<< wmfiles[i] << endl;
out << " PROPERTIES LANGUAGE CXX)" << endl;
}
}
out << "ENDIF(WIN32)" << endl;
}
out << endl;
}
if(!noEnginePlugin)
{
out << "SET(LIBE_SOURCES" << endl;
out <<name<<"EnginePluginInfo.C" << endl;
out << "${COMMON_SOURCES}" << endl;
if (customefiles)
{
useFortran |= CustomFilesUseFortran(efiles);
for (size_t i=0; i<efiles.size(); i++)
out << efiles[i] << endl;
}
else
for (size_t i=0; i<defaultefiles.size(); i++)
out << defaultefiles[i] << endl;
out << ")" << endl;
if (customwefiles)
{
useFortran |= CustomFilesUseFortran(wefiles);
out << "IF(WIN32)" << endl;
out << " SET(LIBE_WIN32_SOURCES" << endl;
for (size_t i=0; i<wefiles.size(); i++)
out << " " << wefiles[i] << endl;
out << " )" << endl;
for (size_t i=0; i<wefiles.size(); i++)
{
if(wefiles[i].endsWith(".c"))
{
out << " SET_SOURCE_FILES_PROPERTIES("
<< wefiles[i] << endl;
out << " PROPERTIES LANGUAGE CXX)" << endl;
}
}
out << "ENDIF(WIN32)" << endl;
}
out << endl;
}
// take any ${} from the CXXFLAGS to mean a variable that contains
// include directories.
std::vector<QString> extraIncludes;
for (size_t i=0; i<cxxflags.size(); i++)
{
if(cxxflags[i].startsWith("${"))
extraIncludes.push_back(cxxflags[i]);
else if(cxxflags[i].startsWith("$("))
extraIncludes.push_back(ConvertDollarParenthesis(cxxflags[i]));
else if(cxxflags[i].startsWith("-I"))
extraIncludes.push_back(cxxflags[i].right(cxxflags[i].size()-2));
}
out << "INCLUDE_DIRECTORIES(" << endl;
out << "${CMAKE_CURRENT_SOURCE_DIR}" << endl;
if(extraIncludes.size() > 0)
out << ToString(extraIncludes, true) ;
out << "${VISIT_COMMON_INCLUDES}" << endl;
out << VisItIncludeDir() << "/avt/DBAtts/MetaData" << endl;
out << VisItIncludeDir() << "/avt/DBAtts/SIL" << endl;
out << VisItIncludeDir() << "/avt/Database/Database" << endl;
out << VisItIncludeDir() << "/avt/Database/Formats" << endl;
out << VisItIncludeDir() << "/avt/Database/Ghost" << endl;
out << VisItIncludeDir() << "/avt/FileWriter" << endl;
out << VisItIncludeDir() << "/avt/Filters" << endl;
out << VisItIncludeDir() << "/avt/MIR/Base" << endl;
out << VisItIncludeDir() << "/avt/MIR/Tet" << endl;
out << VisItIncludeDir() << "/avt/MIR/Zoo" << endl;
out << VisItIncludeDir() << "/avt/Math" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/AbstractFilters" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/Data" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/Pipeline" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/Sinks" << endl;
out << VisItIncludeDir() << "/avt/Pipeline/Sources" << endl;
out << VisItIncludeDir() << "/avt/VisWindow/VisWindow" << endl;
out << VisItIncludeDir() << "/visit_vtk/full" << endl;
out << VisItIncludeDir() << "/visit_vtk/lightweight" << endl;
out << "${VTK_INCLUDE_DIRS} " << endl;
out << ")" << endl;
out << endl;
// Pass other CXXFLAGS
for (size_t i=0; i<cxxflags.size(); i++)
{
if(!cxxflags[i].startsWith("${") &&
!cxxflags[i].startsWith("$(") &&
!cxxflags[i].startsWith("-I"))
out << "ADD_DEFINITIONS(\"" << cxxflags[i] << "\")" << endl;
}
bool needWindowsDefines = false;
for (size_t i=0; i<libs.size() && !needWindowsDefines; i++)
{
if(libs[i].contains("BOXLIB"))
needWindowsDefines = true;
else if(libs[i].contains("HDF4"))
needWindowsDefines = true;
else if(libs[i].contains("FITS"))
needWindowsDefines = true;
else if(libs[i].contains("NETCDF"))
needWindowsDefines = true;
else if(libs[i].contains("CGNS"))
needWindowsDefines = true;
}
if (needWindowsDefines)
{
out << "IF(WIN32)" << endl;
for (size_t i=0; i<libs.size(); i++)
{
if(libs[i].contains("BOXLIB"))
out << " ADD_DEFINITIONS(-DBL_FORT_USE_UPPERCASE)" << endl;
else if(libs[i].contains("HDF4"))
out << " ADD_DEFINITIONS(-D_HDFDLL_ -D_MFHDFLIB_ -D_HDFLIB_ -DINTEL86)" << endl;
else if(libs[i].contains("FITS"))
out << " ADD_DEFINITIONS(-D_HDF5USEDLL_)" << endl;
else if(libs[i].contains("NETCDF"))
out << " ADD_DEFINITIONS(-DDLL_NETCDF)" << endl;
else if(libs[i].contains("CGNS"))
out << " ADD_DEFINITIONS(-DUSE_DLL)" << endl;
}
out << "ENDIF(WIN32)" << endl;
}
if(useFortran)
{
out << "ENABLE_LANGUAGE(Fortran)" << endl;
}
out << endl;
// Extract extra link directories from LDFLAGS if they have ${},$(),-L
std::vector<QString> linkDirs;
for (size_t i=0; i<ldflags.size(); i++)
{
if(ldflags[i].startsWith("${") || ldflags[i].startsWith("$("))
linkDirs.push_back(ldflags[i]);
else if(ldflags[i].startsWith("-L"))
linkDirs.push_back(ldflags[i].right(ldflags[i].size()-2));
}
out << "LINK_DIRECTORIES(${VISIT_LIBRARY_DIR} ${VTK_LIBRARY_DIRS} " << ToString(linkDirs) << ")" << endl;
out << endl;
out << "ADD_LIBRARY(I"<<name<<"Database ${LIBI_SOURCES})" << endl;
out << "TARGET_LINK_LIBRARIES(I"<<name<<"Database visitcommon)" << endl;
out << "SET(INSTALLTARGETS I"<<name<<"Database)" << endl;
out << endl;
if(!onlyEnginePlugin)
{
out << "IF(NOT VISIT_ENGINE_ONLY AND NOT VISIT_DBIO_ONLY)" << endl;
out << " ADD_LIBRARY(M"<<name<<"Database ${LIBM_SOURCES}";
if (customwmfiles)
out << " ${LIBM_WIN32_SOURCES}";
out << " )" << endl;
out << " TARGET_LINK_LIBRARIES(M"<<name<<"Database visitcommon avtdbatts avtdatabase_ser " << ToString(libs) << ToString(mlibs) << ")" << endl;
out << " ADD_TARGET_DEFINITIONS(M"<<name<<"Database MDSERVER)" << endl;
out << " SET(INSTALLTARGETS ${INSTALLTARGETS} M"<<name<<"Database)" << endl;
out << "ENDIF(NOT VISIT_ENGINE_ONLY AND NOT VISIT_DBIO_ONLY)" << endl;
out << endl;
}
if(!noEnginePlugin)
{
out << "ADD_LIBRARY(E"<<name<<"Database_ser ${LIBE_SOURCES}";
if (customwefiles)
out << " ${LIBE_WIN32_SOURCES}";
out << ")" << endl;
out << "TARGET_LINK_LIBRARIES(E"<<name<<"Database_ser visitcommon avtdatabase_ser avtpipeline_ser " << ToString(libs) << ToString(elibsSer) << ")" << endl;
out << "ADD_TARGET_DEFINITIONS(E"<<name<<"Database_ser ENGINE)" << endl;
out << "SET(INSTALLTARGETS ${INSTALLTARGETS} E"<<name<<"Database_ser)" << endl;
out << endl;
out << "IF(VISIT_PARALLEL)" << endl;
out << " ADD_PARALLEL_LIBRARY(E"<<name<<"Database_par ${LIBE_SOURCES})" << endl;
out << " TARGET_LINK_LIBRARIES(E"<<name<<"Database_par visitcommon avtdatabase_par avtpipeline_par " << ToString(libs) << ToString(elibsPar) << ")" << endl;
out << " ADD_TARGET_DEFINITIONS(E"<<name<<"Database_par ENGINE)" << endl;
out << " SET(INSTALLTARGETS ${INSTALLTARGETS} E"<<name<<"Database_par)" << endl;
out << "ENDIF(VISIT_PARALLEL)" << endl;
out << endl;
}
out << "VISIT_INSTALL_DATABASE_PLUGINS(${INSTALLTARGETS})" << endl;
out << "VISIT_PLUGIN_TARGET_RTOD(databases ${INSTALLTARGETS})" << endl;
if (using_dev)
out << "VISIT_PLUGIN_TARGET_FOLDER(databases " << name
<< " ${INSTALLTARGETS})" << endl;
out << endl;
}
void WriteCMake(QTextStream &out)
{
const char *visithome = getenv("VISITARCHHOME");
if (!visithome && !using_dev)
throw QString().sprintf("Please set the VISITARCHHOME "
"environment variable.\n"
"You may have it set automatically "
"using 'visit -xml2cmake'.");
const char *visitplugdirpub = getenv("VISITPLUGININSTPUB");
if (!visitplugdirpub && installpublic)
throw QString().sprintf("Please set the VISITPLUGININSTPUB "
"environment variable.\n"
"You may have it set automatically "
"using 'visit -xml2cmake'.");
const char *visitplugdirpri = getenv("VISITPLUGININSTPRI");
if (!visitplugdirpri)
{
if ((using_dev && installprivate) || !using_dev)
throw QString().sprintf("Please set the VISITPLUGININSTPRI "
"environment variable.\n"
"You may have it set automatically "
"using 'visit -xml2cmake'.");
}
out << "# DO NOT EDIT THIS FILE! THIS FILE IS AUTOMATICALLY GENERATED "
<< "BY xml2cmake" << endl;
QString qvisithome(visithome);
QString qvisitplugdirpub(visitplugdirpub);
QString qvisitplugdirpri(visitplugdirpri);
#ifdef _WIN32
qvisithome = ToCMakePath(qvisithome);
qvisitplugdirpub = ToCMakePath(qvisitplugdirpub);
qvisitplugdirpri = ToCMakePath(qvisitplugdirpri);
#endif
// If we're not using a development version then we need to always
// include something in the generated output.
if(!using_dev)
{
out << "CMAKE_MINIMUM_REQUIRED(VERSION 2.8.8 FATAL_ERROR)" << endl;
out << "SET(VISIT_INCLUDE_DIR \"" << qvisithome
<< "/include\")" << endl;
out << "SET(VISIT_LIBRARY_DIR \"" << qvisithome
<< "/lib\")" << endl;
#ifdef _WIN32
// There is no 'bin' dir for installed VisIt on Windows
out << "SET(VISIT_BINARY_DIR \"" << qvisithome
<< "\")" << endl;
out << "SET(VISIT_ARCHIVE_DIR \"" << qvisithome
<< "/lib\")" << endl;
#else
out << "SET(VISIT_BINARY_DIR \"" << qvisithome
<< "/bin\")" << endl;
out << "SET(VISIT_ARCHIVE_DIR \"" << qvisithome
<< "/archives\")" << endl;
#endif
if(installpublic)
{
out << "SET(VISIT_PLUGIN_DIR \"" << qvisitplugdirpub
<< "\")" << endl;
}
else // installprivate or default
{
out << "SET(VISIT_PLUGIN_DIR \"" << qvisitplugdirpri
<< "\")" << endl;
}
out << "INCLUDE(\"" << qvisithome
<< "/include/PluginVsInstall.cmake\")" << endl;
out << "INCLUDE(\"" << qvisithome
<< "/include/VisItLibraryDependencies.cmake\")" << endl;
out << endl;
}
else
{
// We're using a development version but we're installing public
// or private.
if(installpublic)
{
out << "SET(VISIT_PLUGIN_DIR " << qvisitplugdirpub << ")" << endl;
}
if(installprivate)
{
out << "SET(VISIT_PLUGIN_DIR " << qvisitplugdirpri << ")" << endl;
}
}
QString guilibname("gui");
QString viewerlibname("viewer");
#ifdef WIN32
if (! using_dev)
{
// when calling from an installed version, cmake doesn't know that
// the gui and viewer lib targets have been renamed to guilib and
// viewer lib (to prevent conflicts with the exe targets), so they
// must be explictily listed by the name of the actual lib created.
guilibname = "guilib";
viewerlibname = "viewerlib";
}
#endif
if(type == "plot")
WriteCMake_Plot(out, guilibname, viewerlibname);
else if(type == "operator")
WriteCMake_Operator(out, guilibname, viewerlibname);
else if(type == "database")
WriteCMake_Database(out);
}
};
// ----------------------------------------------------------------------------
// Override default types
// ----------------------------------------------------------------------------
#define Plugin CMakeGeneratorPlugin
#endif
| [
"brugger@18c085ea-50e0-402c-830e-de6fd14e8384"
] | brugger@18c085ea-50e0-402c-830e-de6fd14e8384 |
c4c75e911435e50ee33a782aab66ce60bf45ece0 | 3610218eb21ada41918131f7bec200587c06c4ab | /imp_cpp/utils/utils.cpp | 4f26c119369e05d6700339c4129e4abbaae3e83e | [] | no_license | zhezhouzz/page_rank | 34fdc380a266de33e99a38f69337ee78f1733a29 | 24fcc1a65a931f92b4efe593d1d5434eb75e2be9 | refs/heads/master | 2020-03-25T05:55:21.526232 | 2018-08-28T02:23:13 | 2018-08-28T02:23:13 | 143,472,875 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | cpp | #include "utils.h"
void print_vector_if_active(const std::vector<bool>& if_active) {
FP_LOG(FP_LEVEL_INFO, "if_active: [");
for(int i = 0 ; i < if_active.size(); i++) {
if(if_active[i]) {
FP_LOG(FP_LEVEL_INFO, "true, ");
} else {
FP_LOG(FP_LEVEL_INFO, "false, ");
}
}
FP_LOG(FP_LEVEL_INFO, "]\n");
return;
} | [
"zorichzorich@gmail.com"
] | zorichzorich@gmail.com |
ffa04168d38ecbce537a54008a1e23c6c4253779 | 09d48fee03e9bb3391ec0f6d7881160b8f758aba | /VMMarkII/VMMarkII/Pointer Wrappers/TraitsPointerWrapper.cpp | 1e6405f6e9e46478f390eacf06c32cf7b0812d5a | [] | no_license | vincent-coetzee/ArgonOne | c0558da9ae4f8279a44c730d7cc482e2acb822a1 | 3c23668bfe1c2c8fd50d7e2691dc1e531ce60cbd | refs/heads/master | 2021-10-07T08:55:05.083694 | 2018-12-04T04:56:07 | 2018-12-04T04:56:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,405 | cpp | //
// TraitsPointerWrapper.cpp
// VMMarkII
//
// Created by Vincent Coetzee on 2018/11/30.
// Copyright © 2018 Vincent Coetzee. All rights reserved.
//
#include "TraitsPointerWrapper.hpp"
#include "CobaltPointers.hpp"
#include "StringPointerWrapper.hpp"
#include "ExtensionBlockPointerWrapper.hpp"
#define kSlotLayoutOffsetMask ((Word)65535)
#define kSlotLayoutFlagsBits ((Word)65535)
#define kSlotLayoutFlagsMask (((Word)65535) << ((Word)16))
#define kSlotLayoutFlagsShift ((Word)16)
long SlotLayout::offset()
{
return((long)offsetAndFlags & kSlotLayoutOffsetMask);
}
long SlotLayout::flags()
{
return((long)((offsetAndFlags & kSlotLayoutFlagsMask) >> kSlotLayoutFlagsShift));
}
void SlotLayout::setFlags(long flags)
{
flags = flags & kSlotLayoutFlagsBits;
offsetAndFlags = offsetAndFlags & ~kSlotLayoutFlagsMask;
offsetAndFlags = offsetAndFlags | (flags << kSlotLayoutFlagsShift);
}
void SlotLayout::setOffset(long offset)
{
offset = offset & kSlotLayoutOffsetMask;
offsetAndFlags = offsetAndFlags & ~kSlotLayoutOffsetMask;
offsetAndFlags = offsetAndFlags | offset;
}
TraitsPointerWrapper::TraitsPointerWrapper(Pointer pointer) : ObjectPointerWrapper(pointer)
{
}
long TraitsPointerWrapper::parentCount()
{
return(wordAtIndexAtPointer(kTraitsParentsCountIndex,this->actualPointer));
}
char const *TraitsPointerWrapper::name()
{
Pointer namePointer = untaggedPointer(pointerAtIndexAtPointer(kTraitsNameIndex,this->actualPointer));
Pointer blockPointer = untaggedPointer(pointerAtIndexAtPointer(kStringExtensionBlockIndex,namePointer));
WordPointer wordPointer = ((WordPointer)blockPointer) + kExtensionBlockBytesIndex;
char const * charPointer = (char*)wordPointer;
return(charPointer);
}
String TraitsPointerWrapper::stringName()
{
return(String(this->name()));
}
long TraitsPointerWrapper::slotLayoutCount()
{
return(wordAtIndexAtPointer(kTraitsSlotLayoutsCountIndex,this->actualPointer));
}
Pointer TraitsPointerWrapper::parentAtIndex(int index)
{
long offset = index + kTraitsFixedSlotCount;
return(pointerAtIndexAtPointer(offset,this->actualPointer));
}
SlotLayout* TraitsPointerWrapper::slotLayoutAtName(Pointer name)
{
return(NULL);
}
SlotLayout* slotLayoutAtIndex(int index)
{
return(NULL);
}
| [
"vincent.coetzee@glucode.com"
] | vincent.coetzee@glucode.com |
6fd21918da2aca3bba0220485cb3c0a4dabc595c | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /base/android/scoped_java_ref.h | 95625678be772344b3a8af7b64eea40ecc847d18 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 18,731 | h | // 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.
#ifndef BASE_ANDROID_SCOPED_JAVA_REF_H_
#define BASE_ANDROID_SCOPED_JAVA_REF_H_
#include <jni.h>
#include <stddef.h>
#include <type_traits>
#include <utility>
#include "base/base_export.h"
#include "base/logging.h"
#include "base/macros.h"
namespace base {
namespace android {
// Creates a new local reference frame, in which at least a given number of
// local references can be created. Note that local references already created
// in previous local frames are still valid in the current local frame.
class BASE_EXPORT ScopedJavaLocalFrame {
public:
explicit ScopedJavaLocalFrame(JNIEnv* env);
ScopedJavaLocalFrame(JNIEnv* env, int capacity);
~ScopedJavaLocalFrame();
private:
// This class is only good for use on the thread it was created on so
// it's safe to cache the non-threadsafe JNIEnv* inside this object.
JNIEnv* env_;
DISALLOW_COPY_AND_ASSIGN(ScopedJavaLocalFrame);
};
// Forward declare the generic java reference template class.
template <typename T>
class JavaRef;
// Template specialization of JavaRef, which acts as the base class for all
// other JavaRef<> template types. This allows you to e.g. pass
// ScopedJavaLocalRef<jstring> into a function taking const JavaRef<jobject>&
template <>
class BASE_EXPORT JavaRef<jobject> {
public:
// Initializes a null reference.
constexpr JavaRef() {}
// Allow nullptr to be converted to JavaRef. This avoids having to declare an
// empty JavaRef just to pass null to a function, and makes C++ "nullptr" and
// Java "null" equivalent.
constexpr JavaRef(std::nullptr_t) {}
// Public to allow destruction of null JavaRef objects.
~JavaRef() {}
// TODO(torne): maybe rename this to get() for consistency with unique_ptr
// once there's fewer unnecessary uses of it in the codebase.
jobject obj() const { return obj_; }
explicit operator bool() const { return obj_ != nullptr; }
// Deprecated. Just use bool conversion.
// TODO(torne): replace usage and remove this.
bool is_null() const { return obj_ == nullptr; }
protected:
// Takes ownership of the |obj| reference passed; requires it to be a local
// reference type.
#if DCHECK_IS_ON()
// Implementation contains a DCHECK; implement out-of-line when DCHECK_IS_ON.
JavaRef(JNIEnv* env, jobject obj);
#else
JavaRef(JNIEnv* env, jobject obj) : obj_(obj) {}
#endif
// Used for move semantics. obj_ must have been released first if non-null.
void steal(JavaRef&& other) {
obj_ = other.obj_;
other.obj_ = nullptr;
}
// The following are implementation detail convenience methods, for
// use by the sub-classes.
JNIEnv* SetNewLocalRef(JNIEnv* env, jobject obj);
void SetNewGlobalRef(JNIEnv* env, jobject obj);
void ResetLocalRef(JNIEnv* env);
void ResetGlobalRef();
jobject ReleaseInternal();
private:
jobject obj_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(JavaRef);
};
// Forward declare the object array reader for the convenience function.
template <typename T>
class JavaObjectArrayReader;
// Generic base class for ScopedJavaLocalRef and ScopedJavaGlobalRef. Useful
// for allowing functions to accept a reference without having to mandate
// whether it is a local or global type.
template <typename T>
class JavaRef : public JavaRef<jobject> {
public:
constexpr JavaRef() {}
constexpr JavaRef(std::nullptr_t) {}
~JavaRef() {}
T obj() const { return static_cast<T>(JavaRef<jobject>::obj()); }
// Get a JavaObjectArrayReader for the array pointed to by this reference.
// Only defined for JavaRef<jobjectArray>.
// You must pass the type of the array elements (usually jobject) as the
// template parameter.
template <typename ElementType,
typename T_ = T,
typename = std::enable_if_t<std::is_same<T_, jobjectArray>::value>>
JavaObjectArrayReader<ElementType> ReadElements() const {
return JavaObjectArrayReader<ElementType>(*this);
}
protected:
JavaRef(JNIEnv* env, T obj) : JavaRef<jobject>(env, obj) {}
private:
DISALLOW_COPY_AND_ASSIGN(JavaRef);
};
// Holds a local reference to a JNI method parameter.
// Method parameters should not be deleted, and so this class exists purely to
// wrap them as a JavaRef<T> in the JNI binding generator. Do not create
// instances manually.
template <typename T>
class JavaParamRef : public JavaRef<T> {
public:
// Assumes that |obj| is a parameter passed to a JNI method from Java.
// Does not assume ownership as parameters should not be deleted.
JavaParamRef(JNIEnv* env, T obj) : JavaRef<T>(env, obj) {}
// Allow nullptr to be converted to JavaParamRef. Some unit tests call JNI
// methods directly from C++ and pass null for objects which are not actually
// used by the implementation (e.g. the caller object); allow this to keep
// working.
JavaParamRef(std::nullptr_t) {}
~JavaParamRef() {}
// TODO(torne): remove this cast once we're using JavaRef consistently.
// http://crbug.com/506850
operator T() const { return JavaRef<T>::obj(); }
private:
DISALLOW_COPY_AND_ASSIGN(JavaParamRef);
};
// Holds a local reference to a Java object. The local reference is scoped
// to the lifetime of this object.
// Instances of this class may hold onto any JNIEnv passed into it until
// destroyed. Therefore, since a JNIEnv is only suitable for use on a single
// thread, objects of this class must be created, used, and destroyed, on a
// single thread.
// Therefore, this class should only be used as a stack-based object and from a
// single thread. If you wish to have the reference outlive the current
// callstack (e.g. as a class member) or you wish to pass it across threads,
// use a ScopedJavaGlobalRef instead.
template <typename T>
class ScopedJavaLocalRef : public JavaRef<T> {
public:
// Take ownership of a bare jobject. This does not create a new reference.
// This should only be used by JNI helper functions, or in cases where code
// must call JNIEnv methods directly.
static ScopedJavaLocalRef Adopt(JNIEnv* env, T obj) {
return ScopedJavaLocalRef(env, obj);
}
constexpr ScopedJavaLocalRef() {}
constexpr ScopedJavaLocalRef(std::nullptr_t) {}
// Copy constructor. This is required in addition to the copy conversion
// constructor below.
ScopedJavaLocalRef(const ScopedJavaLocalRef& other) : env_(other.env_) {
JavaRef<T>::SetNewLocalRef(env_, other.obj());
}
// Copy conversion constructor.
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
ScopedJavaLocalRef(const ScopedJavaLocalRef<U>& other) : env_(other.env_) {
JavaRef<T>::SetNewLocalRef(env_, other.obj());
}
// Move constructor. This is required in addition to the move conversion
// constructor below.
ScopedJavaLocalRef(ScopedJavaLocalRef&& other) : env_(other.env_) {
JavaRef<T>::steal(std::move(other));
}
// Move conversion constructor.
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
ScopedJavaLocalRef(ScopedJavaLocalRef<U>&& other) : env_(other.env_) {
JavaRef<T>::steal(std::move(other));
}
// Constructor for other JavaRef types.
explicit ScopedJavaLocalRef(const JavaRef<T>& other) { Reset(other); }
// Assumes that |obj| is a local reference to a Java object and takes
// ownership of this local reference.
// TODO(torne): make legitimate uses call Adopt() instead, and make this
// private.
ScopedJavaLocalRef(JNIEnv* env, T obj) : JavaRef<T>(env, obj), env_(env) {}
~ScopedJavaLocalRef() { Reset(); }
// Null assignment, for disambiguation.
ScopedJavaLocalRef& operator=(std::nullptr_t) {
Reset();
return *this;
}
// Copy assignment.
ScopedJavaLocalRef& operator=(const ScopedJavaLocalRef& other) {
Reset(other);
return *this;
}
// Copy conversion assignment.
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
ScopedJavaLocalRef& operator=(const ScopedJavaLocalRef<U>& other) {
Reset(other);
return *this;
}
// Move assignment.
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
ScopedJavaLocalRef& operator=(ScopedJavaLocalRef<U>&& other) {
env_ = other.env_;
Reset();
JavaRef<T>::steal(std::move(other));
return *this;
}
// Assignment for other JavaRef types.
ScopedJavaLocalRef& operator=(const JavaRef<T>& other) {
Reset(other);
return *this;
}
void Reset() { JavaRef<T>::ResetLocalRef(env_); }
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
void Reset(const ScopedJavaLocalRef<U>& other) {
// We can copy over env_ here as |other| instance must be from the same
// thread as |this| local ref. (See class comment for multi-threading
// limitations, and alternatives).
Reset(other.env_, other.obj());
}
void Reset(const JavaRef<T>& other) {
// If |env_| was not yet set (is still null) it will be attached to the
// current thread in SetNewLocalRef().
Reset(env_, other.obj());
}
// Creates a new local reference to the Java object, unlike the constructor
// with the same parameters that takes ownership of the existing reference.
// Deprecated. Don't use bare jobjects; use a JavaRef as the input.
// TODO(torne): fix existing usage and remove this.
void Reset(JNIEnv* env, T obj) {
env_ = JavaRef<T>::SetNewLocalRef(env, obj);
}
// Releases the local reference to the caller. The caller *must* delete the
// local reference when it is done with it. Note that calling a Java method
// is *not* a transfer of ownership and Release() should not be used.
T Release() { return static_cast<T>(JavaRef<T>::ReleaseInternal()); }
private:
// This class is only good for use on the thread it was created on so
// it's safe to cache the non-threadsafe JNIEnv* inside this object.
JNIEnv* env_ = nullptr;
// Prevent ScopedJavaLocalRef(JNIEnv*, T obj) from being used to take
// ownership of a JavaParamRef's underlying object - parameters are not
// allowed to be deleted and so should not be owned by ScopedJavaLocalRef.
// TODO(torne): this can be removed once JavaParamRef no longer has an
// implicit conversion back to T.
ScopedJavaLocalRef(JNIEnv* env, const JavaParamRef<T>& other);
// Friend required to get env_ from conversions.
template <typename U>
friend class ScopedJavaLocalRef;
// Avoids JavaObjectArrayReader having to accept and store its own env.
template <typename U>
friend class JavaObjectArrayReader;
};
// Holds a global reference to a Java object. The global reference is scoped
// to the lifetime of this object. This class does not hold onto any JNIEnv*
// passed to it, hence it is safe to use across threads (within the constraints
// imposed by the underlying Java object that it references).
template <typename T>
class ScopedJavaGlobalRef : public JavaRef<T> {
public:
constexpr ScopedJavaGlobalRef() {}
constexpr ScopedJavaGlobalRef(std::nullptr_t) {}
// Copy constructor. This is required in addition to the copy conversion
// constructor below.
ScopedJavaGlobalRef(const ScopedJavaGlobalRef& other) { Reset(other); }
// Copy conversion constructor.
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
ScopedJavaGlobalRef(const ScopedJavaGlobalRef<U>& other) {
Reset(other);
}
// Move constructor. This is required in addition to the move conversion
// constructor below.
ScopedJavaGlobalRef(ScopedJavaGlobalRef&& other) {
JavaRef<T>::steal(std::move(other));
}
// Move conversion constructor.
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
ScopedJavaGlobalRef(ScopedJavaGlobalRef<U>&& other) {
JavaRef<T>::steal(std::move(other));
}
// Conversion constructor for other JavaRef types.
explicit ScopedJavaGlobalRef(const JavaRef<T>& other) { Reset(other); }
// Create a new global reference to the object.
// Deprecated. Don't use bare jobjects; use a JavaRef as the input.
ScopedJavaGlobalRef(JNIEnv* env, T obj) { Reset(env, obj); }
~ScopedJavaGlobalRef() { Reset(); }
// Null assignment, for disambiguation.
ScopedJavaGlobalRef& operator=(std::nullptr_t) {
Reset();
return *this;
}
// Copy assignment.
ScopedJavaGlobalRef& operator=(const ScopedJavaGlobalRef& other) {
Reset(other);
return *this;
}
// Copy conversion assignment.
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
ScopedJavaGlobalRef& operator=(const ScopedJavaGlobalRef<U>& other) {
Reset(other);
return *this;
}
// Move assignment.
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
ScopedJavaGlobalRef& operator=(ScopedJavaGlobalRef<U>&& other) {
Reset();
JavaRef<T>::steal(std::move(other));
return *this;
}
// Assignment for other JavaRef types.
ScopedJavaGlobalRef& operator=(const JavaRef<T>& other) {
Reset(other);
return *this;
}
void Reset() { JavaRef<T>::ResetGlobalRef(); }
template <typename U,
typename = std::enable_if_t<std::is_convertible<U, T>::value>>
void Reset(const ScopedJavaGlobalRef<U>& other) {
Reset(nullptr, other.obj());
}
void Reset(const JavaRef<T>& other) { Reset(nullptr, other.obj()); }
// Deprecated. You can just use Reset(const JavaRef&).
void Reset(JNIEnv* env, const JavaParamRef<T>& other) {
Reset(env, other.obj());
}
// Deprecated. Don't use bare jobjects; use a JavaRef as the input.
void Reset(JNIEnv* env, T obj) { JavaRef<T>::SetNewGlobalRef(env, obj); }
// Releases the global reference to the caller. The caller *must* delete the
// global reference when it is done with it. Note that calling a Java method
// is *not* a transfer of ownership and Release() should not be used.
T Release() { return static_cast<T>(JavaRef<T>::ReleaseInternal()); }
};
// Wrapper for a jobjectArray which supports input iteration, allowing Java
// arrays to be iterated over with a range-based for loop, or used with
// <algorithm> functions that accept input iterators.
//
// The iterator returns each object in the array in turn, wrapped in a
// ScopedJavaLocalRef<T>. T will usually be jobject, but if you know that the
// array contains a more specific type (such as jstring) you can use that
// instead. This does not check the type at runtime!
//
// The wrapper holds a local reference to the array and only queries the size of
// the array once, so must only be used as a stack-based object from the current
// thread.
//
// Note that this does *not* update the contents of the array if you mutate the
// returned ScopedJavaLocalRef.
template <typename T>
class JavaObjectArrayReader {
public:
class iterator {
public:
// We can only be an input iterator, as all richer iterator types must
// implement the multipass guarantee (always returning the same object for
// the same iterator position), which is not practical when returning
// temporary objects.
using iterator_category = std::input_iterator_tag;
using difference_type = ptrdiff_t;
using value_type = ScopedJavaLocalRef<T>;
// It doesn't make sense to return a reference type as the iterator creates
// temporary wrapper objects when dereferenced. Fortunately, it's not
// required that input iterators actually use references, and defining it
// as value_type is valid.
using reference = value_type;
// This exists to make operator-> work as expected: its return value must
// resolve to an actual pointer (otherwise the compiler just keeps calling
// operator-> on the return value until it does), so we need an extra level
// of indirection. This is sometimes called an "arrow proxy" or similar, and
// this version is adapted from base/value_iterators.h.
class pointer {
public:
explicit pointer(const reference& ref) : ref_(ref) {}
pointer(const pointer& ptr) = default;
pointer& operator=(const pointer& ptr) = delete;
reference* operator->() { return &ref_; }
private:
reference ref_;
};
iterator(const iterator&) = default;
~iterator() = default;
iterator& operator=(const iterator&) = default;
bool operator==(const iterator& other) const {
DCHECK(reader_ == other.reader_);
return i_ == other.i_;
}
bool operator!=(const iterator& other) const {
DCHECK(reader_ == other.reader_);
return i_ != other.i_;
}
reference operator*() const {
DCHECK(i_ < reader_->size_);
// JNIEnv functions return unowned local references; take ownership with
// Adopt so that ~ScopedJavaLocalRef will release it automatically later.
return value_type::Adopt(
reader_->array_.env_,
static_cast<T>(reader_->array_.env_->GetObjectArrayElement(
reader_->array_.obj(), i_)));
}
pointer operator->() const { return pointer(operator*()); }
iterator& operator++() {
DCHECK(i_ < reader_->size_);
++i_;
return *this;
}
iterator operator++(int) {
iterator old = *this;
++*this;
return old;
}
private:
iterator(const JavaObjectArrayReader* reader, jsize i)
: reader_(reader), i_(i) {}
const JavaObjectArrayReader* reader_;
jsize i_;
friend JavaObjectArrayReader;
};
JavaObjectArrayReader(const JavaRef<jobjectArray>& array) : array_(array) {
size_ = array_.env_->GetArrayLength(array_.obj());
}
// Copy constructor to allow returning it from JavaRef::ReadElements().
JavaObjectArrayReader(const JavaObjectArrayReader& other) = default;
// Assignment operator for consistency with copy constructor.
JavaObjectArrayReader& operator=(const JavaObjectArrayReader& other) =
default;
// Allow move constructor and assignment since this owns a local ref.
JavaObjectArrayReader(JavaObjectArrayReader&& other) = default;
JavaObjectArrayReader& operator=(JavaObjectArrayReader&& other) = default;
bool empty() const { return size_ == 0; }
jsize size() const { return size_; }
iterator begin() const { return iterator(this, 0); }
iterator end() const { return iterator(this, size_); }
private:
ScopedJavaLocalRef<jobjectArray> array_;
jsize size_;
friend iterator;
};
} // namespace android
} // namespace base
#endif // BASE_ANDROID_SCOPED_JAVA_REF_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
410297b8e64a54f76d06aa1fb10f759442fe1f1a | 4b5a008421fb71f83d948dc9f147e955ab4dc7b1 | /uaMobi/qzxing-master/src/zxing/zxing/datamatrix/decoder/DataMatrixBitMatrixParser.cpp | 756f92970302cd9d3f492de457cec91fad64327a | [
"Apache-2.0"
] | permissive | ston1x/UNARetail | a205becbe3c69b3bd51127b6ec29c3e5abf340d0 | 491ced2068cb89ed24d7d5c23477fd80ca54b8dd | refs/heads/master | 2022-10-11T01:26:44.848735 | 2020-06-09T10:07:00 | 2020-06-09T10:07:00 | 271,839,954 | 1 | 0 | null | 2020-06-12T16:11:36 | 2020-06-12T16:11:36 | null | UTF-8 | C++ | false | false | 11,362 | cpp | /*
* BitMatrixParser.cpp
* zxing
*
* Created by Luiz Silva on 09/02/2010.
* Copyright 2010 ZXing 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 <zxing/datamatrix/decoder/BitMatrixParser.h>
#include <zxing/common/IllegalArgumentException.h>
#include <iostream>
namespace zxing {
namespace datamatrix {
int BitMatrixParser::copyBit(size_t x, size_t y, int versionBits) {
return bitMatrix_->get(int(x), int(y)) ? (versionBits << 1) | 0x1 : versionBits << 1;
}
BitMatrixParser::BitMatrixParser(Ref<BitMatrix> bitMatrix) : bitMatrix_(NULL),
parsedVersion_(NULL),
readBitMatrix_(NULL) {
size_t dimension = bitMatrix->getHeight();
if (dimension < 8 || dimension > 144 || (dimension & 0x01) != 0)
throw ReaderException("Dimension must be even, > 8 < 144");
parsedVersion_ = readVersion(bitMatrix);
bitMatrix_ = extractDataRegion(bitMatrix);
readBitMatrix_ = new BitMatrix(bitMatrix_->getWidth(), bitMatrix_->getHeight());
}
Version* BitMatrixParser::readVersion(Ref<BitMatrix> bitMatrix) {
if (parsedVersion_ != 0) {
return parsedVersion_;
}
int numRows = bitMatrix->getHeight();
int numColumns = bitMatrix->getWidth();
Version* version = parsedVersion_->getVersionForDimensions(numRows, numColumns);
if (version != 0) {
return version;
}
throw ReaderException("Couldn't decode version");
}
ArrayRef<zxing::byte> BitMatrixParser::readCodewords() {
ArrayRef<zxing::byte> result(parsedVersion_->getTotalCodewords());
int resultOffset = 0;
int row = 4;
int column = 0;
int numRows = bitMatrix_->getHeight();
int numColumns = bitMatrix_->getWidth();
bool corner1Read = false;
bool corner2Read = false;
bool corner3Read = false;
bool corner4Read = false;
// Read all of the codewords
do {
// Check the four corner cases
if ((row == numRows) && (column == 0) && !corner1Read) {
result[resultOffset++] = (zxing::byte) readCorner1(numRows, numColumns);
row -= 2;
column += 2;
corner1Read = true;
}
else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x03) != 0) && !corner2Read) {
result[resultOffset++] = (zxing::byte) readCorner2(numRows, numColumns);
row -= 2;
column += 2;
corner2Read = true;
}
else if ((row == numRows + 4) && (column == 2) && ((numColumns & 0x07) == 0) && !corner3Read) {
result[resultOffset++] = (zxing::byte) readCorner3(numRows, numColumns);
row -= 2;
column += 2;
corner3Read = true;
}
else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x07) == 4) && !corner4Read) {
result[resultOffset++] = (zxing::byte) readCorner4(numRows, numColumns);
row -= 2;
column += 2;
corner4Read = true;
}
else {
// Sweep upward diagonally to the right
do {
if ((row < numRows) && (column >= 0) && !readBitMatrix_->get(column, row)) {
result[resultOffset++] = (zxing::byte) readUtah(row, column, numRows, numColumns);
}
row -= 2;
column += 2;
} while ((row >= 0) && (column < numColumns));
row += 1;
column += 3;
// Sweep downward diagonally to the left
do {
if ((row >= 0) && (column < numColumns) && !readBitMatrix_->get(column, row)) {
result[resultOffset++] = (zxing::byte) readUtah(row, column, numRows, numColumns);
}
row += 2;
column -= 2;
} while ((row < numRows) && (column >= 0));
row += 3;
column += 1;
}
} while ((row < numRows) || (column < numColumns));
if (resultOffset != parsedVersion_->getTotalCodewords()) {
throw ReaderException("Did not read all codewords");
}
return result;
}
bool BitMatrixParser::readModule(int row, int column, int numRows, int numColumns) {
// Adjust the row and column indices based on boundary wrapping
if (row < 0) {
row += numRows;
column += 4 - ((numRows + 4) & 0x07);
}
if (column < 0) {
column += numColumns;
row += 4 - ((numColumns + 4) & 0x07);
}
readBitMatrix_->set(column, row);
return bitMatrix_->get(column, row);
}
int BitMatrixParser::readUtah(int row, int column, int numRows, int numColumns) {
int currentByte = 0;
if (readModule(row - 2, column - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row - 2, column - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row - 1, column - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row - 1, column - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row - 1, column, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row, column - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row, column - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row, column, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
}
int BitMatrixParser::readCorner1(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(2, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(3, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
}
int BitMatrixParser::readCorner2(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 3, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 2, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 4, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 3, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
}
int BitMatrixParser::readCorner3(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 3, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 3, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
}
int BitMatrixParser::readCorner4(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 3, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 2, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(2, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(3, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
}
Ref<BitMatrix> BitMatrixParser::extractDataRegion(Ref<BitMatrix> bitMatrix) {
int symbolSizeRows = parsedVersion_->getSymbolSizeRows();
int symbolSizeColumns = parsedVersion_->getSymbolSizeColumns();
if ((int)bitMatrix->getHeight() != symbolSizeRows) {
throw IllegalArgumentException("Dimension of bitMatrix must match the version size");
}
int dataRegionSizeRows = parsedVersion_->getDataRegionSizeRows();
int dataRegionSizeColumns = parsedVersion_->getDataRegionSizeColumns();
int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows;
int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns;
int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;
Ref<BitMatrix> bitMatrixWithoutAlignment(new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow));
for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) {
int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;
for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) {
int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns;
for (int i = 0; i < dataRegionSizeRows; ++i) {
int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i;
int writeRowOffset = dataRegionRowOffset + i;
for (int j = 0; j < dataRegionSizeColumns; ++j) {
int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j;
if (bitMatrix->get(readColumnOffset, readRowOffset)) {
int writeColumnOffset = dataRegionColumnOffset + j;
bitMatrixWithoutAlignment->set(writeColumnOffset, writeRowOffset);
}
}
}
}
}
return bitMatrixWithoutAlignment;
}
}
} | [
"ankeleshbnet@inbox.ru"
] | ankeleshbnet@inbox.ru |
56becc69f2a523d8a6f23a02f40cd611ca9512f4 | 7cc5183d0b36133330b6cd428435e6b64a46e051 | /tensorflow/dtensor/cc/default_parallel_executor.cc | 1df8840dd5ab2592561e89b77493a368d5c7e995 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | shizukanaskytree/tensorflow | cfd0f3c583d362c62111a56eec9da6f9e3e0ddf9 | 7356ce170e2b12961309f0bf163d4f0fcf230b74 | refs/heads/master | 2022-11-19T04:46:43.708649 | 2022-11-12T09:03:54 | 2022-11-12T09:10:12 | 177,024,714 | 2 | 1 | Apache-2.0 | 2021-11-10T19:53:04 | 2019-03-21T21:13:38 | C++ | UTF-8 | C++ | false | false | 965 | cc | /* Copyright 2022 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/dtensor/cc/default_parallel_executor.h"
namespace tensorflow {
namespace dtensor {
std::unique_ptr<ParallelExecutor> CreateDefaultParallelExecutor() {
LOG(ERROR) << __func__ << " not implemented.";
return nullptr;
}
} // namespace dtensor
} // namespace tensorflow
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
1a9576fab0e86291016d5f60db54ee08642c5d89 | 21b4347c5a25f1ddb11404e974c47f71e2f34b32 | /Hazel/src/Hazel/Renderer/Buffer.cpp | c15a1f6db6990ad2d7932ebd099c14b00eef5458 | [] | no_license | nsho77/LetsMakeEngine | 40306ae1c867619f4758c96ad2c50651bacb2e52 | 622fde5bc4436455edf5d1d086b0fb999e72c850 | refs/heads/main | 2023-05-03T11:28:22.318568 | 2021-05-29T09:32:14 | 2021-05-29T09:32:14 | 304,617,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cpp | #include "hzpch.h"
#include "Hazel/Renderer/Buffer.h"
#include "Hazel/Renderer/Renderer.h"
#include "Platform/OpenGL/OpenGLBuffer.h"
namespace Hazel {
Ref<VertexBuffer> VertexBuffer::Create(uint32_t size)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: HZ_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return CreateRef<OpenGLVertexBuffer>(size);
}
HZ_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
Ref<VertexBuffer> VertexBuffer::Create(float* vertices, uint32_t size)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: HZ_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return CreateRef<OpenGLVertexBuffer>(vertices, size);
}
HZ_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
Ref<IndexBuffer> IndexBuffer::Create(uint32_t* indices, uint32_t count)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: HZ_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return CreateRef<OpenGLIndexBuffer>(indices, count);
}
HZ_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
} | [
"nsho77@naver.com"
] | nsho77@naver.com |
672cd4df2e25093062b489f3f9512d9649e2494d | 949eb290baa025da4bf5966a7c7445cc6a7c3982 | /include/FalconEngine/Input/MouseButtonState.h | 0cd2d9fafbf9c460691202781b17745866d124a5 | [
"MIT"
] | permissive | study-game-engines/falcon | 980f0edba5b4f2f5c89c8c7e1033781315c57920 | c4d1fed789218d1994908b8dbbcd6c01961f9ef2 | refs/heads/master | 2023-08-14T17:45:50.070647 | 2021-05-25T07:38:57 | 2021-05-25T07:38:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,437 | h | #pragma once
#include <FalconEngine/Core/Macro.h>
#include <unordered_map>
#include <FalconEngine/Input/MouseButton.h>
namespace FalconEngine
{
enum class MouseButtonPressState
{
Pressed,
Released,
};
enum class MouseButton;
class FALCON_ENGINE_API MouseButtonState final
{
public:
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
MouseButtonState();
explicit MouseButtonState(MouseButton button);
~MouseButtonState() = default;
public:
MouseButton mButton;
bool mButtonChanged = false;
bool mPressed;
double mPressedMoment = 0; // Millisecond time stamp.
bool mDown; // Transition from being released to being pressed.
bool mUp; // Transition from being pressed to being released.
};
#pragma warning(disable: 4251)
class FALCON_ENGINE_API MouseButtonStateMap : public std::unordered_map<MouseButton, MouseButtonState>
{
public:
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
MouseButtonStateMap();
};
#pragma warning(default: 4251)
}
| [
"linwx_xin@hotmail.com"
] | linwx_xin@hotmail.com |
7bf368b500bd37952b1d487a53f25cb9bdfe7b03 | 3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9 | /cpp/E/A/D/B/D/AEADBD.h | 4408de789fbdaf72dc157bdd1421a106553a66e6 | [] | no_license | devsisters/2021-NDC-ICECREAM | 7cd09fa2794cbab1ab4702362a37f6ab62638d9b | ac6548f443a75b86d9e9151ff9c1b17c792b2afd | refs/heads/master | 2023-03-19T06:29:03.216461 | 2021-03-10T02:53:14 | 2021-03-10T02:53:14 | 341,872,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67 | h | #ifndef AEADBD_H
namespace AEADBD {
std::string run();
}
#endif | [
"nakhyun@devsisters.com"
] | nakhyun@devsisters.com |
57ae0942065b2217e35908c8f73d16cb8719b6bd | 95e24c3032b0e6b45b3239e5e23d74e017a3ba11 | /Strings/Check whether a string is a valid shuffle of two strings or not/Check whether a string is a valid shuffle of two strings or not.cpp | 3adcc8e1dc9667ec103f9b69283f5dbd1a22b889 | [] | no_license | keshavjaiswal39/DSA-450-Questions-Love-Babbar-DataSheet | b167470f913b6d4e5e525583ecd1e7d070c335f7 | b6885254063427ddc6e7f7751512caaf788f1a83 | refs/heads/master | 2023-05-29T06:08:52.624084 | 2021-06-20T11:10:24 | 2021-06-20T11:10:24 | 347,831,521 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | cpp | #include<bits/stdc++.h>
#include<string>
using namespace std;
bool validShuffle(string s1,string s2,string res)
{
int l1=s1.size();
int l2=s2.size();
int lr=res.size();
if((l1+l2)!=lr)
{
return false;
}
int i=0,j=0,k=0;
while(k<lr)
{
if(i<l1 and s1[i]==res[k])
{
i++;
}
else if(j<l2 and s2[j]==res[k])
{
j++;
}
else
{
return false;
}
k++;
}
if(i<l1 or j<l2)
{
return false;
}
else
{
return true;
}
}
int main()
{
string s1;
string s2;
string res;
cin>>s1>>s2>>res;
if (validShuffle(s2,s2,res))
{
cout<<"Yes";
}
else
{
cout<<"No";
}
}
| [
"keshav.jaiswal39@gmail.com"
] | keshav.jaiswal39@gmail.com |
da8b9df65b0e529fa0a64271c1f950d29a0f86c7 | bb6ebff7a7f6140903d37905c350954ff6599091 | /third_party/angle/src/libGLESv2/formatutils.cpp | 3aac25efadd073030d37da7a6a3460942dd459d1 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 116,024 | cpp | #include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE 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.
//
// formatutils.cpp: Queries for GL image formats.
#include "common/mathutil.h"
#include "libGLESv2/formatutils.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/imageformats.h"
#include "libGLESv2/renderer/copyimage.h"
namespace gl
{
// ES2 requires that format is equal to internal format at all glTex*Image2D entry points and the implementation
// can decide the true, sized, internal format. The ES2FormatMap determines the internal format for all valid
// format and type combinations.
struct FormatTypeInfo
{
GLenum mInternalFormat;
ColorWriteFunction mColorWriteFunction;
FormatTypeInfo(GLenum internalFormat, ColorWriteFunction writeFunc)
: mInternalFormat(internalFormat), mColorWriteFunction(writeFunc)
{ }
};
typedef std::pair<GLenum, GLenum> FormatTypePair;
typedef std::pair<FormatTypePair, FormatTypeInfo> FormatPair;
typedef std::map<FormatTypePair, FormatTypeInfo> FormatMap;
// A helper function to insert data into the format map with fewer characters.
static inline void InsertFormatMapping(FormatMap *map, GLenum format, GLenum type, GLenum internalFormat, ColorWriteFunction writeFunc)
{
map->insert(FormatPair(FormatTypePair(format, type), FormatTypeInfo(internalFormat, writeFunc)));
}
FormatMap BuildES2FormatMap()
{
FormatMap map;
using namespace rx;
// | Format | Type | Internal format | Color write function |
InsertFormatMapping(&map, GL_ALPHA, GL_UNSIGNED_BYTE, GL_ALPHA8_EXT, WriteColor<A8, GLfloat> );
InsertFormatMapping(&map, GL_ALPHA, GL_FLOAT, GL_ALPHA32F_EXT, WriteColor<A32F, GLfloat> );
InsertFormatMapping(&map, GL_ALPHA, GL_HALF_FLOAT_OES, GL_ALPHA16F_EXT, WriteColor<A16F, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE, GL_UNSIGNED_BYTE, GL_LUMINANCE8_EXT, WriteColor<L8, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE, GL_FLOAT, GL_LUMINANCE32F_EXT, WriteColor<L32F, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE, GL_HALF_FLOAT_OES, GL_LUMINANCE16F_EXT, WriteColor<L16F, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, GL_LUMINANCE8_ALPHA8_EXT, WriteColor<L8A8, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE_ALPHA, GL_FLOAT, GL_LUMINANCE_ALPHA32F_EXT, WriteColor<L32A32F, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE_ALPHA, GL_HALF_FLOAT_OES, GL_LUMINANCE_ALPHA16F_EXT, WriteColor<L16A16F, GLfloat> );
InsertFormatMapping(&map, GL_RED, GL_UNSIGNED_BYTE, GL_R8_EXT, WriteColor<R8, GLfloat> );
InsertFormatMapping(&map, GL_RED, GL_FLOAT, GL_R32F_EXT, WriteColor<R32F, GLfloat> );
InsertFormatMapping(&map, GL_RED, GL_HALF_FLOAT_OES, GL_R16F_EXT, WriteColor<R16F, GLfloat> );
InsertFormatMapping(&map, GL_RG, GL_UNSIGNED_BYTE, GL_RG8_EXT, WriteColor<R8G8, GLfloat> );
InsertFormatMapping(&map, GL_RG, GL_FLOAT, GL_RG32F_EXT, WriteColor<R32G32F, GLfloat> );
InsertFormatMapping(&map, GL_RG, GL_HALF_FLOAT_OES, GL_RG16F_EXT, WriteColor<R16G16F, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8_OES, WriteColor<R8G8B8, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, GL_RGB565, WriteColor<R5G6B5, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_FLOAT, GL_RGB32F_EXT, WriteColor<R32G32B32F, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_HALF_FLOAT_OES, GL_RGB16F_EXT, WriteColor<R16G16B16F, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8_OES, WriteColor<R8G8B8A8, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, GL_RGBA4, WriteColor<R4G4B4A4, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, GL_RGB5_A1, WriteColor<R5G5B5A1, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_FLOAT, GL_RGBA32F_EXT, WriteColor<R32G32B32A32F, GLfloat>);
InsertFormatMapping(&map, GL_RGBA, GL_HALF_FLOAT_OES, GL_RGBA16F_EXT, WriteColor<R16G16B16A16F, GLfloat>);
InsertFormatMapping(&map, GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_BGRA8_EXT, WriteColor<B8G8R8A8, GLfloat> );
InsertFormatMapping(&map, GL_BGRA_EXT, GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT, GL_BGRA4_ANGLEX, WriteColor<B4G4R4A4, GLfloat> );
InsertFormatMapping(&map, GL_BGRA_EXT, GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT, GL_BGR5_A1_ANGLEX, WriteColor<B5G5R5A1, GLfloat> );
InsertFormatMapping(&map, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, NULL );
InsertFormatMapping(&map, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, NULL );
InsertFormatMapping(&map, GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE, GL_UNSIGNED_BYTE, GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE, NULL );
InsertFormatMapping(&map, GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE, GL_UNSIGNED_BYTE, GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE, NULL );
InsertFormatMapping(&map, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_DEPTH_COMPONENT16, NULL );
InsertFormatMapping(&map, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, GL_DEPTH_COMPONENT32_OES, NULL );
InsertFormatMapping(&map, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, GL_DEPTH24_STENCIL8_OES, NULL );
return map;
}
FormatMap BuildES3FormatMap()
{
FormatMap map;
using namespace rx;
// | Format | Type | Internal format | Color write function |
InsertFormatMapping(&map, GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8, WriteColor<R8G8B8A8, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_BYTE, GL_RGBA8_SNORM, WriteColor<R8G8B8A8S, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, GL_RGBA4, WriteColor<R4G4B4A4, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, GL_RGB5_A1, WriteColor<R5G5B5A1, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, GL_RGB10_A2, WriteColor<R10G10B10A2, GLfloat> );
InsertFormatMapping(&map, GL_RGBA, GL_FLOAT, GL_RGBA32F, WriteColor<R32G32B32A32F, GLfloat>);
InsertFormatMapping(&map, GL_RGBA, GL_HALF_FLOAT, GL_RGBA16F, WriteColor<R16G16B16A16F, GLfloat>);
InsertFormatMapping(&map, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, GL_RGBA8UI, WriteColor<R8G8B8A8, GLuint> );
InsertFormatMapping(&map, GL_RGBA_INTEGER, GL_BYTE, GL_RGBA8I, WriteColor<R8G8B8A8S, GLint> );
InsertFormatMapping(&map, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_RGBA16UI, WriteColor<R16G16B16A16, GLuint> );
InsertFormatMapping(&map, GL_RGBA_INTEGER, GL_SHORT, GL_RGBA16I, WriteColor<R16G16B16A16S, GLint> );
InsertFormatMapping(&map, GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_RGBA32UI, WriteColor<R32G32B32A32, GLuint> );
InsertFormatMapping(&map, GL_RGBA_INTEGER, GL_INT, GL_RGBA32I, WriteColor<R32G32B32A32S, GLint> );
InsertFormatMapping(&map, GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, GL_RGB10_A2UI, WriteColor<R10G10B10A2, GLuint> );
InsertFormatMapping(&map, GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8, WriteColor<R8G8B8, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_BYTE, GL_RGB8_SNORM, WriteColor<R8G8B8S, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, GL_RGB565, WriteColor<R5G6B5, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, GL_R11F_G11F_B10F, WriteColor<R11G11B10F, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, GL_RGB9_E5, WriteColor<R9G9B9E5, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_FLOAT, GL_RGB32F, WriteColor<R32G32B32F, GLfloat> );
InsertFormatMapping(&map, GL_RGB, GL_HALF_FLOAT, GL_RGB16F, WriteColor<R16G16B16F, GLfloat> );
InsertFormatMapping(&map, GL_RGB_INTEGER, GL_UNSIGNED_BYTE, GL_RGB8UI, WriteColor<R8G8B8, GLuint> );
InsertFormatMapping(&map, GL_RGB_INTEGER, GL_BYTE, GL_RGB8I, WriteColor<R8G8B8S, GLint> );
InsertFormatMapping(&map, GL_RGB_INTEGER, GL_UNSIGNED_SHORT, GL_RGB16UI, WriteColor<R16G16B16, GLuint> );
InsertFormatMapping(&map, GL_RGB_INTEGER, GL_SHORT, GL_RGB16I, WriteColor<R16G16B16S, GLint> );
InsertFormatMapping(&map, GL_RGB_INTEGER, GL_UNSIGNED_INT, GL_RGB32UI, WriteColor<R32G32B32, GLuint> );
InsertFormatMapping(&map, GL_RGB_INTEGER, GL_INT, GL_RGB32I, WriteColor<R32G32B32S, GLint> );
InsertFormatMapping(&map, GL_RG, GL_UNSIGNED_BYTE, GL_RG8, WriteColor<R8G8, GLfloat> );
InsertFormatMapping(&map, GL_RG, GL_BYTE, GL_RG8_SNORM, WriteColor<R8G8S, GLfloat> );
InsertFormatMapping(&map, GL_RG, GL_FLOAT, GL_RG32F, WriteColor<R32G32F, GLfloat> );
InsertFormatMapping(&map, GL_RG, GL_HALF_FLOAT, GL_RG16F, WriteColor<R16G16F, GLfloat> );
InsertFormatMapping(&map, GL_RG_INTEGER, GL_UNSIGNED_BYTE, GL_RG8UI, WriteColor<R8G8, GLuint> );
InsertFormatMapping(&map, GL_RG_INTEGER, GL_BYTE, GL_RG8I, WriteColor<R8G8S, GLint> );
InsertFormatMapping(&map, GL_RG_INTEGER, GL_UNSIGNED_SHORT, GL_RG16UI, WriteColor<R16G16, GLuint> );
InsertFormatMapping(&map, GL_RG_INTEGER, GL_SHORT, GL_RG16I, WriteColor<R16G16S, GLint> );
InsertFormatMapping(&map, GL_RG_INTEGER, GL_UNSIGNED_INT, GL_RG32UI, WriteColor<R32G32, GLuint> );
InsertFormatMapping(&map, GL_RG_INTEGER, GL_INT, GL_RG32I, WriteColor<R32G32S, GLint> );
InsertFormatMapping(&map, GL_RED, GL_UNSIGNED_BYTE, GL_R8, WriteColor<R8, GLfloat> );
InsertFormatMapping(&map, GL_RED, GL_BYTE, GL_R8_SNORM, WriteColor<R8S, GLfloat> );
InsertFormatMapping(&map, GL_RED, GL_FLOAT, GL_R32F, WriteColor<R32F, GLfloat> );
InsertFormatMapping(&map, GL_RED, GL_HALF_FLOAT, GL_R16F, WriteColor<R16F, GLfloat> );
InsertFormatMapping(&map, GL_RED_INTEGER, GL_UNSIGNED_BYTE, GL_R8UI, WriteColor<R8, GLuint> );
InsertFormatMapping(&map, GL_RED_INTEGER, GL_BYTE, GL_R8I, WriteColor<R8S, GLint> );
InsertFormatMapping(&map, GL_RED_INTEGER, GL_UNSIGNED_SHORT, GL_R16UI, WriteColor<R16, GLuint> );
InsertFormatMapping(&map, GL_RED_INTEGER, GL_SHORT, GL_R16I, WriteColor<R16S, GLint> );
InsertFormatMapping(&map, GL_RED_INTEGER, GL_UNSIGNED_INT, GL_R32UI, WriteColor<R32, GLuint> );
InsertFormatMapping(&map, GL_RED_INTEGER, GL_INT, GL_R32I, WriteColor<R32S, GLint> );
InsertFormatMapping(&map, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, GL_LUMINANCE8_ALPHA8_EXT, WriteColor<L8A8, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE, GL_UNSIGNED_BYTE, GL_LUMINANCE8_EXT, WriteColor<L8, GLfloat> );
InsertFormatMapping(&map, GL_ALPHA, GL_UNSIGNED_BYTE, GL_ALPHA8_EXT, WriteColor<A8, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE_ALPHA, GL_FLOAT, GL_LUMINANCE_ALPHA32F_EXT, WriteColor<L32A32F, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE, GL_FLOAT, GL_LUMINANCE32F_EXT, WriteColor<L32F, GLfloat> );
InsertFormatMapping(&map, GL_ALPHA, GL_FLOAT, GL_ALPHA32F_EXT, WriteColor<A32F, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE_ALPHA, GL_HALF_FLOAT, GL_LUMINANCE_ALPHA16F_EXT, WriteColor<L16A16F, GLfloat> );
InsertFormatMapping(&map, GL_LUMINANCE, GL_HALF_FLOAT, GL_LUMINANCE16F_EXT, WriteColor<L16F, GLfloat> );
InsertFormatMapping(&map, GL_ALPHA, GL_HALF_FLOAT, GL_ALPHA16F_EXT, WriteColor<A16F, GLfloat> );
InsertFormatMapping(&map, GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_BGRA8_EXT, WriteColor<B8G8R8A8, GLfloat> );
InsertFormatMapping(&map, GL_BGRA_EXT, GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT, GL_BGRA4_ANGLEX, WriteColor<B4G4R4A4, GLfloat> );
InsertFormatMapping(&map, GL_BGRA_EXT, GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT, GL_BGR5_A1_ANGLEX, WriteColor<B5G5R5A1, GLfloat> );
InsertFormatMapping(&map, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_DEPTH_COMPONENT16, NULL );
InsertFormatMapping(&map, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, GL_DEPTH_COMPONENT24, NULL );
InsertFormatMapping(&map, GL_DEPTH_COMPONENT, GL_FLOAT, GL_DEPTH_COMPONENT32F, NULL );
InsertFormatMapping(&map, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, GL_DEPTH24_STENCIL8, NULL );
InsertFormatMapping(&map, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, GL_DEPTH32F_STENCIL8, NULL );
return map;
}
static const FormatMap &GetFormatMap(GLuint clientVersion)
{
if (clientVersion == 2)
{
static const FormatMap formats = BuildES2FormatMap();
return formats;
}
else if (clientVersion == 3)
{
static const FormatMap formats = BuildES3FormatMap();
return formats;
}
else
{
UNREACHABLE();
static FormatMap emptyMap;
return emptyMap;
}
}
struct FormatInfo
{
GLenum mInternalformat;
GLenum mFormat;
GLenum mType;
FormatInfo(GLenum internalformat, GLenum format, GLenum type)
: mInternalformat(internalformat), mFormat(format), mType(type) { }
bool operator<(const FormatInfo& other) const
{
return memcmp(this, &other, sizeof(FormatInfo)) < 0;
}
};
// ES3 has a specific set of permutations of internal formats, formats and types which are acceptable.
typedef std::set<FormatInfo> ES3FormatSet;
ES3FormatSet BuildES3FormatSet()
{
ES3FormatSet set;
// Format combinations from ES 3.0.1 spec, table 3.2
// | Internal format | Format | Type |
// | | | |
set.insert(FormatInfo(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGBA4, GL_RGBA, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGBA8_SNORM, GL_RGBA, GL_BYTE ));
set.insert(FormatInfo(GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 ));
set.insert(FormatInfo(GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV ));
set.insert(FormatInfo(GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV ));
set.insert(FormatInfo(GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1 ));
set.insert(FormatInfo(GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_RGBA32F, GL_RGBA, GL_FLOAT ));
set.insert(FormatInfo(GL_RGBA16F, GL_RGBA, GL_FLOAT ));
set.insert(FormatInfo(GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE ));
set.insert(FormatInfo(GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT ));
set.insert(FormatInfo(GL_RGBA16I, GL_RGBA_INTEGER, GL_SHORT ));
set.insert(FormatInfo(GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT ));
set.insert(FormatInfo(GL_RGBA32I, GL_RGBA_INTEGER, GL_INT ));
set.insert(FormatInfo(GL_RGB10_A2UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV ));
set.insert(FormatInfo(GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGB565, GL_RGB, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGB8_SNORM, GL_RGB, GL_BYTE ));
set.insert(FormatInfo(GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5 ));
set.insert(FormatInfo(GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV ));
set.insert(FormatInfo(GL_RGB9_E5, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV ));
set.insert(FormatInfo(GL_RGB16F, GL_RGB, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_R11F_G11F_B10F, GL_RGB, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_RGB9_E5, GL_RGB, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_RGB32F, GL_RGB, GL_FLOAT ));
set.insert(FormatInfo(GL_RGB16F, GL_RGB, GL_FLOAT ));
set.insert(FormatInfo(GL_R11F_G11F_B10F, GL_RGB, GL_FLOAT ));
set.insert(FormatInfo(GL_RGB9_E5, GL_RGB, GL_FLOAT ));
set.insert(FormatInfo(GL_RGB8UI, GL_RGB_INTEGER, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGB8I, GL_RGB_INTEGER, GL_BYTE ));
set.insert(FormatInfo(GL_RGB16UI, GL_RGB_INTEGER, GL_UNSIGNED_SHORT ));
set.insert(FormatInfo(GL_RGB16I, GL_RGB_INTEGER, GL_SHORT ));
set.insert(FormatInfo(GL_RGB32UI, GL_RGB_INTEGER, GL_UNSIGNED_INT ));
set.insert(FormatInfo(GL_RGB32I, GL_RGB_INTEGER, GL_INT ));
set.insert(FormatInfo(GL_RG8, GL_RG, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RG8_SNORM, GL_RG, GL_BYTE ));
set.insert(FormatInfo(GL_RG16F, GL_RG, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_RG32F, GL_RG, GL_FLOAT ));
set.insert(FormatInfo(GL_RG16F, GL_RG, GL_FLOAT ));
set.insert(FormatInfo(GL_RG8UI, GL_RG_INTEGER, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RG8I, GL_RG_INTEGER, GL_BYTE ));
set.insert(FormatInfo(GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT ));
set.insert(FormatInfo(GL_RG16I, GL_RG_INTEGER, GL_SHORT ));
set.insert(FormatInfo(GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT ));
set.insert(FormatInfo(GL_RG32I, GL_RG_INTEGER, GL_INT ));
set.insert(FormatInfo(GL_R8, GL_RED, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_R8_SNORM, GL_RED, GL_BYTE ));
set.insert(FormatInfo(GL_R16F, GL_RED, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_R32F, GL_RED, GL_FLOAT ));
set.insert(FormatInfo(GL_R16F, GL_RED, GL_FLOAT ));
set.insert(FormatInfo(GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_R8I, GL_RED_INTEGER, GL_BYTE ));
set.insert(FormatInfo(GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT ));
set.insert(FormatInfo(GL_R16I, GL_RED_INTEGER, GL_SHORT ));
set.insert(FormatInfo(GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT ));
set.insert(FormatInfo(GL_R32I, GL_RED_INTEGER, GL_INT ));
// Unsized formats
set.insert(FormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 ));
set.insert(FormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1 ));
set.insert(FormatInfo(GL_RGB, GL_RGB, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5 ));
set.insert(FormatInfo(GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE ));
// Depth stencil formats
set.insert(FormatInfo(GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT ));
set.insert(FormatInfo(GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT ));
set.insert(FormatInfo(GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT ));
set.insert(FormatInfo(GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT ));
set.insert(FormatInfo(GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8 ));
set.insert(FormatInfo(GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV));
// From GL_OES_texture_float
set.insert(FormatInfo(GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_FLOAT ));
set.insert(FormatInfo(GL_LUMINANCE, GL_LUMINANCE, GL_FLOAT ));
set.insert(FormatInfo(GL_ALPHA, GL_ALPHA, GL_FLOAT ));
// From GL_OES_texture_half_float
set.insert(FormatInfo(GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_LUMINANCE, GL_LUMINANCE, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_ALPHA, GL_ALPHA, GL_HALF_FLOAT ));
// From GL_EXT_texture_format_BGRA8888
set.insert(FormatInfo(GL_BGRA_EXT, GL_BGRA_EXT, GL_UNSIGNED_BYTE ));
// From GL_EXT_texture_storage
// | Internal format | Format | Type |
// | | | |
set.insert(FormatInfo(GL_ALPHA8_EXT, GL_ALPHA, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_LUMINANCE8_EXT, GL_LUMINANCE, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_LUMINANCE8_ALPHA8_EXT, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_ALPHA32F_EXT, GL_ALPHA, GL_FLOAT ));
set.insert(FormatInfo(GL_LUMINANCE32F_EXT, GL_LUMINANCE, GL_FLOAT ));
set.insert(FormatInfo(GL_LUMINANCE_ALPHA32F_EXT, GL_LUMINANCE_ALPHA, GL_FLOAT ));
set.insert(FormatInfo(GL_ALPHA16F_EXT, GL_ALPHA, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_LUMINANCE16F_EXT, GL_LUMINANCE, GL_HALF_FLOAT ));
set.insert(FormatInfo(GL_LUMINANCE_ALPHA16F_EXT, GL_LUMINANCE_ALPHA, GL_HALF_FLOAT ));
// From GL_EXT_texture_storage and GL_EXT_texture_format_BGRA8888
set.insert(FormatInfo(GL_BGRA8_EXT, GL_BGRA_EXT, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_BGRA4_ANGLEX, GL_BGRA_EXT, GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT));
set.insert(FormatInfo(GL_BGRA4_ANGLEX, GL_BGRA_EXT, GL_UNSIGNED_BYTE ));
set.insert(FormatInfo(GL_BGR5_A1_ANGLEX, GL_BGRA_EXT, GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT));
set.insert(FormatInfo(GL_BGR5_A1_ANGLEX, GL_BGRA_EXT, GL_UNSIGNED_BYTE ));
// From GL_ANGLE_depth_texture
set.insert(FormatInfo(GL_DEPTH_COMPONENT32_OES, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT_24_8_OES ));
// Compressed formats
// From ES 3.0.1 spec, table 3.16
// | Internal format | Format | Type |
// | | | |
set.insert(FormatInfo(GL_COMPRESSED_R11_EAC, GL_COMPRESSED_R11_EAC, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_R11_EAC, GL_COMPRESSED_R11_EAC, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_SIGNED_R11_EAC, GL_COMPRESSED_SIGNED_R11_EAC, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_RG11_EAC, GL_COMPRESSED_RG11_EAC, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_SIGNED_RG11_EAC, GL_COMPRESSED_SIGNED_RG11_EAC, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_RGB8_ETC2, GL_COMPRESSED_RGB8_ETC2, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_SRGB8_ETC2, GL_COMPRESSED_SRGB8_ETC2, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_RGBA8_ETC2_EAC, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, GL_UNSIGNED_BYTE));
// From GL_EXT_texture_compression_dxt1
set.insert(FormatInfo(GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE));
set.insert(FormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE));
// From GL_ANGLE_texture_compression_dxt3
set.insert(FormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE, GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE, GL_UNSIGNED_BYTE));
// From GL_ANGLE_texture_compression_dxt5
set.insert(FormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE, GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE, GL_UNSIGNED_BYTE));
return set;
}
static const ES3FormatSet &GetES3FormatSet()
{
static const ES3FormatSet es3FormatSet = BuildES3FormatSet();
return es3FormatSet;
}
// Map of sizes of input types
struct TypeInfo
{
GLuint mTypeBytes;
bool mSpecialInterpretation;
TypeInfo()
: mTypeBytes(0), mSpecialInterpretation(false) { }
TypeInfo(GLuint typeBytes, bool specialInterpretation)
: mTypeBytes(typeBytes), mSpecialInterpretation(specialInterpretation) { }
bool operator<(const TypeInfo& other) const
{
return memcmp(this, &other, sizeof(TypeInfo)) < 0;
}
};
typedef std::pair<GLenum, TypeInfo> TypeInfoPair;
typedef std::map<GLenum, TypeInfo> TypeInfoMap;
static TypeInfoMap BuildTypeInfoMap()
{
TypeInfoMap map;
map.insert(TypeInfoPair(GL_UNSIGNED_BYTE, TypeInfo( 1, false)));
map.insert(TypeInfoPair(GL_BYTE, TypeInfo( 1, false)));
map.insert(TypeInfoPair(GL_UNSIGNED_SHORT, TypeInfo( 2, false)));
map.insert(TypeInfoPair(GL_SHORT, TypeInfo( 2, false)));
map.insert(TypeInfoPair(GL_UNSIGNED_INT, TypeInfo( 4, false)));
map.insert(TypeInfoPair(GL_INT, TypeInfo( 4, false)));
map.insert(TypeInfoPair(GL_HALF_FLOAT, TypeInfo( 2, false)));
map.insert(TypeInfoPair(GL_HALF_FLOAT_OES, TypeInfo( 2, false)));
map.insert(TypeInfoPair(GL_FLOAT, TypeInfo( 4, false)));
map.insert(TypeInfoPair(GL_UNSIGNED_SHORT_5_6_5, TypeInfo( 2, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_SHORT_4_4_4_4, TypeInfo( 2, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_SHORT_5_5_5_1, TypeInfo( 2, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT, TypeInfo( 2, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT, TypeInfo( 2, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_INT_2_10_10_10_REV, TypeInfo( 4, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_INT_24_8, TypeInfo( 4, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_INT_10F_11F_11F_REV, TypeInfo( 4, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_INT_5_9_9_9_REV, TypeInfo( 4, true )));
map.insert(TypeInfoPair(GL_UNSIGNED_INT_24_8_OES, TypeInfo( 4, true )));
map.insert(TypeInfoPair(GL_FLOAT_32_UNSIGNED_INT_24_8_REV, TypeInfo( 8, true )));
return map;
}
static bool GetTypeInfo(GLenum type, TypeInfo *outTypeInfo)
{
static const TypeInfoMap infoMap = BuildTypeInfoMap();
TypeInfoMap::const_iterator iter = infoMap.find(type);
if (iter != infoMap.end())
{
if (outTypeInfo)
{
*outTypeInfo = iter->second;
}
return true;
}
else
{
return false;
}
}
// Information about internal formats
typedef bool ((Context::*ContextSupportCheckMemberFunction)(void) const);
typedef bool (*ContextSupportCheckFunction)(const Context *context);
typedef bool ((rx::Renderer::*RendererSupportCheckMemberFunction)(void) const);
typedef bool (*ContextRendererSupportCheckFunction)(const Context *context, const rx::Renderer *renderer);
template <ContextSupportCheckMemberFunction func>
bool CheckSupport(const Context *context)
{
return (context->*func)();
}
template <ContextSupportCheckMemberFunction contextFunc, RendererSupportCheckMemberFunction rendererFunc>
bool CheckSupport(const Context *context, const rx::Renderer *renderer)
{
if (context)
{
return (context->*contextFunc)();
}
else if (renderer)
{
return (renderer->*rendererFunc)();
}
else
{
UNREACHABLE();
return false;
}
}
template <typename objectType>
bool AlwaysSupported(const objectType*)
{
return true;
}
template <typename objectTypeA, typename objectTypeB>
bool AlwaysSupported(const objectTypeA*, const objectTypeB*)
{
return true;
}
template <typename objectType>
bool NeverSupported(const objectType*)
{
return false;
}
template <typename objectTypeA, typename objectTypeB>
bool NeverSupported(const objectTypeA *, const objectTypeB *)
{
return false;
}
template <typename objectType>
bool UnimplementedSupport(const objectType*)
{
UNIMPLEMENTED();
return false;
}
template <typename objectTypeA, typename objectTypeB>
bool UnimplementedSupport(const objectTypeA*, const objectTypeB*)
{
UNIMPLEMENTED();
return false;
}
struct InternalFormatInfo
{
GLuint mRedBits;
GLuint mGreenBits;
GLuint mBlueBits;
GLuint mLuminanceBits;
GLuint mAlphaBits;
GLuint mSharedBits;
GLuint mDepthBits;
GLuint mStencilBits;
GLuint mPixelBits;
GLuint mComponentCount;
GLuint mCompressedBlockWidth;
GLuint mCompressedBlockHeight;
GLenum mFormat;
GLenum mType;
GLenum mComponentType;
GLenum mColorEncoding;
bool mIsCompressed;
ContextRendererSupportCheckFunction mIsColorRenderable;
ContextRendererSupportCheckFunction mIsDepthRenderable;
ContextRendererSupportCheckFunction mIsStencilRenderable;
ContextRendererSupportCheckFunction mIsTextureFilterable;
ContextSupportCheckFunction mSupportFunction;
InternalFormatInfo() : mRedBits(0), mGreenBits(0), mBlueBits(0), mLuminanceBits(0), mAlphaBits(0), mSharedBits(0), mDepthBits(0), mStencilBits(0),
mPixelBits(0), mComponentCount(0), mCompressedBlockWidth(0), mCompressedBlockHeight(0), mFormat(GL_NONE), mType(GL_NONE),
mComponentType(GL_NONE), mColorEncoding(GL_NONE), mIsCompressed(false), mIsColorRenderable(NeverSupported),
mIsDepthRenderable(NeverSupported), mIsStencilRenderable(NeverSupported), mIsTextureFilterable(NeverSupported),
mSupportFunction(NeverSupported)
{
}
static InternalFormatInfo UnsizedFormat(GLenum format, ContextSupportCheckFunction supportFunction)
{
InternalFormatInfo formatInfo;
formatInfo.mFormat = format;
formatInfo.mSupportFunction = supportFunction;
if (format == GL_RGB || format == GL_RGBA)
formatInfo.mIsColorRenderable = AlwaysSupported;
return formatInfo;
}
static InternalFormatInfo RGBAFormat(GLuint red, GLuint green, GLuint blue, GLuint alpha, GLuint shared,
GLenum format, GLenum type, GLenum componentType, bool srgb,
ContextRendererSupportCheckFunction colorRenderable,
ContextRendererSupportCheckFunction textureFilterable,
ContextSupportCheckFunction supportFunction)
{
InternalFormatInfo formatInfo;
formatInfo.mRedBits = red;
formatInfo.mGreenBits = green;
formatInfo.mBlueBits = blue;
formatInfo.mAlphaBits = alpha;
formatInfo.mSharedBits = shared;
formatInfo.mPixelBits = red + green + blue + alpha + shared;
formatInfo.mComponentCount = ((red > 0) ? 1 : 0) + ((green > 0) ? 1 : 0) + ((blue > 0) ? 1 : 0) + ((alpha > 0) ? 1 : 0);
formatInfo.mFormat = format;
formatInfo.mType = type;
formatInfo.mComponentType = componentType;
formatInfo.mColorEncoding = (srgb ? GL_SRGB : GL_LINEAR);
formatInfo.mIsColorRenderable = colorRenderable;
formatInfo.mIsTextureFilterable = textureFilterable;
formatInfo.mSupportFunction = supportFunction;
return formatInfo;
}
static InternalFormatInfo LUMAFormat(GLuint luminance, GLuint alpha, GLenum format, GLenum type, GLenum componentType,
ContextSupportCheckFunction supportFunction)
{
InternalFormatInfo formatInfo;
formatInfo.mLuminanceBits = luminance;
formatInfo.mAlphaBits = alpha;
formatInfo.mPixelBits = luminance + alpha;
formatInfo.mComponentCount = ((luminance > 0) ? 1 : 0) + ((alpha > 0) ? 1 : 0);
formatInfo.mFormat = format;
formatInfo.mType = type;
formatInfo.mComponentType = componentType;
formatInfo.mColorEncoding = GL_LINEAR;
formatInfo.mIsTextureFilterable = AlwaysSupported;
formatInfo.mSupportFunction = supportFunction;
return formatInfo;
}
static InternalFormatInfo DepthStencilFormat(GLuint depthBits, GLuint stencilBits, GLuint unusedBits, GLenum format,
GLenum type, GLenum componentType,
ContextRendererSupportCheckFunction depthRenderable,
ContextRendererSupportCheckFunction stencilRenderable,
ContextSupportCheckFunction supportFunction)
{
InternalFormatInfo formatInfo;
formatInfo.mDepthBits = depthBits;
formatInfo.mStencilBits = stencilBits;
formatInfo.mPixelBits = depthBits + stencilBits + unusedBits;
formatInfo.mComponentCount = ((depthBits > 0) ? 1 : 0) + ((stencilBits > 0) ? 1 : 0);
formatInfo.mFormat = format;
formatInfo.mType = type;
formatInfo.mComponentType = componentType;
formatInfo.mColorEncoding = GL_LINEAR;
formatInfo.mIsDepthRenderable = depthRenderable;
formatInfo.mIsStencilRenderable = stencilRenderable;
formatInfo.mIsTextureFilterable = AlwaysSupported;
formatInfo.mSupportFunction = supportFunction;
return formatInfo;
}
static InternalFormatInfo CompressedFormat(GLuint compressedBlockWidth, GLuint compressedBlockHeight, GLuint compressedBlockSize,
GLuint componentCount, GLenum format, GLenum type, bool srgb,
ContextSupportCheckFunction supportFunction)
{
InternalFormatInfo formatInfo;
formatInfo.mCompressedBlockWidth = compressedBlockWidth;
formatInfo.mCompressedBlockHeight = compressedBlockHeight;
formatInfo.mPixelBits = compressedBlockSize;
formatInfo.mComponentCount = componentCount;
formatInfo.mFormat = format;
formatInfo.mType = type;
formatInfo.mComponentType = GL_UNSIGNED_NORMALIZED;
formatInfo.mColorEncoding = (srgb ? GL_SRGB : GL_LINEAR);
formatInfo.mIsCompressed = true;
formatInfo.mIsTextureFilterable = AlwaysSupported;
formatInfo.mSupportFunction = supportFunction;
return formatInfo;
}
};
typedef std::pair<GLenum, InternalFormatInfo> InternalFormatInfoPair;
typedef std::map<GLenum, InternalFormatInfo> InternalFormatInfoMap;
static InternalFormatInfoMap BuildES3InternalFormatInfoMap()
{
InternalFormatInfoMap map;
// From ES 3.0.1 spec, table 3.12
map.insert(InternalFormatInfoPair(GL_NONE, InternalFormatInfo()));
// | Internal format | | R | G | B | A |S | Format | Type | Component type | SRGB | Color | Texture | Supported |
// | | | | | | | | | | | | renderable | filterable | |
map.insert(InternalFormatInfoPair(GL_R8, InternalFormatInfo::RGBAFormat( 8, 0, 0, 0, 0, GL_RED, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R8_SNORM, InternalFormatInfo::RGBAFormat( 8, 0, 0, 0, 0, GL_RED, GL_BYTE, GL_SIGNED_NORMALIZED, false, NeverSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG8, InternalFormatInfo::RGBAFormat( 8, 8, 0, 0, 0, GL_RG, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG8_SNORM, InternalFormatInfo::RGBAFormat( 8, 8, 0, 0, 0, GL_RG, GL_BYTE, GL_SIGNED_NORMALIZED, false, NeverSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB8, InternalFormatInfo::RGBAFormat( 8, 8, 8, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB8_SNORM, InternalFormatInfo::RGBAFormat( 8, 8, 8, 0, 0, GL_RGB, GL_BYTE, GL_SIGNED_NORMALIZED, false, NeverSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB565, InternalFormatInfo::RGBAFormat( 5, 6, 5, 0, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA4, InternalFormatInfo::RGBAFormat( 4, 4, 4, 4, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB5_A1, InternalFormatInfo::RGBAFormat( 5, 5, 5, 1, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA8, InternalFormatInfo::RGBAFormat( 8, 8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA8_SNORM, InternalFormatInfo::RGBAFormat( 8, 8, 8, 8, 0, GL_RGBA, GL_BYTE, GL_SIGNED_NORMALIZED, false, NeverSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB10_A2, InternalFormatInfo::RGBAFormat(10, 10, 10, 2, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB10_A2UI, InternalFormatInfo::RGBAFormat(10, 10, 10, 2, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_SRGB8, InternalFormatInfo::RGBAFormat( 8, 8, 8, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, true, NeverSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_SRGB8_ALPHA8, InternalFormatInfo::RGBAFormat( 8, 8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, true, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R11F_G11F_B10F, InternalFormatInfo::RGBAFormat(11, 11, 10, 0, 0, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, GL_FLOAT, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB9_E5, InternalFormatInfo::RGBAFormat( 9, 9, 9, 0, 5, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, GL_FLOAT, false, NeverSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R8I, InternalFormatInfo::RGBAFormat( 8, 0, 0, 0, 0, GL_RED_INTEGER, GL_BYTE, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R8UI, InternalFormatInfo::RGBAFormat( 8, 0, 0, 0, 0, GL_RED_INTEGER, GL_UNSIGNED_BYTE, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R16I, InternalFormatInfo::RGBAFormat(16, 0, 0, 0, 0, GL_RED_INTEGER, GL_SHORT, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R16UI, InternalFormatInfo::RGBAFormat(16, 0, 0, 0, 0, GL_RED_INTEGER, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R32I, InternalFormatInfo::RGBAFormat(32, 0, 0, 0, 0, GL_RED_INTEGER, GL_INT, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R32UI, InternalFormatInfo::RGBAFormat(32, 0, 0, 0, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG8I, InternalFormatInfo::RGBAFormat( 8, 8, 0, 0, 0, GL_RG_INTEGER, GL_BYTE, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG8UI, InternalFormatInfo::RGBAFormat( 8, 8, 0, 0, 0, GL_RG_INTEGER, GL_UNSIGNED_BYTE, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG16I, InternalFormatInfo::RGBAFormat(16, 16, 0, 0, 0, GL_RG_INTEGER, GL_SHORT, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG16UI, InternalFormatInfo::RGBAFormat(16, 16, 0, 0, 0, GL_RG_INTEGER, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG32I, InternalFormatInfo::RGBAFormat(32, 32, 0, 0, 0, GL_RG_INTEGER, GL_INT, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG32UI, InternalFormatInfo::RGBAFormat(32, 32, 0, 0, 0, GL_RG_INTEGER, GL_UNSIGNED_INT, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB8I, InternalFormatInfo::RGBAFormat( 8, 8, 8, 0, 0, GL_RGB_INTEGER, GL_BYTE, GL_INT, false, NeverSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB8UI, InternalFormatInfo::RGBAFormat( 8, 8, 8, 0, 0, GL_RGB_INTEGER, GL_UNSIGNED_BYTE, GL_UNSIGNED_INT, false, NeverSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB16I, InternalFormatInfo::RGBAFormat(16, 16, 16, 0, 0, GL_RGB_INTEGER, GL_SHORT, GL_INT, false, NeverSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB16UI, InternalFormatInfo::RGBAFormat(16, 16, 16, 0, 0, GL_RGB_INTEGER, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT, false, NeverSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB32I, InternalFormatInfo::RGBAFormat(32, 32, 32, 0, 0, GL_RGB_INTEGER, GL_INT, GL_INT, false, NeverSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB32UI, InternalFormatInfo::RGBAFormat(32, 32, 32, 0, 0, GL_RGB_INTEGER, GL_UNSIGNED_INT, GL_UNSIGNED_INT, false, NeverSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA8I, InternalFormatInfo::RGBAFormat( 8, 8, 8, 8, 0, GL_RGBA_INTEGER, GL_BYTE, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA8UI, InternalFormatInfo::RGBAFormat( 8, 8, 8, 8, 0, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA16I, InternalFormatInfo::RGBAFormat(16, 16, 16, 16, 0, GL_RGBA_INTEGER, GL_SHORT, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA16UI, InternalFormatInfo::RGBAFormat(16, 16, 16, 16, 0, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA32I, InternalFormatInfo::RGBAFormat(32, 32, 32, 32, 0, GL_RGBA_INTEGER, GL_INT, GL_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA32UI, InternalFormatInfo::RGBAFormat(32, 32, 32, 32, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_UNSIGNED_INT, false, AlwaysSupported, NeverSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_BGRA8_EXT, InternalFormatInfo::RGBAFormat( 8, 8, 8, 8, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_BGRA4_ANGLEX, InternalFormatInfo::RGBAFormat( 4, 4, 4, 4, 0, GL_BGRA_EXT, GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_BGR5_A1_ANGLEX, InternalFormatInfo::RGBAFormat( 5, 5, 5, 1, 0, GL_BGRA_EXT, GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported )));
// Floating point renderability and filtering is provided by OES_texture_float and OES_texture_half_float
// | Internal format | | D |S | Format | Type | Comp | SRGB | Color renderable | Texture filterable | Supported |
// | | | | | | | type | | | | |
map.insert(InternalFormatInfoPair(GL_R16F, InternalFormatInfo::RGBAFormat(16, 0, 0, 0, 0, GL_RED, GL_HALF_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat16RenderableTextures, &rx::Renderer::getFloat16TextureRenderingSupport>, CheckSupport<&Context::supportsFloat16LinearFilter, &rx::Renderer::getFloat16TextureFilteringSupport>, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG16F, InternalFormatInfo::RGBAFormat(16, 16, 0, 0, 0, GL_RG, GL_HALF_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat16RenderableTextures, &rx::Renderer::getFloat16TextureRenderingSupport>, CheckSupport<&Context::supportsFloat16LinearFilter, &rx::Renderer::getFloat16TextureFilteringSupport>, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB16F, InternalFormatInfo::RGBAFormat(16, 16, 16, 0, 0, GL_RGB, GL_HALF_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat16RenderableTextures, &rx::Renderer::getFloat16TextureRenderingSupport>, CheckSupport<&Context::supportsFloat16LinearFilter, &rx::Renderer::getFloat16TextureFilteringSupport>, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA16F, InternalFormatInfo::RGBAFormat(16, 16, 16, 16, 0, GL_RGBA, GL_HALF_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat16RenderableTextures, &rx::Renderer::getFloat16TextureRenderingSupport>, CheckSupport<&Context::supportsFloat16LinearFilter, &rx::Renderer::getFloat16TextureFilteringSupport>, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_R32F, InternalFormatInfo::RGBAFormat(32, 0, 0, 0, 0, GL_RED, GL_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat32RenderableTextures, &rx::Renderer::getFloat32TextureRenderingSupport>, CheckSupport<&Context::supportsFloat32LinearFilter, &rx::Renderer::getFloat32TextureFilteringSupport>, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RG32F, InternalFormatInfo::RGBAFormat(32, 32, 0, 0, 0, GL_RG, GL_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat32RenderableTextures, &rx::Renderer::getFloat32TextureRenderingSupport>, CheckSupport<&Context::supportsFloat32LinearFilter, &rx::Renderer::getFloat32TextureFilteringSupport>, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGB32F, InternalFormatInfo::RGBAFormat(32, 32, 32, 0, 0, GL_RGB, GL_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat32RenderableTextures, &rx::Renderer::getFloat32TextureRenderingSupport>, CheckSupport<&Context::supportsFloat32LinearFilter, &rx::Renderer::getFloat32TextureFilteringSupport>, AlwaysSupported )));
map.insert(InternalFormatInfoPair(GL_RGBA32F, InternalFormatInfo::RGBAFormat(32, 32, 32, 32, 0, GL_RGBA, GL_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat32RenderableTextures, &rx::Renderer::getFloat32TextureRenderingSupport>, CheckSupport<&Context::supportsFloat32LinearFilter, &rx::Renderer::getFloat32TextureFilteringSupport>, AlwaysSupported )));
// Depth stencil formats
// | Internal format | | D |S | X | Format | Type | Component type | Depth | Stencil | Supported |
// | | | | | | | | | renderable | renderable | |
map.insert(InternalFormatInfoPair(GL_DEPTH_COMPONENT16, InternalFormatInfo::DepthStencilFormat(16, 0, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_UNSIGNED_NORMALIZED, AlwaysSupported, NeverSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_DEPTH_COMPONENT24, InternalFormatInfo::DepthStencilFormat(24, 0, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, GL_UNSIGNED_NORMALIZED, AlwaysSupported, NeverSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_DEPTH_COMPONENT32F, InternalFormatInfo::DepthStencilFormat(32, 0, 0, GL_DEPTH_COMPONENT, GL_FLOAT, GL_FLOAT, AlwaysSupported, NeverSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_DEPTH_COMPONENT32_OES, InternalFormatInfo::DepthStencilFormat(32, 0, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, GL_UNSIGNED_NORMALIZED, AlwaysSupported, NeverSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_DEPTH24_STENCIL8, InternalFormatInfo::DepthStencilFormat(24, 8, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, GL_UNSIGNED_NORMALIZED, AlwaysSupported, AlwaysSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_DEPTH32F_STENCIL8, InternalFormatInfo::DepthStencilFormat(32, 8, 24, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, GL_FLOAT, AlwaysSupported, AlwaysSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_STENCIL_INDEX8, InternalFormatInfo::DepthStencilFormat( 0, 8, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_BYTE, GL_UNSIGNED_INT, NeverSupported, AlwaysSupported, AlwaysSupported)));
// Luminance alpha formats
// | Internal format | | L | A | Format | Type | Component type | Supported |
map.insert(InternalFormatInfoPair(GL_ALPHA8_EXT, InternalFormatInfo::LUMAFormat( 0, 8, GL_ALPHA, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE8_EXT, InternalFormatInfo::LUMAFormat( 8, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_ALPHA32F_EXT, InternalFormatInfo::LUMAFormat( 0, 32, GL_ALPHA, GL_FLOAT, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE32F_EXT, InternalFormatInfo::LUMAFormat(32, 0, GL_LUMINANCE, GL_FLOAT, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_ALPHA16F_EXT, InternalFormatInfo::LUMAFormat( 0, 16, GL_ALPHA, GL_HALF_FLOAT, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE16F_EXT, InternalFormatInfo::LUMAFormat(16, 0, GL_LUMINANCE, GL_HALF_FLOAT, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE8_ALPHA8_EXT, InternalFormatInfo::LUMAFormat( 8, 8, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE_ALPHA32F_EXT, InternalFormatInfo::LUMAFormat(32, 32, GL_LUMINANCE_ALPHA, GL_FLOAT, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE_ALPHA16F_EXT, InternalFormatInfo::LUMAFormat(16, 16, GL_LUMINANCE_ALPHA, GL_HALF_FLOAT, GL_FLOAT, AlwaysSupported)));
// Unsized formats
// | Internal format | | Format | Supported |
map.insert(InternalFormatInfoPair(GL_ALPHA, InternalFormatInfo::UnsizedFormat(GL_ALPHA, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE, InternalFormatInfo::UnsizedFormat(GL_LUMINANCE, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE_ALPHA, InternalFormatInfo::UnsizedFormat(GL_LUMINANCE_ALPHA, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RED, InternalFormatInfo::UnsizedFormat(GL_RED, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RG, InternalFormatInfo::UnsizedFormat(GL_RG, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RGB, InternalFormatInfo::UnsizedFormat(GL_RGB, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RGBA, InternalFormatInfo::UnsizedFormat(GL_RGBA, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RED_INTEGER, InternalFormatInfo::UnsizedFormat(GL_RED_INTEGER, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RG_INTEGER, InternalFormatInfo::UnsizedFormat(GL_RG_INTEGER, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RGB_INTEGER, InternalFormatInfo::UnsizedFormat(GL_RGB_INTEGER, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RGBA_INTEGER, InternalFormatInfo::UnsizedFormat(GL_RGBA_INTEGER, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_BGRA_EXT, InternalFormatInfo::UnsizedFormat(GL_BGRA_EXT, AlwaysSupported)));
// Compressed formats, From ES 3.0.1 spec, table 3.16
// | Internal format | |W |H | BS |CC| Format | Type | SRGB | Supported |
map.insert(InternalFormatInfoPair(GL_COMPRESSED_R11_EAC, InternalFormatInfo::CompressedFormat(4, 4, 64, 1, GL_COMPRESSED_R11_EAC, GL_UNSIGNED_BYTE, false, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_SIGNED_R11_EAC, InternalFormatInfo::CompressedFormat(4, 4, 64, 1, GL_COMPRESSED_SIGNED_R11_EAC, GL_UNSIGNED_BYTE, false, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RG11_EAC, InternalFormatInfo::CompressedFormat(4, 4, 128, 2, GL_COMPRESSED_RG11_EAC, GL_UNSIGNED_BYTE, false, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_SIGNED_RG11_EAC, InternalFormatInfo::CompressedFormat(4, 4, 128, 2, GL_COMPRESSED_SIGNED_RG11_EAC, GL_UNSIGNED_BYTE, false, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGB8_ETC2, InternalFormatInfo::CompressedFormat(4, 4, 64, 3, GL_COMPRESSED_RGB8_ETC2, GL_UNSIGNED_BYTE, false, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_SRGB8_ETC2, InternalFormatInfo::CompressedFormat(4, 4, 64, 3, GL_COMPRESSED_SRGB8_ETC2, GL_UNSIGNED_BYTE, true, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, InternalFormatInfo::CompressedFormat(4, 4, 64, 3, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_UNSIGNED_BYTE, false, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, InternalFormatInfo::CompressedFormat(4, 4, 64, 3, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_UNSIGNED_BYTE, true, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGBA8_ETC2_EAC, InternalFormatInfo::CompressedFormat(4, 4, 128, 4, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_UNSIGNED_BYTE, false, UnimplementedSupport)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, InternalFormatInfo::CompressedFormat(4, 4, 128, 4, GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, GL_UNSIGNED_BYTE, true, UnimplementedSupport)));
// From GL_EXT_texture_compression_dxt1
// | Internal format | |W |H | BS |CC| Format | Type | SRGB | Supported |
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGB_S3TC_DXT1_EXT, InternalFormatInfo::CompressedFormat(4, 4, 64, 3, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE, false, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, InternalFormatInfo::CompressedFormat(4, 4, 64, 4, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE, false, AlwaysSupported)));
// From GL_ANGLE_texture_compression_dxt3
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE, InternalFormatInfo::CompressedFormat(4, 4, 128, 4, GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE, GL_UNSIGNED_BYTE, false, AlwaysSupported)));
// From GL_ANGLE_texture_compression_dxt5
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE, InternalFormatInfo::CompressedFormat(4, 4, 128, 4, GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE, GL_UNSIGNED_BYTE, false, AlwaysSupported)));
return map;
}
static InternalFormatInfoMap BuildES2InternalFormatInfoMap()
{
InternalFormatInfoMap map;
// From ES 2.0.25 table 4.5
map.insert(InternalFormatInfoPair(GL_NONE, InternalFormatInfo()));
// | Internal format | | R | G | B | A |S | Format | Type | Component type | SRGB | Color | Texture | Supported |
// | | | | | | | | | | | | renderable | filterable | |
map.insert(InternalFormatInfoPair(GL_RGBA4, InternalFormatInfo::RGBAFormat( 4, 4, 4, 4, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RGB5_A1, InternalFormatInfo::RGBAFormat( 5, 5, 5, 1, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RGB565, InternalFormatInfo::RGBAFormat( 5, 6, 5, 0, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported)));
// Extension formats
map.insert(InternalFormatInfoPair(GL_R8_EXT, InternalFormatInfo::RGBAFormat( 8, 0, 0, 0, 0, GL_RED_EXT, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures>)));
map.insert(InternalFormatInfoPair(GL_RG8_EXT, InternalFormatInfo::RGBAFormat( 8, 8, 0, 0, 0, GL_RG_EXT, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures>)));
map.insert(InternalFormatInfoPair(GL_RGB8_OES, InternalFormatInfo::RGBAFormat( 8, 8, 8, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RGBA8_OES, InternalFormatInfo::RGBAFormat( 8, 8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_BGRA8_EXT, InternalFormatInfo::RGBAFormat( 8, 8, 8, 8, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, false, AlwaysSupported, AlwaysSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_BGRA4_ANGLEX, InternalFormatInfo::RGBAFormat( 4, 4, 4, 4, 0, GL_BGRA_EXT, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_NORMALIZED, false, NeverSupported, AlwaysSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_BGR5_A1_ANGLEX, InternalFormatInfo::RGBAFormat( 5, 5, 5, 1, 0, GL_BGRA_EXT, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_NORMALIZED, false, NeverSupported, AlwaysSupported, AlwaysSupported)));
// Floating point formats have to query the renderer for support
// | Internal format | | R | G | B | A |S | Format | Type | Comp | SRGB | Color renderable | Texture filterable | Supported |
// | | | | | | | | | | type | | | | |
map.insert(InternalFormatInfoPair(GL_R16F_EXT, InternalFormatInfo::RGBAFormat(16, 0, 0, 0, 0, GL_RED, GL_HALF_FLOAT_OES, GL_FLOAT, false, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures> )));
map.insert(InternalFormatInfoPair(GL_R32F_EXT, InternalFormatInfo::RGBAFormat(32, 0, 0, 0, 0, GL_RED, GL_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures> )));
map.insert(InternalFormatInfoPair(GL_RG16F_EXT, InternalFormatInfo::RGBAFormat(16, 16, 0, 0, 0, GL_RG, GL_HALF_FLOAT_OES, GL_FLOAT, false, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures> )));
map.insert(InternalFormatInfoPair(GL_RG32F_EXT, InternalFormatInfo::RGBAFormat(32, 32, 0, 0, 0, GL_RG, GL_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures, &rx::Renderer::getRGTextureSupport>, CheckSupport<&Context::supportsRGTextures> )));
map.insert(InternalFormatInfoPair(GL_RGB16F_EXT, InternalFormatInfo::RGBAFormat(16, 16, 16, 0, 0, GL_RGB, GL_HALF_FLOAT_OES, GL_FLOAT, false, CheckSupport<&Context::supportsFloat16RenderableTextures, &rx::Renderer::getFloat16TextureRenderingSupport>, CheckSupport<&Context::supportsFloat16LinearFilter, &rx::Renderer::getFloat16TextureFilteringSupport>, CheckSupport<&Context::supportsFloat16Textures>)));
map.insert(InternalFormatInfoPair(GL_RGB32F_EXT, InternalFormatInfo::RGBAFormat(32, 32, 32, 0, 0, GL_RGB, GL_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat32RenderableTextures, &rx::Renderer::getFloat32TextureRenderingSupport>, CheckSupport<&Context::supportsFloat32LinearFilter, &rx::Renderer::getFloat32TextureFilteringSupport>, CheckSupport<&Context::supportsFloat32Textures>)));
map.insert(InternalFormatInfoPair(GL_RGBA16F_EXT, InternalFormatInfo::RGBAFormat(16, 16, 16, 16, 0, GL_RGBA, GL_HALF_FLOAT_OES, GL_FLOAT, false, CheckSupport<&Context::supportsFloat16RenderableTextures, &rx::Renderer::getFloat16TextureRenderingSupport>, CheckSupport<&Context::supportsFloat16LinearFilter, &rx::Renderer::getFloat16TextureFilteringSupport>, CheckSupport<&Context::supportsFloat16Textures>)));
map.insert(InternalFormatInfoPair(GL_RGBA32F_EXT, InternalFormatInfo::RGBAFormat(32, 32, 32, 32, 0, GL_RGBA, GL_FLOAT, GL_FLOAT, false, CheckSupport<&Context::supportsFloat32RenderableTextures, &rx::Renderer::getFloat32TextureRenderingSupport>, CheckSupport<&Context::supportsFloat32LinearFilter, &rx::Renderer::getFloat32TextureFilteringSupport>, CheckSupport<&Context::supportsFloat32Textures>)));
// Depth and stencil formats
// | Internal format | | D |S |X | Format | Type | Internal format | Depth | Stencil | Supported |
// | | | | | | | | type | renderable | renderable | |
map.insert(InternalFormatInfoPair(GL_DEPTH_COMPONENT32_OES,InternalFormatInfo::DepthStencilFormat(32, 0, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, GL_UNSIGNED_NORMALIZED, AlwaysSupported, NeverSupported, CheckSupport<&Context::supportsDepthTextures>)));
map.insert(InternalFormatInfoPair(GL_DEPTH24_STENCIL8_OES, InternalFormatInfo::DepthStencilFormat(24, 8, 0, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, GL_UNSIGNED_NORMALIZED, AlwaysSupported, AlwaysSupported, CheckSupport<&Context::supportsDepthTextures>)));
map.insert(InternalFormatInfoPair(GL_DEPTH_COMPONENT16, InternalFormatInfo::DepthStencilFormat(16, 0, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_UNSIGNED_NORMALIZED, AlwaysSupported, NeverSupported, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_STENCIL_INDEX8, InternalFormatInfo::DepthStencilFormat( 0, 8, 0, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, NeverSupported, AlwaysSupported, AlwaysSupported)));
// Unsized formats
// | Internal format | | Format | Supported |
map.insert(InternalFormatInfoPair(GL_ALPHA, InternalFormatInfo::UnsizedFormat(GL_ALPHA, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE, InternalFormatInfo::UnsizedFormat(GL_LUMINANCE, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE_ALPHA, InternalFormatInfo::UnsizedFormat(GL_LUMINANCE_ALPHA, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RED_EXT, InternalFormatInfo::UnsizedFormat(GL_RED_EXT, CheckSupport<&Context::supportsRGTextures>)));
map.insert(InternalFormatInfoPair(GL_RG_EXT, InternalFormatInfo::UnsizedFormat(GL_RG_EXT, CheckSupport<&Context::supportsRGTextures>)));
map.insert(InternalFormatInfoPair(GL_RGB, InternalFormatInfo::UnsizedFormat(GL_RGB, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_RGBA, InternalFormatInfo::UnsizedFormat(GL_RGBA, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_BGRA_EXT, InternalFormatInfo::UnsizedFormat(GL_BGRA_EXT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_DEPTH_COMPONENT, InternalFormatInfo::UnsizedFormat(GL_DEPTH_COMPONENT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_DEPTH_STENCIL_OES, InternalFormatInfo::UnsizedFormat(GL_DEPTH_STENCIL_OES, AlwaysSupported)));
// Luminance alpha formats from GL_EXT_texture_storage
// | Internal format | | L | A | Format | Type | Component type | Supported |
map.insert(InternalFormatInfoPair(GL_ALPHA8_EXT, InternalFormatInfo::LUMAFormat( 0, 8, GL_ALPHA, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE8_EXT, InternalFormatInfo::LUMAFormat( 8, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_ALPHA32F_EXT, InternalFormatInfo::LUMAFormat( 0, 32, GL_ALPHA, GL_FLOAT, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE32F_EXT, InternalFormatInfo::LUMAFormat(32, 0, GL_LUMINANCE, GL_FLOAT, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_ALPHA16F_EXT, InternalFormatInfo::LUMAFormat( 0, 16, GL_ALPHA, GL_HALF_FLOAT_OES, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE16F_EXT, InternalFormatInfo::LUMAFormat(16, 0, GL_LUMINANCE, GL_HALF_FLOAT_OES, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE8_ALPHA8_EXT, InternalFormatInfo::LUMAFormat( 8, 8, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, GL_UNSIGNED_NORMALIZED, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE_ALPHA32F_EXT, InternalFormatInfo::LUMAFormat(32, 32, GL_LUMINANCE_ALPHA, GL_FLOAT, GL_FLOAT, AlwaysSupported)));
map.insert(InternalFormatInfoPair(GL_LUMINANCE_ALPHA16F_EXT, InternalFormatInfo::LUMAFormat(16, 16, GL_LUMINANCE_ALPHA, GL_HALF_FLOAT_OES, GL_FLOAT, AlwaysSupported)));
// From GL_EXT_texture_compression_dxt1
// | Internal format | |W |H | BS |CC|Format | Type | SRGB | Supported |
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGB_S3TC_DXT1_EXT, InternalFormatInfo::CompressedFormat(4, 4, 64, 3, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE, false, CheckSupport<&Context::supportsDXT1Textures>)));
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, InternalFormatInfo::CompressedFormat(4, 4, 64, 4, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE, false, CheckSupport<&Context::supportsDXT1Textures>)));
// From GL_ANGLE_texture_compression_dxt3
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE, InternalFormatInfo::CompressedFormat(4, 4, 128, 4, GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE, GL_UNSIGNED_BYTE, false, CheckSupport<&Context::supportsDXT3Textures>)));
// From GL_ANGLE_texture_compression_dxt5
map.insert(InternalFormatInfoPair(GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE, InternalFormatInfo::CompressedFormat(4, 4, 128, 4, GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE, GL_UNSIGNED_BYTE, false, CheckSupport<&Context::supportsDXT5Textures>)));
return map;
}
static bool GetInternalFormatInfo(GLenum internalFormat, GLuint clientVersion, InternalFormatInfo *outFormatInfo)
{
const InternalFormatInfoMap* map = NULL;
if (clientVersion == 2)
{
static const InternalFormatInfoMap formatMap = BuildES2InternalFormatInfoMap();
map = &formatMap;
}
else if (clientVersion == 3)
{
static const InternalFormatInfoMap formatMap = BuildES3InternalFormatInfoMap();
map = &formatMap;
}
else
{
UNREACHABLE();
}
InternalFormatInfoMap::const_iterator iter = map->find(internalFormat);
if (iter != map->end())
{
if (outFormatInfo)
{
*outFormatInfo = iter->second;
}
return true;
}
else
{
return false;
}
}
typedef std::set<GLenum> FormatSet;
static FormatSet BuildES2ValidFormatSet()
{
static const FormatMap &formatMap = GetFormatMap(2);
FormatSet set;
for (FormatMap::const_iterator i = formatMap.begin(); i != formatMap.end(); i++)
{
const FormatTypePair& formatPair = i->first;
set.insert(formatPair.first);
}
return set;
}
static FormatSet BuildES3ValidFormatSet()
{
static const ES3FormatSet &formatSet = GetES3FormatSet();
FormatSet set;
for (ES3FormatSet::const_iterator i = formatSet.begin(); i != formatSet.end(); i++)
{
const FormatInfo& formatInfo = *i;
set.insert(formatInfo.mFormat);
}
return set;
}
typedef std::set<GLenum> TypeSet;
static TypeSet BuildES2ValidTypeSet()
{
static const FormatMap &formatMap = GetFormatMap(2);
TypeSet set;
for (FormatMap::const_iterator i = formatMap.begin(); i != formatMap.end(); i++)
{
const FormatTypePair& formatPair = i->first;
set.insert(formatPair.second);
}
return set;
}
static TypeSet BuildES3ValidTypeSet()
{
static const ES3FormatSet &formatSet = GetES3FormatSet();
TypeSet set;
for (ES3FormatSet::const_iterator i = formatSet.begin(); i != formatSet.end(); i++)
{
const FormatInfo& formatInfo = *i;
set.insert(formatInfo.mType);
}
return set;
}
struct EffectiveInternalFormatInfo
{
GLenum mEffectiveFormat;
GLenum mDestFormat;
GLuint mMinRedBits;
GLuint mMaxRedBits;
GLuint mMinGreenBits;
GLuint mMaxGreenBits;
GLuint mMinBlueBits;
GLuint mMaxBlueBits;
GLuint mMinAlphaBits;
GLuint mMaxAlphaBits;
EffectiveInternalFormatInfo(GLenum effectiveFormat, GLenum destFormat, GLuint minRedBits, GLuint maxRedBits,
GLuint minGreenBits, GLuint maxGreenBits, GLuint minBlueBits, GLuint maxBlueBits,
GLuint minAlphaBits, GLuint maxAlphaBits)
: mEffectiveFormat(effectiveFormat), mDestFormat(destFormat), mMinRedBits(minRedBits),
mMaxRedBits(maxRedBits), mMinGreenBits(minGreenBits), mMaxGreenBits(maxGreenBits),
mMinBlueBits(minBlueBits), mMaxBlueBits(maxBlueBits), mMinAlphaBits(minAlphaBits),
mMaxAlphaBits(maxAlphaBits) {};
};
typedef std::vector<EffectiveInternalFormatInfo> EffectiveInternalFormatList;
static EffectiveInternalFormatList BuildSizedEffectiveInternalFormatList()
{
EffectiveInternalFormatList list;
// OpenGL ES 3.0.3 Specification, Table 3.17, pg 141: Effective internal format coresponding to destination internal format and
// linear source buffer component sizes.
// | Source channel min/max sizes |
// Effective Internal Format | N/A | R | G | B | A |
list.push_back(EffectiveInternalFormatInfo(GL_ALPHA8_EXT, GL_NONE, 0, 0, 0, 0, 0, 0, 1, 8));
list.push_back(EffectiveInternalFormatInfo(GL_R8, GL_NONE, 1, 8, 0, 0, 0, 0, 0, 0));
list.push_back(EffectiveInternalFormatInfo(GL_RG8, GL_NONE, 1, 8, 1, 8, 0, 0, 0, 0));
list.push_back(EffectiveInternalFormatInfo(GL_RGB565, GL_NONE, 1, 5, 1, 6, 1, 5, 0, 0));
list.push_back(EffectiveInternalFormatInfo(GL_RGB8, GL_NONE, 6, 8, 7, 8, 6, 8, 0, 0));
list.push_back(EffectiveInternalFormatInfo(GL_RGBA4, GL_NONE, 1, 4, 1, 4, 1, 4, 1, 4));
list.push_back(EffectiveInternalFormatInfo(GL_RGB5_A1, GL_NONE, 5, 5, 5, 5, 5, 5, 1, 1));
list.push_back(EffectiveInternalFormatInfo(GL_RGBA8, GL_NONE, 5, 8, 5, 8, 5, 8, 2, 8));
list.push_back(EffectiveInternalFormatInfo(GL_RGB10_A2, GL_NONE, 9, 10, 9, 10, 9, 10, 2, 2));
return list;
}
static EffectiveInternalFormatList BuildUnsizedEffectiveInternalFormatList()
{
EffectiveInternalFormatList list;
// OpenGL ES 3.0.3 Specification, Table 3.17, pg 141: Effective internal format coresponding to destination internal format and
// linear source buffer component sizes.
// | Source channel min/max sizes |
// Effective Internal Format | Dest Format | R | G | B | A |
list.push_back(EffectiveInternalFormatInfo(GL_ALPHA8_EXT, GL_ALPHA, 0, UINT_MAX, 0, UINT_MAX, 0, UINT_MAX, 1, 8));
list.push_back(EffectiveInternalFormatInfo(GL_LUMINANCE8_EXT, GL_LUMINANCE, 1, 8, 0, UINT_MAX, 0, UINT_MAX, 0, UINT_MAX));
list.push_back(EffectiveInternalFormatInfo(GL_LUMINANCE8_ALPHA8_EXT, GL_LUMINANCE_ALPHA, 1, 8, 0, UINT_MAX, 0, UINT_MAX, 1, 8));
list.push_back(EffectiveInternalFormatInfo(GL_RGB565, GL_RGB, 1, 5, 1, 6, 1, 5, 0, UINT_MAX));
list.push_back(EffectiveInternalFormatInfo(GL_RGB8, GL_RGB, 6, 8, 7, 8, 6, 8, 0, UINT_MAX));
list.push_back(EffectiveInternalFormatInfo(GL_RGBA4, GL_RGBA, 1, 4, 1, 4, 1, 4, 1, 4));
list.push_back(EffectiveInternalFormatInfo(GL_RGB5_A1, GL_RGBA, 5, 5, 5, 5, 5, 5, 1, 1));
list.push_back(EffectiveInternalFormatInfo(GL_RGBA8, GL_RGBA, 5, 8, 5, 8, 5, 8, 5, 8));
return list;
}
static bool GetEffectiveInternalFormat(const InternalFormatInfo &srcFormat, const InternalFormatInfo &destFormat,
GLuint clientVersion, GLenum *outEffectiveFormat)
{
const EffectiveInternalFormatList *list = NULL;
GLenum targetFormat = GL_NONE;
if (gl::IsSizedInternalFormat(destFormat.mFormat, clientVersion))
{
static const EffectiveInternalFormatList sizedList = BuildSizedEffectiveInternalFormatList();
list = &sizedList;
}
else
{
static const EffectiveInternalFormatList unsizedList = BuildUnsizedEffectiveInternalFormatList();
list = &unsizedList;
targetFormat = destFormat.mFormat;
}
for (size_t curFormat = 0; curFormat < list->size(); ++curFormat)
{
const EffectiveInternalFormatInfo& formatInfo = list->at(curFormat);
if ((formatInfo.mDestFormat == targetFormat) &&
(formatInfo.mMinRedBits <= srcFormat.mRedBits && formatInfo.mMaxRedBits >= srcFormat.mRedBits) &&
(formatInfo.mMinGreenBits <= srcFormat.mGreenBits && formatInfo.mMaxGreenBits >= srcFormat.mGreenBits) &&
(formatInfo.mMinBlueBits <= srcFormat.mBlueBits && formatInfo.mMaxBlueBits >= srcFormat.mBlueBits) &&
(formatInfo.mMinAlphaBits <= srcFormat.mAlphaBits && formatInfo.mMaxAlphaBits >= srcFormat.mAlphaBits))
{
*outEffectiveFormat = formatInfo.mEffectiveFormat;
return true;
}
}
return false;
}
struct CopyConversion
{
GLenum mTextureFormat;
GLenum mFramebufferFormat;
CopyConversion(GLenum textureFormat, GLenum framebufferFormat)
: mTextureFormat(textureFormat), mFramebufferFormat(framebufferFormat) { }
bool operator<(const CopyConversion& other) const
{
return memcmp(this, &other, sizeof(CopyConversion)) < 0;
}
};
typedef std::set<CopyConversion> CopyConversionSet;
static CopyConversionSet BuildValidES3CopyTexImageCombinations()
{
CopyConversionSet set;
// From ES 3.0.1 spec, table 3.15
set.insert(CopyConversion(GL_ALPHA, GL_RGBA));
set.insert(CopyConversion(GL_LUMINANCE, GL_RED));
set.insert(CopyConversion(GL_LUMINANCE, GL_RG));
set.insert(CopyConversion(GL_LUMINANCE, GL_RGB));
set.insert(CopyConversion(GL_LUMINANCE, GL_RGBA));
set.insert(CopyConversion(GL_LUMINANCE_ALPHA, GL_RGBA));
set.insert(CopyConversion(GL_RED, GL_RED));
set.insert(CopyConversion(GL_RED, GL_RG));
set.insert(CopyConversion(GL_RED, GL_RGB));
set.insert(CopyConversion(GL_RED, GL_RGBA));
set.insert(CopyConversion(GL_RG, GL_RG));
set.insert(CopyConversion(GL_RG, GL_RGB));
set.insert(CopyConversion(GL_RG, GL_RGBA));
set.insert(CopyConversion(GL_RGB, GL_RGB));
set.insert(CopyConversion(GL_RGB, GL_RGBA));
set.insert(CopyConversion(GL_RGBA, GL_RGBA));
// Necessary for ANGLE back-buffers
set.insert(CopyConversion(GL_ALPHA, GL_BGRA_EXT));
set.insert(CopyConversion(GL_LUMINANCE, GL_BGRA_EXT));
set.insert(CopyConversion(GL_LUMINANCE_ALPHA, GL_BGRA_EXT));
set.insert(CopyConversion(GL_RED, GL_BGRA_EXT));
set.insert(CopyConversion(GL_RG, GL_BGRA_EXT));
set.insert(CopyConversion(GL_RGB, GL_BGRA_EXT));
set.insert(CopyConversion(GL_RGBA, GL_BGRA_EXT));
set.insert(CopyConversion(GL_RED_INTEGER, GL_RED_INTEGER));
set.insert(CopyConversion(GL_RED_INTEGER, GL_RG_INTEGER));
set.insert(CopyConversion(GL_RED_INTEGER, GL_RGB_INTEGER));
set.insert(CopyConversion(GL_RED_INTEGER, GL_RGBA_INTEGER));
set.insert(CopyConversion(GL_RG_INTEGER, GL_RG_INTEGER));
set.insert(CopyConversion(GL_RG_INTEGER, GL_RGB_INTEGER));
set.insert(CopyConversion(GL_RG_INTEGER, GL_RGBA_INTEGER));
set.insert(CopyConversion(GL_RGB_INTEGER, GL_RGB_INTEGER));
set.insert(CopyConversion(GL_RGB_INTEGER, GL_RGBA_INTEGER));
set.insert(CopyConversion(GL_RGBA_INTEGER, GL_RGBA_INTEGER));
return set;
}
bool IsValidInternalFormat(GLenum internalFormat, const Context *context)
{
if (!context)
{
return false;
}
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, context->getClientVersion(), &internalFormatInfo))
{
ASSERT(internalFormatInfo.mSupportFunction != NULL);
return internalFormatInfo.mSupportFunction(context);
}
else
{
return false;
}
}
bool IsValidFormat(GLenum format, GLuint clientVersion)
{
if (clientVersion == 2)
{
static const FormatSet formatSet = BuildES2ValidFormatSet();
return formatSet.find(format) != formatSet.end();
}
else if (clientVersion == 3)
{
static const FormatSet formatSet = BuildES3ValidFormatSet();
return formatSet.find(format) != formatSet.end();
}
else
{
UNREACHABLE();
return false;
}
}
bool IsValidType(GLenum type, GLuint clientVersion)
{
if (clientVersion == 2)
{
static const TypeSet typeSet = BuildES2ValidTypeSet();
return typeSet.find(type) != typeSet.end();
}
else if (clientVersion == 3)
{
static const TypeSet typeSet = BuildES3ValidTypeSet();
return typeSet.find(type) != typeSet.end();
}
else
{
UNREACHABLE();
return false;
}
}
bool IsValidFormatCombination(GLenum internalFormat, GLenum format, GLenum type, GLuint clientVersion)
{
if (clientVersion == 2)
{
static const FormatMap &formats = GetFormatMap(clientVersion);
FormatMap::const_iterator iter = formats.find(FormatTypePair(format, type));
return (iter != formats.end()) && ((internalFormat == (GLint)type) || (internalFormat == iter->second.mInternalFormat));
}
else if (clientVersion == 3)
{
static const ES3FormatSet &formats = GetES3FormatSet();
return formats.find(FormatInfo(internalFormat, format, type)) != formats.end();
}
else
{
UNREACHABLE();
return false;
}
}
bool IsValidCopyTexImageCombination(GLenum textureInternalFormat, GLenum frameBufferInternalFormat, GLuint readBufferHandle, GLuint clientVersion)
{
InternalFormatInfo textureInternalFormatInfo;
InternalFormatInfo framebufferInternalFormatInfo;
if (GetInternalFormatInfo(textureInternalFormat, clientVersion, &textureInternalFormatInfo) &&
GetInternalFormatInfo(frameBufferInternalFormat, clientVersion, &framebufferInternalFormatInfo))
{
if (clientVersion == 2)
{
UNIMPLEMENTED();
return false;
}
else if (clientVersion == 3)
{
static const CopyConversionSet conversionSet = BuildValidES3CopyTexImageCombinations();
const CopyConversion conversion = CopyConversion(textureInternalFormatInfo.mFormat,
framebufferInternalFormatInfo.mFormat);
if (conversionSet.find(conversion) != conversionSet.end())
{
// Section 3.8.5 of the GLES 3.0.3 spec states that source and destination formats
// must both be signed, unsigned, or fixed point and both source and destinations
// must be either both SRGB or both not SRGB. EXT_color_buffer_float adds allowed
// conversion between fixed and floating point.
if ((textureInternalFormatInfo.mColorEncoding == GL_SRGB) != (framebufferInternalFormatInfo.mColorEncoding == GL_SRGB))
{
return false;
}
if (((textureInternalFormatInfo.mComponentType == GL_INT) != (framebufferInternalFormatInfo.mComponentType == GL_INT)) ||
((textureInternalFormatInfo.mComponentType == GL_UNSIGNED_INT) != (framebufferInternalFormatInfo.mComponentType == GL_UNSIGNED_INT)))
{
return false;
}
if (gl::IsFloatOrFixedComponentType(textureInternalFormatInfo.mComponentType) &&
!gl::IsFloatOrFixedComponentType(framebufferInternalFormatInfo.mComponentType))
{
return false;
}
// GLES specification 3.0.3, sec 3.8.5, pg 139-140:
// The effective internal format of the source buffer is determined with the following rules applied in order:
// * If the source buffer is a texture or renderbuffer that was created with a sized internal format then the
// effective internal format is the source buffer's sized internal format.
// * If the source buffer is a texture that was created with an unsized base internal format, then the
// effective internal format is the source image array's effective internal format, as specified by table
// 3.12, which is determined from the <format> and <type> that were used when the source image array was
// specified by TexImage*.
// * Otherwise the effective internal format is determined by the row in table 3.17 or 3.18 where
// Destination Internal Format matches internalformat and where the [source channel sizes] are consistent
// with the values of the source buffer's [channel sizes]. Table 3.17 is used if the
// FRAMEBUFFER_ATTACHMENT_ENCODING is LINEAR and table 3.18 is used if the FRAMEBUFFER_ATTACHMENT_ENCODING
// is SRGB.
InternalFormatInfo sourceEffectiveFormat;
if (readBufferHandle != 0)
{
// Not the default framebuffer, therefore the read buffer must be a user-created texture or renderbuffer
if (gl::IsSizedInternalFormat(framebufferInternalFormatInfo.mFormat, clientVersion))
{
sourceEffectiveFormat = framebufferInternalFormatInfo;
}
else
{
// Renderbuffers cannot be created with an unsized internal format, so this must be an unsized-format
// texture. We can use the same table we use when creating textures to get its effective sized format.
GLenum effectiveFormat = gl::GetSizedInternalFormat(framebufferInternalFormatInfo.mFormat,
framebufferInternalFormatInfo.mType, clientVersion);
gl::GetInternalFormatInfo(effectiveFormat, clientVersion, &sourceEffectiveFormat);
}
}
else
{
// The effective internal format must be derived from the source framebuffer's channel sizes.
// This is done in GetEffectiveInternalFormat for linear buffers (table 3.17)
if (framebufferInternalFormatInfo.mColorEncoding == GL_LINEAR)
{
GLenum effectiveFormat;
if (GetEffectiveInternalFormat(framebufferInternalFormatInfo, textureInternalFormatInfo, clientVersion, &effectiveFormat))
{
gl::GetInternalFormatInfo(effectiveFormat, clientVersion, &sourceEffectiveFormat);
}
else
{
return false;
}
}
else if (framebufferInternalFormatInfo.mColorEncoding == GL_SRGB)
{
// SRGB buffers can only be copied to sized format destinations according to table 3.18
if (gl::IsSizedInternalFormat(textureInternalFormat, clientVersion) &&
(framebufferInternalFormatInfo.mRedBits >= 1 && framebufferInternalFormatInfo.mRedBits <= 8) &&
(framebufferInternalFormatInfo.mGreenBits >= 1 && framebufferInternalFormatInfo.mGreenBits <= 8) &&
(framebufferInternalFormatInfo.mBlueBits >= 1 && framebufferInternalFormatInfo.mBlueBits <= 8) &&
(framebufferInternalFormatInfo.mAlphaBits >= 1 && framebufferInternalFormatInfo.mAlphaBits <= 8))
{
gl::GetInternalFormatInfo(GL_SRGB8_ALPHA8, clientVersion, &sourceEffectiveFormat);
}
else
{
return false;
}
}
else
{
UNREACHABLE();
}
}
if (gl::IsSizedInternalFormat(textureInternalFormatInfo.mFormat, clientVersion))
{
// Section 3.8.5 of the GLES 3.0.3 spec, pg 139, requires that, if the destination format is sized,
// component sizes of the source and destination formats must exactly match
if (textureInternalFormatInfo.mRedBits != sourceEffectiveFormat.mRedBits ||
textureInternalFormatInfo.mGreenBits != sourceEffectiveFormat.mGreenBits ||
textureInternalFormatInfo.mBlueBits != sourceEffectiveFormat.mBlueBits ||
textureInternalFormatInfo.mAlphaBits != sourceEffectiveFormat.mAlphaBits)
{
return false;
}
}
return true; // A conversion function exists, and no rule in the specification has precluded conversion
// between these formats.
}
return false;
}
else
{
UNREACHABLE();
return false;
}
}
else
{
UNREACHABLE();
return false;
}
}
bool IsSizedInternalFormat(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mPixelBits > 0;
}
else
{
UNREACHABLE();
return false;
}
}
GLenum GetSizedInternalFormat(GLenum format, GLenum type, GLuint clientVersion)
{
const FormatMap &formats = GetFormatMap(clientVersion);
FormatMap::const_iterator iter = formats.find(FormatTypePair(format, type));
return (iter != formats.end()) ? iter->second.mInternalFormat : GL_NONE;
}
GLuint GetPixelBytes(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mPixelBits / 8;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetAlphaBits(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mAlphaBits;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetRedBits(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mRedBits;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetGreenBits(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mGreenBits;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetBlueBits(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mBlueBits;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetLuminanceBits(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mLuminanceBits;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetDepthBits(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mDepthBits;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetStencilBits(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mStencilBits;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetTypeBytes(GLenum type)
{
TypeInfo typeInfo;
if (GetTypeInfo(type, &typeInfo))
{
return typeInfo.mTypeBytes;
}
else
{
UNREACHABLE();
return 0;
}
}
bool IsSpecialInterpretationType(GLenum type)
{
TypeInfo typeInfo;
if (GetTypeInfo(type, &typeInfo))
{
return typeInfo.mSpecialInterpretation;
}
else
{
UNREACHABLE();
return false;
}
}
bool IsFloatOrFixedComponentType(GLenum type)
{
if (type == GL_UNSIGNED_NORMALIZED ||
type == GL_SIGNED_NORMALIZED ||
type == GL_FLOAT)
{
return true;
}
else
{
return false;
}
}
GLenum GetFormat(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mFormat;
}
else
{
UNREACHABLE();
return GL_NONE;
}
}
GLenum GetType(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mType;
}
else
{
UNREACHABLE();
return GL_NONE;
}
}
GLenum GetComponentType(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mComponentType;
}
else
{
UNREACHABLE();
return GL_NONE;
}
}
GLuint GetComponentCount(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mComponentCount;
}
else
{
UNREACHABLE();
return false;
}
}
GLenum GetColorEncoding(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mColorEncoding;
}
else
{
UNREACHABLE();
return false;
}
}
bool IsColorRenderingSupported(GLenum internalFormat, const rx::Renderer *renderer)
{
InternalFormatInfo internalFormatInfo;
if (renderer && GetInternalFormatInfo(internalFormat, renderer->getCurrentClientVersion(), &internalFormatInfo))
{
return internalFormatInfo.mIsColorRenderable(NULL, renderer);
}
else
{
UNREACHABLE();
return false;
}
}
bool IsColorRenderingSupported(GLenum internalFormat, const Context *context)
{
InternalFormatInfo internalFormatInfo;
if (context && GetInternalFormatInfo(internalFormat, context->getClientVersion(), &internalFormatInfo))
{
return internalFormatInfo.mIsColorRenderable(context, NULL);
}
else
{
UNREACHABLE();
return false;
}
}
bool IsTextureFilteringSupported(GLenum internalFormat, const rx::Renderer *renderer)
{
InternalFormatInfo internalFormatInfo;
if (renderer && GetInternalFormatInfo(internalFormat, renderer->getCurrentClientVersion(), &internalFormatInfo))
{
return internalFormatInfo.mIsTextureFilterable(NULL, renderer);
}
else
{
UNREACHABLE();
return false;
}
}
bool IsTextureFilteringSupported(GLenum internalFormat, const Context *context)
{
InternalFormatInfo internalFormatInfo;
if (context && GetInternalFormatInfo(internalFormat, context->getClientVersion(), &internalFormatInfo))
{
return internalFormatInfo.mIsTextureFilterable(context, NULL);
}
else
{
UNREACHABLE();
return false;
}
}
bool IsDepthRenderingSupported(GLenum internalFormat, const rx::Renderer *renderer)
{
InternalFormatInfo internalFormatInfo;
if (renderer && GetInternalFormatInfo(internalFormat, renderer->getCurrentClientVersion(), &internalFormatInfo))
{
return internalFormatInfo.mIsDepthRenderable(NULL, renderer);
}
else
{
UNREACHABLE();
return false;
}
}
bool IsDepthRenderingSupported(GLenum internalFormat, const Context *context)
{
InternalFormatInfo internalFormatInfo;
if (context && GetInternalFormatInfo(internalFormat, context->getClientVersion(), &internalFormatInfo))
{
return internalFormatInfo.mIsDepthRenderable(context, NULL);
}
else
{
UNREACHABLE();
return false;
}
}
bool IsStencilRenderingSupported(GLenum internalFormat, const rx::Renderer *renderer)
{
InternalFormatInfo internalFormatInfo;
if (renderer && GetInternalFormatInfo(internalFormat, renderer->getCurrentClientVersion(), &internalFormatInfo))
{
return internalFormatInfo.mIsStencilRenderable(NULL, renderer);
}
else
{
UNREACHABLE();
return false;
}
}
bool IsStencilRenderingSupported(GLenum internalFormat, const Context *context)
{
InternalFormatInfo internalFormatInfo;
if (context && GetInternalFormatInfo(internalFormat, context->getClientVersion(), &internalFormatInfo))
{
return internalFormatInfo.mIsStencilRenderable(context, NULL);
}
else
{
UNREACHABLE();
return false;
}
}
GLuint GetRowPitch(GLenum internalFormat, GLenum type, GLuint clientVersion, GLsizei width, GLint alignment)
{
ASSERT(alignment > 0 && isPow2(alignment));
return rx::roundUp(GetBlockSize(internalFormat, type, clientVersion, width, 1), static_cast<GLuint>(alignment));
}
GLuint GetDepthPitch(GLenum internalFormat, GLenum type, GLuint clientVersion, GLsizei width, GLsizei height, GLint alignment)
{
return GetRowPitch(internalFormat, type, clientVersion, width, alignment) * height;
}
GLuint GetBlockSize(GLenum internalFormat, GLenum type, GLuint clientVersion, GLsizei width, GLsizei height)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
if (internalFormatInfo.mIsCompressed)
{
GLsizei numBlocksWide = (width + internalFormatInfo.mCompressedBlockWidth - 1) / internalFormatInfo.mCompressedBlockWidth;
GLsizei numBlocksHight = (height + internalFormatInfo.mCompressedBlockHeight - 1) / internalFormatInfo.mCompressedBlockHeight;
return (internalFormatInfo.mPixelBits * numBlocksWide * numBlocksHight) / 8;
}
else
{
TypeInfo typeInfo;
if (GetTypeInfo(type, &typeInfo))
{
if (typeInfo.mSpecialInterpretation)
{
return typeInfo.mTypeBytes * width * height;
}
else
{
return internalFormatInfo.mComponentCount * typeInfo.mTypeBytes * width * height;
}
}
else
{
UNREACHABLE();
return 0;
}
}
}
else
{
UNREACHABLE();
return 0;
}
}
bool IsFormatCompressed(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mIsCompressed;
}
else
{
UNREACHABLE();
return false;
}
}
GLuint GetCompressedBlockWidth(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mCompressedBlockWidth;
}
else
{
UNREACHABLE();
return 0;
}
}
GLuint GetCompressedBlockHeight(GLenum internalFormat, GLuint clientVersion)
{
InternalFormatInfo internalFormatInfo;
if (GetInternalFormatInfo(internalFormat, clientVersion, &internalFormatInfo))
{
return internalFormatInfo.mCompressedBlockHeight;
}
else
{
UNREACHABLE();
return 0;
}
}
ColorWriteFunction GetColorWriteFunction(GLenum format, GLenum type, GLuint clientVersion)
{
static const FormatMap &formats = GetFormatMap(clientVersion);
FormatMap::const_iterator iter = formats.find(FormatTypePair(format, type));
return (iter != formats.end()) ? iter->second.mColorWriteFunction : NULL;
}
}
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
c40636625511769a8a8bd667d315a05186037d73 | 8439ff68be423af921eba416a9762338856f4011 | /Lab 1 Funkcja Kwadratowa/FunkcjaKwadratowa/main.cpp | 1b638ea78917f09ebab6bbf5d0930ce7f0ecb0fa | [] | no_license | zeref80/StudiaProgramowanie | 69289c5cc8c41a7074d3d8e7ad67890fe5593cc3 | 094a42a062642c65e6d1995d62725a9df01e890d | refs/heads/main | 2023-09-05T09:28:57.028725 | 2021-10-28T13:24:10 | 2021-10-28T13:24:10 | 415,715,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,297 | cpp | #include <iostream>
#include <math.h>
using namespace std;
float a;
float b;
float c;
float delta;
int main()
{
// setlocale(LC_CTYPE, "Polish");
cout<<"Program bedzie zwracac miejsca zerowe funkcji kwadratowej postaci ax^2+bx+c"<<endl;
cout<<"Prosze stosowac sie do polecen wyswietlanych ne ekranie"<<endl;
cout << "Podaj wspolczynnik a: "<<endl;
cin >> a;
while (a == 0) {
cout << "To nie jest funkcja kwadratowa " ;
cout << "Podaj prosze ponownie wspolczynnik a: "<<endl;
cin >> a;
}
cout << "Podaj wspolczynnik b: ";
cin >> b;
cout << "Podaj wspolczynnik c: ";
cin >> c;
delta=(b*b)-(4*a*c);
if (delta<0)
{
cout << "Ta funkcja nie ma punktu przeciecia z osia OX. Jej wspolrzedne wierzcholka to: " << "(" <<-b/(2*a )<< "," << -delta/(4*a)<<")";
}
else if (delta>0)
{
cout << "Ta funkcja ma 2 rozne pierwiastki rzeczywiste: " <<"X1= "<<(-b-sqrt(delta))/(2*a)<<" oraz X2= "<<(-b+sqrt(delta))/(2*a)<<endl;
cout << "Wspolrzedne wierzcholka to: " <<"("<<-b/(2*a)<<","<< (4*a)<<")";
}
else
cout << "Ta funkcja ma tylko 1 rozwiazanie, ktore jest jednoczesnie wierzcholkiem funkcji: " << "("<<-b/(2*a)<<","<< -delta/(4*a)<<")";
cout << endl;
return 0;
}
| [
"12345qaz6789@wp.pl"
] | 12345qaz6789@wp.pl |
52d3788b75dee86f6b6ca756ccdda6aa3bddd859 | d040975e39bc06e54d057f5a85559345d6994bef | /_includes/dsomapviewer.cc | 29425dd7e9b97fe1cdb95ddfb777fc82cdb4bdaa | [] | no_license | floooh/flohofwoe.www | f3248d2211986bc75ae57406553ccbe192c6c483 | b1ee979e3fbb49256a0eae9456696b120174db7a | refs/heads/master | 2020-05-31T18:02:17.068306 | 2014-02-26T22:09:15 | 2014-02-26T22:09:15 | 9,329,159 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | cc | //------------------------------------------------------------------------------
// dsomapviewer.cc
// (C) 2012 A.Weissflog
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "dsomapviewerapplication.h"
ImplementNebulaApplication();
void
NebulaMain(const Util::CommandLineArgs& args)
{
App::DSOMapViewerApplication app;
app.SetCompanyName("Bigpoint GmbH");
app.SetAppTitle("DSO Map Viewer App");
app.SetAppID("DSMV");
app.SetAppVersion("1.0");
app.SetCmdLineArgs(args);
#if __EMSCRIPTEN__
app.SetOverrideRootDirectory("httpnz://localhost/cdndata");
#elif __IOS__
app.SetOverrideRootDirectory("httpnz://127.0.0.1:8000/cdndata");
//app->SetOverrideRootDirectory("httpnz://www.flohofwoe.net/demos/cdndata");
#elif __OSX__
app.SetOverrideRootDirectory("httpnz://0.0.0.0:8000/cdndata");
#elif __NACL__
app.SetOverrideRootDirectory("httpnz://localhost:8080/cdndata");
#endif
app.StartMainLoop();
}
| [
"floooh@gmail.com"
] | floooh@gmail.com |
23d8aaf82e87da9f9a2b83dea6bd7e3e42156acc | da930cdc1776f67bb68e8675b308fdd0b6f869aa | /prac/work.cpp | 2ea851c301e40fb3a236c89f4e44204e1a3932bd | [] | no_license | exspeed/PSC | c0e7ce51e7d81634d20ef19bbaeb3c4ddb6fa099 | 465593717795b0f9ae3ce28ba8622c92bd544b2d | refs/heads/master | 2021-05-04T11:44:30.386459 | 2017-01-28T19:21:03 | 2017-01-28T19:21:03 | 43,104,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | #include<iostream>
#include<stdio.h>
using namespace std;
int getTime(int shr, int smin, int ehr, int emin){
int min;
if(emin >= smin){
min = emin - smin;
}else{
min = (60 -smin) + emin;
shr++;
}
int hr = shr > ehr ? (12 - shr) + ehr : ehr -shr;
return (min + 60*hr);
}
// format: start time (hr:min) end time (hr:min)
int main(){
printf("number of guards: ");
int N; cin >> N;
printf("rotation time: ");
int rotation; cin >> rotation;
int time[N][4];
int totalTime[N];
for(int i = 0; i < N; i++){
scanf("%d:%d %d:%d",&time[i][0], &time[i][1], &time[i][2],&time[i][3]);
totalTime[i] = getTime(time[i][0], time[i][1], time[i][2],time[i][3]);
}
cout << totalTime[0]<< endl;
// works every 30 m int rotations = 60;ins
int possible = totalTime[0] % rotation;
if(possible == 0){
cout << "YES\n";
}
return 0;
}
| [
"andrewheng2@gmail.com"
] | andrewheng2@gmail.com |
a7a09c882caa30ef3ac44d65bc8b6b6686729169 | 9dc9d726d5a2f0b3f4994b2bdbc63777c7354a88 | /Source/MgsLib/Control.hpp | a1ca76cbd242fd6286f4412160fce5aea8eb08b8 | [] | no_license | droogie/msgi | 36f4a2f81a256e6ae84d2eb4f3f65cd5a6cf9b1a | 953c24b0df5d780ef72a0510380ad1d9b06ddce0 | refs/heads/master | 2020-03-18T18:55:08.782640 | 2018-05-27T19:48:19 | 2018-05-27T19:48:19 | 135,122,562 | 1 | 1 | null | 2018-05-28T07:04:27 | 2018-05-28T07:04:27 | null | UTF-8 | C++ | false | false | 1,278 | hpp | #pragma once
#include "MgsFunction.hpp"
#include "Psx.hpp"
void ForceLinkControlCpp();
void DoControlTests();
struct Res_Control_unknown
{
__int16 field_0_scriptData_orHashedName;
__int16 field_2_name_hash;
__int16 field_4_trigger_Hash_Name_or_camera_w;
__int16 field_6_count;
int field_8_wordPtr;
int field_C;
int field_10;
SVECTOR field_14_vec;
};
MGS_ASSERT_SIZEOF(Res_Control_unknown, 0x1c);
struct map_record;
struct Res_Control
{
SVECTOR field_0_vec;
SVECTOR field_8_vec;
Res_Control_unknown field_10_pStruct_hzd_unknown;
map_record *field_2C_map;
__int16 field_30_scriptData;
__int16 field_32_height;
__int16 field_34;
__int16 field_36;
__int16 field_38;
__int16 field_3A;
__int16 field_3C;
__int16 field_3E;
__int16 field_40;
__int16 field_42;
SVECTOR field_44_vec;
SVECTOR field_4C_turn_vec;
char field_54;
char field_55_flags;
char field_56;
char field_57;
char field_58;
char field_59;
__int16 field_5A;
int field_5C_mesg;
SVECTOR field_60_vecs_ary[2];
int field_70;
int field_74;
__int16 field_78;
__int16 field_7A;
};
MGS_ASSERT_SIZEOF(Res_Control, 0x7c);
| [
"Paul@paul.com"
] | Paul@paul.com |
6b843b1b71e4054ca3f4ea70d9eb4f699121d87e | 583a231b07742ecfc96ab40be179abc3d4247559 | /Ejercicio11/main.cpp | 34ae1a5f32d489263deeb39a108cf86d9098e9e5 | [] | no_license | MateoHoyos/Lab1 | 8aa64162ef9505dd7e220625abb14f5208a70ae5 | 64e10ecc15fab5f8cabfbcea9d43385edc9e1508 | refs/heads/main | 2022-12-27T05:22:29.326311 | 2020-10-03T03:35:25 | 2020-10-03T03:35:25 | 300,787,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | cpp | #include <iostream>
using namespace std;
/*Ejercicio 11. Escriba un programa que pida un número N e imprima en pantalla su tabla de mul-
tiplicar hasta 10xN.
Ej: si se ingresa 7 se debe imprimir:
1x7=7
2x7=14
3x7=21
4x7=28
5x7=35
6x7=42
7x7=49
8x7=56
9x7=63
10x7=70*/
int main()
{
int N;
cout<<"Ingrese un numero N: ";
cin>>N;
for(int i=1;i<=10;i++){
cout<<i<<"x"<<N<<"="<<i*N<<endl;
}
return 0;
}
| [
"mateo.hoyos@udea.edu.co"
] | mateo.hoyos@udea.edu.co |
c315a8a35d3a830b5bc0f7f4cb63b9d2c3aa13f5 | 58e37a43d291d1884234f86b855b5f7da55725ef | /Recurssion/Basics/printNumberIncDec.cpp | cc65087c80204c69cb2d3095c110648ae5e672b1 | [] | no_license | shashank9aug/DSA_CB | 74337f8fb5dde5b94b380512dcec39a13e643690 | 1301329e4f9fd5105b4cb3c9d0f5c5772ed890ce | refs/heads/master | 2023-08-18T05:35:42.946559 | 2021-10-15T10:04:52 | 2021-10-15T10:04:52 | 370,120,570 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | cpp | /*
---important---
There are two ways for function call :
->Increasing order : We are calling function after output statement
will be in top to bottom (Base)
->decreasing order : we are calling function before output statement
will be in bottom (Base) to top
*/
#include<iostream>
using namespace std;
//decreasing order
void dec(int n){
//Base case :
if(n==0){
return;
}
//rec case :
cout<<n<<",";
dec(n-1);
}
//Increasing order :
void inc(int n){
//Base case :
if(n==0){
return;
}
//rec case :
inc(n-1);
cout<<n<<",";
}
int main(){
int n;
cout<<"Enter value of n : ";
cin>>n;
dec(n);
cout<<endl;
inc(n);
return 0;
} | [
"shekhar1245shashank@gmail.com"
] | shekhar1245shashank@gmail.com |
5dbdd626e8add6603e0bae2a970225f33ec60d2a | f2f10e55a14b36180ec8d08afb208201af8aa479 | /Block.h | 5cfbc6618b125aff7f088ec1048c1fcd2ac81b60 | [] | no_license | ajdm05/Semana5 | 00cf815b7c761f202334acd5a32ec35991530dc6 | 90b386649dee76c0591ab501ad85c91e5502445d | refs/heads/master | 2021-05-26T23:37:44.583113 | 2013-05-24T13:34:50 | 2013-05-24T13:34:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | h | #ifndef BLOCK_H
#define BLOCK_H
#include "SDL.h"
#include "SDL_image.h"
#include "Utility.h"
#include "Dot.h"
enum{
NONE,
TOP,
BOT,
LEFT,
RIGHT,
CORNERUL,
CORNERUR,
CORNERDL,
CORNERDR,
COLLIDING
};
class Block
{
public:
bool isColliding;
bool wasColliding;
Block();
float x, y;
int life;
int width,height;
SDL_Surface *image;
SDL_Surface *screen;
Dot *dot;
Block(float x, float y, int width, int height,
SDL_Surface *image, SDL_Surface *screen,
Dot *dot);
int collisionType();
bool isPointInside(float pointX, float pointY);
void show();
void logic();
virtual ~Block();
protected:
private:
};
#endif // BLOCK_H
| [
"angela.delgado@unitec.edu"
] | angela.delgado@unitec.edu |
c9d88f40a3c74d7f9e136e90fc3c615782a75fcf | 8c9cbb17b03dc10281d93ea89f60743bb02802d6 | /FLVParser/FLV/FLVTagAudio.hpp | 4571ce6f09fd2746e65e994e50eede69901e7a8d | [] | no_license | asdlei99/FLVParser | ac46fc1e1785a99f67cde7998102f6648a73aaac | 7f34fe1a8f97d842d5b21f6255a0094607b3e3d0 | refs/heads/master | 2020-06-03T19:15:21.077094 | 2018-09-30T01:56:05 | 2018-09-30T01:56:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,385 | hpp | //
// FLVTagAudio.hpp
// FLVParser
//
// Created by dKingbin on 2018/9/23.
// Copyright © 2018年 dKingbin. All rights reserved.
//
#ifndef FLVTagAudio_hpp
#define FLVTagAudio_hpp
#include <iostream>
#include "PtrBuffer.hpp"
#include "FLVTag.hpp"
#include "BitBuffer.hpp"
namespace ffstl
{
struct MP3Header
{
uint16_t syn_; //u(11)
uint8_t version_; //u(2)
uint8_t layer_; //u(2)
uint8_t protection_; //u(1)
uint8_t bitrate_; //u(4)
uint8_t frequency_; //u(2)
uint8_t padding_; //u(1)
uint8_t private_; //u(1)
//00-立体声 01-Joint Stereo 10-双声道 11-单声道 (默认双声道)
uint8_t mode_; //u(2)
uint8_t mode_extension_;//u(2)
uint8_t copyright_; //u(1)
uint8_t original_; //u(1)
uint8_t emphasis_; //u(2)
};
struct ACCHeader
{
uint8_t audioObjectType_; //u(5)
uint8_t samplingFrequencyIndex_; //u(4)
uint8_t channelConfiguration_; //u(4)
uint8_t extensionSamplingIndex_; //u(4)
uint8_t extensionAudioObjectType_;
};
class FLVTagAudio : public FLVTag
{
public:
FLVTagAudio(std::shared_ptr<PtrBuffer> buffer) : FLVTag(buffer)
{}
virtual void parser(size_t& size);
void parse_acc(size_t size);
void parse_mp3(size_t size);
protected:
int8_t soundFormat_;
int8_t soundRate_;
int8_t soundSize_;
int8_t soundType_;
int8_t aacPacketType_;
};
}
#endif /* FLVTagAudio_hpp */
| [
"yaoshibang@iMac.local"
] | yaoshibang@iMac.local |
b3ecdcf3c96b0df6f0524fdb1cc749014cf763da | 9ff9404def65279f09fb92077ab685fc0edbc0a9 | /nccl/src/enqueue.cc | 7796f49da2fdf76423e6e180c73c41ce5a28cb8b | [] | no_license | htang2012/misc-software-projects | c6d2cd6f33174cd07ce940ef73b71ebeb35f9d4a | e67d87249cf6d2a2d014e9d4ad40c1a06784aae0 | refs/heads/master | 2020-09-15T17:02:21.220498 | 2019-12-03T21:49:02 | 2019-12-03T21:49:02 | 223,510,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,925 | cc | /*************************************************************************
* Copyright (c) 2017-2019, NVIDIA CORPORATION. All rights reserved.
*
* See LICENSE.txt for license information
************************************************************************/
#include "enqueue.h"
#include "argcheck.h"
// Only generate inline kernels for LL
#define NCCL_FUNC5(coll, op, dtype) { }
#define NCCL_FUNC4(coll, op, dtype) {}
// Must be consistent with ncclDataType_t
#define NCCL_FUNCS3A(coll, op) {}
#define NCCL_FUNCS3B(coll, op) {}
// Must be consistent with ncclRedOp_t -- but we only generate kernel for sums.
#define NCCL_FUNCS2A(coll) {}
#define NCCL_FUNCS2B(coll) {}
// Must be consistent with the ncclFuncSet enum
static void* const ncclKerns[NCCL_NUM_FUNCTIONS*ncclNumOps*ncclNumTypes*NCCL_NUM_ALGORITHMS*NCCL_NUM_PROTOCOLS] = {
NCCL_FUNCS2B(ncclBroadcast),
NCCL_FUNCS2A(ncclReduce),
NCCL_FUNCS2B(ncclAllGather),
NCCL_FUNCS2A(ncclReduceScatter),
NCCL_FUNCS2A(ncclAllReduce)
};
/*****************************************************************************/
/* Launch system : synchronization and CUDA kernel launch */
/*****************************************************************************/
ncclResult_t ncclLaunchCooperativeKernelMultiDevice(struct cudaLaunchParams *paramsList, int* cudaDevs, int numDevices, int cgMode) {
#if CUDART_VERSION >= 9000
if (cgMode & 0x01) {
CUDACHECK(cudaLaunchCooperativeKernelMultiDevice(paramsList, numDevices,
// These flags are to reduce the latency of using this API
cudaCooperativeLaunchMultiDeviceNoPreSync|cudaCooperativeLaunchMultiDeviceNoPostSync));
return ncclSuccess;
}
#endif
int savedDev;
CUDACHECK(cudaGetDevice(&savedDev));
for (int i = 0; i < numDevices; i++) {
struct cudaLaunchParams* params = paramsList+i;
CUDACHECK(cudaSetDevice(cudaDevs[i]));
}
CUDACHECK(cudaSetDevice(savedDev));
return ncclSuccess;
}
ncclResult_t setupLaunch(struct ncclComm* comm, struct cudaLaunchParams* params) {
// Set active = 2 for the last operation
// Find the first operation, choose the kernel accordingly and pass it
// as the first argument.
struct ncclColl* coll = comm->channels[0].collectives+comm->channels[0].collStart;
memcpy(&comm->args, coll, sizeof(struct ncclColl));
// As we pass that coll directly, we can free it immediately.
coll->active = 0;
params->func = ncclKerns[coll->funcIndex];
return ncclSuccess;
}
ncclResult_t ncclCpuBarrierIn(struct ncclComm* comm, int* isLast) {
volatile int* ptr = (volatile int*)(comm->intraBarrier+comm->intraPhase);
int val = *ptr;
bool done = false;
while (done == false) {
if (val >= comm->intraRanks) {
WARN("Trying to launch too many collectives");
return ncclInvalidUsage;
}
if (val+1 == comm->intraRanks) {
// Reset the barrier.
comm->intraBarrier[comm->intraPhase^1] = 0;
*isLast = 1;
return ncclSuccess;
}
done = __sync_bool_compare_and_swap(ptr, val, val+1);
val++;
}
*isLast = 0;
return ncclSuccess;
}
ncclResult_t ncclCpuBarrierLast(struct ncclComm* comm) {
volatile int* ptr = (volatile int*)(comm->intraBarrier+comm->intraPhase);
int val = *ptr;
if (__sync_bool_compare_and_swap(ptr, val, val+1) != true) {
WARN("Trying to launch too many collectives");
return ncclInternalError;
}
return ncclSuccess;
}
ncclResult_t ncclCpuBarrierOut(struct ncclComm* comm) {
volatile int* ptr = (volatile int*)(comm->intraBarrier+comm->intraPhase);
while (*ptr < comm->intraRanks) pthread_yield();
comm->intraPhase ^= 1;
return ncclSuccess;
}
ncclResult_t ncclBarrierEnqueue(struct ncclComm* comm) {
if (comm->nRanks == 1) return ncclSuccess;
struct cudaLaunchParams* params = comm->myParams;
NCCLCHECK(setupLaunch(comm, params));
// Use internal NCCL stream for CGMD/GROUP launch if required or if the user stream is NULL
if (comm->launchMode == ncclComm::GROUP && (comm->groupCudaStream || comm->userStream == NULL)) {
// Enqueue event in user stream
CUDACHECK(cudaEventRecord(comm->doneEvent, comm->userStream));
// Create dependency between user stream and internal NCCL stream
CUDACHECK(cudaStreamWaitEvent(comm->groupStream, comm->doneEvent, 0));
} else {
}
int isLast = 0;
NCCLCHECK(ncclCpuBarrierIn(comm, &isLast));
if (isLast) {
if (comm->launchMode == ncclComm::GROUP) {
// I'm the last. Launch all operations.
NCCLCHECK(ncclLaunchCooperativeKernelMultiDevice(comm->intraParams, comm->intraCudaDevs, comm->intraRanks, *comm->intraCGMode));
}
NCCLCHECK(ncclCpuBarrierLast(comm));
}
return ncclSuccess;
}
ncclResult_t ncclBarrierEnqueueWait(ncclComm_t comm) {
if (comm->nRanks == 1) return ncclSuccess;
// We can't print the CG mode before the first barrier happened.
if (comm->rank == 0 && *comm->intraCGMode & 0x10) {
*comm->intraCGMode ^= 0x10;
INFO(NCCL_INIT,"Launch mode %s%s%s",
comm->launchMode == ncclComm::GROUP ? "Group" : "Parallel",
*comm->intraCGMode ? "/CGMD" : "",
(comm->launchMode == ncclComm::GROUP && comm->groupCudaStream) ? "/Stream" : "");
}
NCCLCHECK(ncclCpuBarrierOut(comm));
struct cudaLaunchParams *params = comm->myParams;
// Start the network proxies as soon as the kernel has been launched. We can't
// perform any CUDA call between the two or having a cudaFree between the CUDA
// launch and the transportStartProxy call could cause a deadlock.
// Also, starting the proxies after the CUDA launch seems to be better for
// performance (latency).
comm->lastOpCount = comm->opCount;
NCCLCHECK(transportStartProxy(comm));
return ncclSuccess;
}
ncclResult_t ncclEnqueueEvents(ncclComm_t comm) {
struct cudaLaunchParams *params = comm->myParams;
// Enqueue event after NCCL kernel
// Use internal NCCL stream for CGMD/GROUP launch if required or if the user stream is NULL
if (comm->launchMode == ncclComm::GROUP && (comm->groupCudaStream || comm->userStream == NULL)) {
// Create dependency between NCCL internal stream and user stream
CUDACHECK(cudaStreamWaitEvent(comm->userStream, comm->doneEvent, 0));
}
comm->userStreamSet = false;
return ncclSuccess;
}
/*****************************************************************************/
/* Enqueueing system : computation of kernel and proxy operations parameters */
/*****************************************************************************/
// Trees are not perfectly sticking to the model for medium sizes. Applying a static correction
// factor is not ideal but works quite well. Powers of two, 64 B to 1 GB.
static float treeCorrectionFactor[NCCL_NUM_PROTOCOLS][22] = {
{ 1.0, 1.0, 1.0, 1.0, .9, .8, .7, .7, .7, .7, .6, .5, .5, .5, .6, .7, .8, .9, .9, 1.0, 1.0, 1.0 },
{ 1.0, 1.0, 1.0, 1.0, 1.0, .9, .8, .8, .8, .8, .7, .7, .7, .6, .6, .7, .7, .8, .8, .9, .9, 1.0 },
{ .9, .9, .9, .9, .9, .9, .9, .8, .7, .6, .6, .5, .5, .5, .5, .5, .5, .6, .6, .7, .8, .9 }
};
static ncclResult_t getAlgoInfo(struct ncclInfo* info) {
struct ncclComm* comm = info->comm;
float minTime = 3600000.0; // Hopefully no operation will take an hour to complete.
// Find algorithm / protocol.
info->algorithm = -1;
info->protocol = -1;
for (int a=0; a<NCCL_NUM_ALGORITHMS; a++) {
for (int p=0; p<NCCL_NUM_PROTOCOLS; p++) {
float bw = comm->bandwidths[info->coll][a][p];
if (bw == 0) continue;
int logSize = log2i(info->nBytes>>6);
if (a == NCCL_ALGO_TREE && logSize < 22) bw *= treeCorrectionFactor[p][logSize];
float time = comm->latencies[info->coll][a][p] + (info->nBytes) / (1000 * bw);
if (time < minTime) {
info->algorithm = a;
info->protocol = p;
minTime = time;
}
}
}
if (info->algorithm == -1 || info->protocol == -1) {
WARN("Error : no algorithm/protocol available");
return ncclInternalError;
}
//if (comm->rank == 0) INFO(NCCL_COLL, "%ld Bytes -> Algo %d proto %d time %d", info->nBytes, info->algorithm, info->protocol, minTime);
TRACE(NCCL_COLL, "%ld Bytes -> Algo %d proto %d time %f", info->nBytes, info->algorithm, info->protocol, minTime);
int nc = comm->nChannels;
int nt = comm->maxThreads[info->protocol];
int threadThreshold = comm->threadThresholds[info->algorithm][info->protocol];
while (info->nBytes < nc*nt*threadThreshold) {
if (nc >= 2) nc--;
else if ((nt % 128) == 0) nt/=2;
else break;
}
if (info->protocol == NCCL_PROTO_SIMPLE) nt += WARP_SIZE; // Extra warp for sync
info->nChannels = nc;
info->nThreads = nt;
return ncclSuccess;
}
static ncclResult_t getPatternInfo(struct ncclInfo* info) {
switch (info->coll) {
case ncclCollBroadcast:
info->pattern = info->algorithm == NCCL_ALGO_TREE ? ncclPatternTreeDown : ncclPatternPipelineFrom; break;
case ncclCollReduce:
info->pattern = info->algorithm == NCCL_ALGO_TREE ? ncclPatternTreeUp : ncclPatternPipelineTo; break;
case ncclCollReduceScatter:
case ncclCollAllGather:
info->pattern = ncclPatternRing; break;
case ncclCollAllReduce:
info->pattern = info->algorithm == NCCL_ALGO_TREE ? ncclPatternTreeUpDown : ncclPatternRingTwice; break;
default:
WARN("Unknown pattern for collective %d algorithm %d", info->coll, info->algorithm);
return ncclInternalError;
}
return ncclSuccess;
}
static ncclResult_t getLoopInfo(struct ncclInfo* info) {
switch (info->pattern) {
case ncclPatternTreeUp:
case ncclPatternTreeDown:
case ncclPatternTreeUpDown:
case ncclPatternPipelineFrom:
case ncclPatternPipelineTo:
info->nstepsPerLoop = info-> nchunksPerLoop = 1; break;
case ncclPatternRing:
info->nstepsPerLoop = info->comm->nRanks-1; info->nchunksPerLoop = info->comm->nRanks; break;
case ncclPatternRingTwice:
info->nstepsPerLoop = 2*(info->comm->nRanks-1); info->nchunksPerLoop = info->comm->nRanks; break;
default:
WARN("Unknown pattern %d\n", info->pattern);
return ncclInternalError;
}
return ncclSuccess;
}
static ncclResult_t computeColl(struct ncclInfo* info /* input */, struct ncclColl* coll, struct ncclProxyArgs* proxyArgs /* output */) {
// Set nstepsPerLoop and nchunksPerLoop
NCCLCHECK(getAlgoInfo(info));
NCCLCHECK(getPatternInfo(info));
NCCLCHECK(getLoopInfo(info));
coll->args.root = info->root;
coll->args.N = info->count;
coll->args.ThisInput = info->sendbuff;
coll->args.ThisOutput = info->recvbuff;
coll->args.comm = info->comm->devComm;
coll->args.opCount = info->comm->opCount;
coll->args.nChannels = info->nChannels;
coll->args.nThreads = info->nThreads;
coll->funcIndex = FUNC_INDEX(info->coll, info->op, info->datatype, info->algorithm, info->protocol);
int stepSize = (info->protocol == NCCL_PROTO_LL ? NCCL_LL_BUFF_SIZE : info->protocol == NCCL_PROTO_LL128 ? NCCL_LL128_BUFF_SIZE : info->comm->channels[0].buffSize ) / NCCL_STEPS;
int chunkSteps = (info->protocol == NCCL_PROTO_SIMPLE && info->algorithm == NCCL_ALGO_RING) ? info->chunkSteps : 1;
int sliceSteps = (info->protocol == NCCL_PROTO_SIMPLE && info->algorithm == NCCL_ALGO_RING) ? info->sliceSteps : 1;
int chunkSize = stepSize*chunkSteps;
// Compute lastChunkSize
if (info->algorithm == NCCL_ALGO_TREE && info->protocol == NCCL_PROTO_SIMPLE) {
if (info->pattern == ncclPatternTreeUpDown) {
// Optimize chunkSize / nSteps
while (info->nBytes / (info->nChannels*chunkSize) < info->comm->channels[0].treeUp.depth*8 && chunkSize > 131072) chunkSize /= 2;
while (info->nBytes / (info->nChannels*chunkSize) < info->comm->channels[0].treeUp.depth*4 && chunkSize > 65536) chunkSize /= 2;
while (info->nBytes / (info->nChannels*chunkSize) < info->comm->channels[0].treeUp.depth && chunkSize > 32768) chunkSize /= 2;
}
// Use lastChunkSize as chunkSize
coll->args.lastChunkSize = chunkSize / ncclTypeSize(info->datatype);
} else if (info->protocol == NCCL_PROTO_LL) {
int sliceSize = NCCL_LL_SLICE_LINES * sizeof(uint64_t);
const ssize_t loopSize = info->nChannels*info->nchunksPerLoop*(ssize_t)sliceSize;
coll->args.lastChunkSize = DIVUP((info->nBytes-(info->nBytes/loopSize)*loopSize), info->nChannels*info->nchunksPerLoop);
ALIGN_SIZE(coll->args.lastChunkSize, info->nThreads*sizeof(uint64_t));
coll->args.lastChunkSize /= ncclTypeSize(info->datatype);
} else if (info->algorithm == NCCL_ALGO_TREE && info->protocol == NCCL_PROTO_LL128) {
int nstepsInter = 1+log2i(info->comm->nNodes);
while (info->nBytes / (info->nChannels*chunkSize) < nstepsInter*4 && chunkSize > 32768) chunkSize /= 2;
// Use lastChunkSize as chunkSize
coll->args.lastChunkSize = chunkSize*NCCL_LL128_DATAELEMS/(NCCL_LL128_LINEELEMS*ncclTypeSize(info->datatype));
}
// Compute nSteps for proxies
int chunkEffectiveSize = chunkSize;
if (info->protocol == NCCL_PROTO_LL) chunkEffectiveSize /= 2;
if (info->protocol == NCCL_PROTO_LL128) chunkEffectiveSize = (chunkSize / NCCL_LL128_LINEELEMS) * NCCL_LL128_DATAELEMS;
//if (info->comm->rank == 0) printf("Coll %d, size %ld -> %dx%d, chunkSize %d (algo %d proto%d)\n", info->coll, info->nBytes, info->nChannels, info->nThreads, chunkSize, info->algorithm, info->protocol);
int nLoops = (int)(DIVUP(info->nBytes, (((size_t)(info->nChannels))*info->nchunksPerLoop*chunkEffectiveSize)));
proxyArgs->nsteps = info->nstepsPerLoop * nLoops * chunkSteps;
proxyArgs->sliceSteps = sliceSteps;
proxyArgs->chunkSteps = chunkSteps;
proxyArgs->protocol = info->protocol;
proxyArgs->opCount = info->comm->opCount;
TRACE(NCCL_NET,"opCount %lx slicesteps %d spl %d cpl %d nbytes %zi -> protocol %d nchannels %d nthreads %d, nloops %d nsteps %d comm %p",
coll->args.opCount, proxyArgs->sliceSteps, info->nstepsPerLoop, info->nchunksPerLoop, info->nBytes, info->protocol, info->nChannels, info->nThreads,
nLoops, proxyArgs->nsteps, info->comm);
return ncclSuccess;
}
static ncclResult_t saveKernel(struct ncclInfo* info) {
if (info->comm->nRanks == 1) {
if (info->sendbuff != info->recvbuff)
return ncclSuccess;
}
struct ncclColl coll;
struct ncclProxyArgs proxyArgs;
memset(&proxyArgs, 0, sizeof(struct ncclProxyArgs));
NCCLCHECK(computeColl(info, &coll, &proxyArgs));
info->comm->myParams->blockDim.x = std::max<unsigned>(info->comm->myParams->blockDim.x, coll.args.nThreads);
if (info->comm->userStreamSet == false) {
info->comm->userStreamSet = true;
}
return ncclSuccess;
}
ncclResult_t ncclEnqueueCheck(struct ncclInfo* info) {
if (info->comm == NULL) return ncclInvalidArgument;
INFO(NCCL_COLL,"%s: opCount %lx sendbuff %p recvbuff %p count %zi datatype %d op %d root %d comm %p [nranks=%d] ",
info->opName, info->comm->opCount, info->sendbuff, info->recvbuff, info->count,
info->datatype, info->op, info->root, info->comm, info->comm->nRanks);
// Launch asynchronously if needed
if (ncclAsyncMode()) {
ncclResult_t ret = ncclSuccess;
int savedDev = -1;
if (info->comm->checkPointers) {
CUDACHECKGOTO(cudaGetDevice(&savedDev), ret, end);
CUDACHECKGOTO(cudaSetDevice(info->comm->cudaDev), ret, end);
}
// Check arguments
NCCLCHECKGOTO(ArgsCheck(info), ret, end);
// Always register comm even in case of error to make sure ncclGroupEnd
// cleans it up.
NCCLCHECKGOTO(ncclAsyncColl(info->comm), ret, end);
NCCLCHECKGOTO(saveKernel(info), ret, end);
end:
if (savedDev != -1) CUDACHECK(cudaSetDevice(savedDev));
ncclAsyncErrCheck(ret);
return ret;
} else {
NCCLCHECK(ArgsCheck(info));
NCCLCHECK(saveKernel(info));
NCCLCHECK(ncclBarrierEnqueue(info->comm));
NCCLCHECK(ncclBarrierEnqueueWait(info->comm));
NCCLCHECK(ncclEnqueueEvents(info->comm));
return ncclSuccess;
}
}
| [
"yuhenryt@intel.com"
] | yuhenryt@intel.com |
4fbd65c7141d1449374e08f3e781a17ef5095476 | ecf44d261c10f3b960618ed416c068b1fa24dfd1 | /adlik_serving/runtime/tensorrt/factory/trt_model_options.h | 061e122807f6933d3595145ec5a6834577f80b35 | [
"Apache-2.0"
] | permissive | zhaohainan666/Adlik | 64b4b7107288aee740584dc481ef485ad3300779 | 51e8c798720d1b9139fc9660a4fa40aa644ac451 | refs/heads/master | 2020-08-02T02:20:57.505665 | 2019-09-27T00:36:36 | 2019-09-27T00:36:36 | 211,206,303 | 1 | 0 | Apache-2.0 | 2019-09-27T00:48:56 | 2019-09-27T00:48:55 | null | UTF-8 | C++ | false | false | 383 | h | #ifndef ADLIK_SERVING_RUNTIME_TENSORRT_FACTORY_TRT_MODEL_OPTIONS_H
#define ADLIK_SERVING_RUNTIME_TENSORRT_FACTORY_TRT_MODEL_OPTIONS_H
#include "cub/base/fwddecl.h"
FWD_DECL_STRUCT(cub, ProgramOptions)
namespace tensorrt {
struct TrtModelOptions {
TrtModelOptions();
void subscribe(cub::ProgramOptions&);
private:
bool enableBatching;
};
} // namespace tensorrt
#endif
| [
"zhao.lufan30@zte.com.cn"
] | zhao.lufan30@zte.com.cn |
9dcea1920ceaa6fae3eef03494890a49aab2dcc9 | cf111b440f33ba9741ff45c60ac33dfade24e2ac | /Projects/Grafeo/shapes/text.h | de4f39a61e21a55e355bf90eaac2c28118c96294 | [
"Unlicense"
] | permissive | fredmorcos/attic | cd08e951f56c3b256899ef5ca4ccd030d3185bc1 | 36d5891a959cfc83f9eeef003b4e0b574dd7d7e1 | refs/heads/master | 2023-07-05T10:03:58.115062 | 2023-06-21T22:55:38 | 2023-06-22T07:07:58 | 154,962,425 | 4 | 1 | Unlicense | 2023-06-22T07:08:00 | 2018-10-27T12:30:38 | JavaScript | UTF-8 | C++ | false | false | 1,174 | h | /*
* This file is part of OpenGrafik.
*
* OpenGrafik 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.
*
* OpenGrafik 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 OpenGrafik. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TEXT_H
#define TEXT_H
#include "shape.h"
#include <QGraphicsTextItem>
class Text : public QGraphicsTextItem
{
Q_OBJECT
public:
Text(QGraphicsItem *parent = 0);
signals:
void selectedChange(QGraphicsItem *item);
void lostFocus(Text *item);
void linkActivated();
protected:
void focusOutEvent(QFocusEvent *event);
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
QVariant itemChange(GraphicsItemChange change, const QVariant &value);
};
#endif // TEXT_H
| [
"fred.morcos@gmail.com"
] | fred.morcos@gmail.com |
03b0194045804f73e74f0dcdfaec86439b482ec8 | 5a5fa9fcd0f6448a6f75cc2314781b47aaf64f02 | /src/Animation.cpp | e488345742105bcdc06561db9c4d739a7e576653 | [] | no_license | kevinamorim/FEUP-LAIG-TP2 | e4be0c616b70b0cc06b7807f01f59d036eef16ad | 73d337d17f5276de599320e806677fa1d43c7163 | refs/heads/master | 2021-01-10T19:57:05.419098 | 2016-02-19T14:00:38 | 2016-02-19T14:00:38 | 25,466,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,585 | cpp | #include "Animation.h"
// =======================
// Animation
// =======================
Animation::Animation(string id, float span)
{
this->id = id;
this->spanTime = span;
this->currentPos = new Point3d(0,0,0);
}
string Animation::getID()
{
return this->id;
}
bool Animation::Done()
{
return done;
}
Point3d * Animation::getCurrentPos()
{
return currentPos;
}
// =======================
// Linear Animation
// =======================
LinearAnimation::LinearAnimation(string id, float span, vector<Point3d *> controlPts) : Animation(id, span)
{
this->controlPoints = vector<Point3d *>();
this->direction = vector<Point3d *>();
this->distance = vector<float>();
this->numControlPoints = controlPts.size();
for(int i = 0; i < numControlPoints; i++)
{
// This is done so that new points are used
// (instead of the passed points, so that we don't access memory areas we're not supposed to be accessing)
Point3d * p = new Point3d();
p->setPoint3d(controlPts[i]);
controlPoints.push_back(p);
}
float totalDistance = 0;
// Let's calculate the direction vector and the distance between the control points
// (first will be ignored, for it is the starting point)
this->direction.push_back(new Point3d(0,0,0));
this->distance.push_back(0);
for(int i = 1; i < numControlPoints; i++)
{
float dist = Point3d::distance(controlPoints[i], controlPoints[i-1]);
Point3d * p = Point3d::subtract(controlPoints[i], controlPoints[i-1]);
// normalize
p->x /= dist;
p->y /= dist;
p->z /= dist;
this->direction.push_back(p);
this->distance.push_back(dist);
//cout << "Direction [" << i-1 << "->" << i << "] : " << this->direction.at(i) << endl;
//cout << " Distance [" << i-1 << "->" << i << "] : " << this->distance.at(i) << endl;
totalDistance += distance[i];
}
// constant object speed (u/s)
this->speed = totalDistance / spanTime;
this->currentPos = new Point3d();
this->currentPos->setPoint3d(controlPoints.at(0));
this->currentControl = 1;
this->currentRotation = getRotation();
this->inLoop = true;
this->reset();
}
void LinearAnimation::init(unsigned long t)
{
this->currentPos->setPoint3d(this->controlPoints.at(0));
this->currentControl = 1;
this->moved = 0;
this->currentRotation = getRotation();
this->oldTime = t;
this->restart = false;
this->done = false;
}
void LinearAnimation::draw()
{
if(!done)
{
glTranslatef(currentPos->x, currentPos->y, currentPos->z);
glRotatef(currentRotation->x, 0, 1, 0);
//glRotatef(currentRotation->y, 1, 0, 0);
}
}
void LinearAnimation::reset()
{
this->restart = true;
}
void LinearAnimation::update(unsigned long t)
{
if(restart)
{
init(t);
}
else
{
if(!done)
{
float deltaTime = (t - oldTime) * 0.001;
this->oldTime = t;
float deltaMovement = this->speed * deltaTime;
move(deltaMovement);
moved += deltaMovement;
if(moved >= distance[currentControl])
{
moved -= distance[currentControl];
currentPos->setPoint3d(controlPoints[currentControl]);
currentControl = (currentControl + 1) % numControlPoints;
if(currentControl == 0)
{
if(inLoop)
{
init(t);
}
else
{
done = true;
}
}
else
{
currentRotation = getRotation();
move(moved);
}
}
}
}
}
Point3d * LinearAnimation::getRotation()
{
float angleX, angleY, angleZ;
Point2d vecZ = Point2d(0, 1);
Point2d vecY = Point2d(direction[currentControl]->y, 1);
Point2d vecD = Point2d(direction[currentControl]->x, direction[currentControl]->z);
float cosX = Point2d::dotProduct(&vecZ, &vecD) / (vecZ.size() * vecD.size());
//float cosY = Point2d::dotProduct(&vecY, &vecZ) / (vecY.size() * vecZ.size());
angleX = 360 * acos(cosX) * 0.5 * INV_PI;
angleX *= (direction[currentControl]->z >= 0 && direction[currentControl]->x >= 0) ? 1 : -1;
//angleX = 0;
//angleY = 360 * acos(cosY) / (2 * PI);
//angleY *= (direction[currentControl]->y >= 0) ? -1 : 1; // the rotation in x will be anti-clockwise, therefore the angle must me inverted
angleY = 0;
angleZ = 0;
return new Point3d(angleX, angleY, angleZ);
}
void LinearAnimation::move(float distance)
{
this->currentPos->x += distance * direction[currentControl]->x;
this->currentPos->y += distance * direction[currentControl]->y;
this->currentPos->z += distance * direction[currentControl]->z;
}
// =======================
// Circular Animation
// =======================
CircularAnimation::CircularAnimation(string id, float span, Point3d * center, float radius, float startAng, float rotAng) : Animation(id, span)
{
this->center = new Point3d();
this->center->setPoint3d(center);
this->radius = radius;
this->startAngle = startAng;
this->rotateAngle = rotAng;
this->angularSpeed = (rotateAngle / spanTime); // angle/s
this->inLoop = true;
this->reset();
}
void CircularAnimation::init(unsigned long t)
{
this->currentRotate = startAngle;
this->currentPos->setPoint3d(getCurrentPos());
this->restart = false;
this->done = false;
this->oldTime = t;
}
void CircularAnimation::draw()
{
if(!done)
{
glTranslatef(center->x, center->y, center->z);
glRotatef(currentRotate, 0, 1, 0);
glTranslatef(radius, 0, 0);
}
}
void CircularAnimation::reset()
{
this->restart = true;
}
void CircularAnimation::update(unsigned long t)
{
if(restart)
{
init(t);
}
else
{
if(!done) // should not be called if done
{
float deltaTime = (t - oldTime) * 0.001;
this->oldTime = t;
currentRotate += angularSpeed * deltaTime;
if(abs(currentRotate) >= abs(startAngle + rotateAngle))
{
if(inLoop)
{
init(t);
}
else
{
this->done = true;
}
}
}
}
}
Point3d * CircularAnimation::getCurrentPos()
{
float angleDeg = startAngle + currentRotate;
float angleRad = angleDeg * 2 * PI / 360;
float x = center->x + radius * cos(angleRad);
float y = center->y;
float z = center->z + radius * sin(angleRad);
currentPos->setPoint3d(x, y, z);
return currentPos;
}
// =======================
// Composed Animation
// =======================
ComposedAnimation::ComposedAnimation(string id) : Animation(id, 0)
{
this->currentAnimation = 0;
this->numAnimations = 0;
this->animations = vector<Animation *>();
this->inLoop = true;
}
void ComposedAnimation::addAnimation(Animation* anim)
{
anim->inLoop = false; // required, else the sequence will not work and only one animation will be played
this->animations.push_back(anim);
numAnimations++;
//this->offsetPos = new Point3d(0,0,0);
this->reset();
}
void ComposedAnimation::init(unsigned long t)
{
this->currentAnimation = 0;
//offsetPos->setPoint3d(0,0,0);
this->animations[currentAnimation]->init(t);
this->done = false;
this->restart = false;
}
void ComposedAnimation::draw()
{
//glTranslatef(offsetPos->x, offsetPos->y, offsetPos->z);
animations[currentAnimation]->draw();
}
void ComposedAnimation::reset()
{
this->restart = true;
}
void ComposedAnimation::update(unsigned long t)
{
if(restart)
{
//cout << "restarting... " << endl;
init(t);
}
else
{
//cout << "updating animation... " << endl;
animations[currentAnimation]->update(t);
if(animations[currentAnimation]->Done())
{
//Point3d * p = animations[currentAnimation]->getCurrentPos();
//offsetPos->setPoint3d(p);
currentAnimation = (currentAnimation + 1) % numAnimations;
if(currentAnimation == 0)
{
if(inLoop)
{
init(t);
}
else
{
this->done = true;
}
}
else
{
this->animations[currentAnimation]->init(t);
}
}
}
}
| [
"lmaga801@gmail.com"
] | lmaga801@gmail.com |
7d30f7a6d87cbc9e558ddf70852df1a0bc69f199 | f1fd3b23ac060aeac7143e7c05d650912b83eb88 | /libcef_dll/ctocpp/life_span_handler_ctocpp.h | 736ae42a334c9af079a0a850d859afaaef6a204b | [
"BSD-3-Clause"
] | permissive | cloudscrape/cef | a8b99cedeaf3eafdc0de36701a13f3d4c84abb62 | 99bf1b8458b104b1bb8d2d24ce1691a248d77f37 | refs/heads/master | 2021-01-09T20:47:12.797880 | 2016-05-29T01:58:53 | 2016-05-29T02:00:28 | 60,127,479 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,976 | h | // Copyright (c) 2016 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.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#ifndef CEF_LIBCEF_DLL_CTOCPP_LIFE_SPAN_HANDLER_CTOCPP_H_
#define CEF_LIBCEF_DLL_CTOCPP_LIFE_SPAN_HANDLER_CTOCPP_H_
#pragma once
#ifndef BUILDING_CEF_SHARED
#pragma message("Warning: "__FILE__" may be accessed DLL-side only")
#else // BUILDING_CEF_SHARED
#include "include/cef_life_span_handler.h"
#include "include/capi/cef_life_span_handler_capi.h"
#include "include/cef_client.h"
#include "include/capi/cef_client_capi.h"
#include "libcef_dll/ctocpp/ctocpp.h"
// Wrap a C structure with a C++ class.
// This class may be instantiated and accessed DLL-side only.
class CefLifeSpanHandlerCToCpp
: public CefCToCpp<CefLifeSpanHandlerCToCpp, CefLifeSpanHandler,
cef_life_span_handler_t> {
public:
CefLifeSpanHandlerCToCpp();
// CefLifeSpanHandler methods.
bool OnBeforePopup(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,
const CefString& target_url, const CefString& target_frame_name,
WindowOpenDisposition target_disposition, bool user_gesture,
const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo,
CefRefPtr<CefClient>& client, CefBrowserSettings& settings,
bool* no_javascript_access) override;
void OnAfterCreated(CefRefPtr<CefBrowser> browser) override;
bool DoClose(CefRefPtr<CefBrowser> browser) override;
void OnBeforeClose(CefRefPtr<CefBrowser> browser) override;
};
#endif // BUILDING_CEF_SHARED
#endif // CEF_LIBCEF_DLL_CTOCPP_LIFE_SPAN_HANDLER_CTOCPP_H_
| [
"magreenblatt@gmail.com"
] | magreenblatt@gmail.com |
033b0fe33ec5e9c4cc82220b9d52a2f39c208cc5 | 7ea37716cff11c15fed0774ea9b1ae56708adcf3 | /tests/core/misc_tests.cpp | 9dbca4c55e9bbc3ee2b165699569142cf072dabf | [
"Apache-2.0"
] | permissive | tlemo/darwin | ee9ad08f18c6cda057fe4d3f14347ba2aa228b5b | 669dd93f931e33e501e49155d4a7ba09297ad5a9 | refs/heads/master | 2022-03-08T14:45:17.956167 | 2021-04-16T23:07:58 | 2021-04-16T23:07:58 | 157,114,747 | 105 | 21 | Apache-2.0 | 2021-02-09T18:15:23 | 2018-11-11T19:46:24 | C++ | UTF-8 | C++ | false | false | 1,595 | cpp | // Copyright 2018 The Darwin Neuroevolution Framework 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 <third_party/gtest/gtest.h>
#include <random>
namespace misc_tests {
// a quick sanity check for std::random_device
//
// 1. https://en.cppreference.com/w/cpp/numeric/random/random_device
// 2. http://www.pcg-random.org/posts/cpps-random_device.html
//
// current versions of MinGW ship with a broken implementation which returns
// a deterministic sequence of values, which defeats the random_device's purpose
// (https://sourceforge.net/p/mingw-w64/bugs/338)
//
// NOTE: yes, technically std::random_device is permitted to be pseudo-random,
// although there's no excuse to degrade to that on a general purpose platform
//
TEST(StandardLibraryTest, RandomDevice) {
std::random_device rd_1;
std::random_device rd_2;
// with a decent random_device implementation, the chance of a collision
// should be 1 / 2^32 (assuming 32bit integers)
EXPECT_NE(rd_1(), rd_2()) << "Sorry, you have a useless std::random_device";
}
} // namespace misc_tests
| [
"lemo1234@gmail.com"
] | lemo1234@gmail.com |
395a1a03538af63737c2ea660ee2fbc09167a720 | c90ada5ac6154ef204cd1638069396abefe4e0a1 | /NihavGameEngine/source/Library.Shared/EngineModule.h | 559f5603e4cb61665945383e6e3f3d7326d31bf0 | [] | no_license | Nihav-Jain/NihavGameEngine | c85d81bf521bf920ec7762465d23e90506ff757f | 6b62d4a713153da31c195691b63225805a7daed1 | refs/heads/master | 2021-01-17T11:52:20.984861 | 2017-01-21T23:01:24 | 2017-01-21T23:01:24 | 49,788,949 | 1 | 0 | null | 2016-03-20T23:38:55 | 2016-01-16T20:04:45 | C++ | UTF-8 | C++ | false | false | 844 | h | #pragma once
#include "RTTI.h"
#include "Factory.h"
namespace Library
{
class EngineModule : public RTTI
{
RTTI_DECLARATIONS(EngineModule, RTTI);
public:
EngineModule();
virtual ~EngineModule();
virtual void Activate() {};
virtual void Deactivate() {};
friend class Engine;
};
#define CONCRETE_MODULE_FACTORY(ConcreteModuleType) CONCRETE_FACTORY(ConcreteModuleType, EngineModule);
#define ENGINE_MODULE_DECLARATIONS() \
public: \
static const Library::Hashmap<const std::uint64_t*, EngineModule**>::Iterator Itr;
#define ENGINE_MODULE_DEFINITIONS(ModuleType, PointerToTypeId, PointerToSingletonPtr) \
const Library::Hashmap<const std::uint64_t*, EngineModule**>::Iterator ModuleType::Itr = Engine::ModuleList().Insert(PointerToTypeId, reinterpret_cast<EngineModule**>(PointerToSingletonPtr));
}
| [
"njain@fiea.ucf.edu"
] | njain@fiea.ucf.edu |
d6224c098750f0fa43f37b968b864aeb9721dd80 | 560090526e32e009e2e9331e8a2b4f1e7861a5e8 | /Compiled/blaze-3.2/blazetest/src/mathtest/dmatdmatsub/M4x4aMDa.cpp | b52a8757bec1b92c661c3528fce6e4d28b13519a | [
"BSD-3-Clause"
] | permissive | jcd1994/MatlabTools | 9a4c1f8190b5ceda102201799cc6c483c0a7b6f7 | 2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1 | refs/heads/master | 2021-01-18T03:05:19.351404 | 2018-02-14T02:17:07 | 2018-02-14T02:17:07 | 84,264,330 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,697 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dmatdmatsub/M4x4aMDa.cpp
// \brief Source file for the M4x4aMDa dense matrix/dense matrix subtraction math test
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/StaticMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'M4x4aMDa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
typedef blaze::StaticMatrix<TypeA,4UL,4UL> M4x4a;
typedef blaze::DynamicMatrix<TypeA> MDa;
// Creator type definitions
typedef blazetest::Creator<M4x4a> CM4x4a;
typedef blazetest::Creator<MDa> CMDa;
// Running the tests
RUN_DMATDMATSUB_OPERATION_TEST( CM4x4a(), CMDa( 4UL, 4UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"jonathan.doucette@alumni.ubc.ca"
] | jonathan.doucette@alumni.ubc.ca |
4f1980f95498d33ca2ae98923bf5cd45fbac6092 | 4c09b31b9761710ae8065c613d56f0d7a3c87fb0 | /AI Learing/EasyPR-DLL-CSharp/TEST/Stdafx.cpp | 78588f8e67f3b609799772772612fa69574153f9 | [
"Apache-2.0"
] | permissive | hurrybill/GIT | 4d67c63fab5e4b005a75ae13e08bd51ffa97a3d9 | 886659e4d547c6f996437f732ed0ba3adc2874d5 | refs/heads/master | 2021-09-10T06:34:56.930462 | 2018-03-21T15:57:11 | 2018-03-21T15:57:11 | 126,044,072 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 156 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// TEST.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
| [
"hurrybill@163.com"
] | hurrybill@163.com |
067fb052816ea9094fcd2959d72fd4ab63dbca0a | e01d6c4d183a3d712573f6345a45b78b80d35f75 | /mkrdfile.cpp | 1d52c085a515e533e9b159a957c3a89c7b5673fe | [] | no_license | IanGray/Comp11TestGenerator | 903cdf352630d4cddda607001f93a8ef664cac45 | b9e61dc1eff716780385983121cba5359e279f60 | refs/heads/master | 2021-01-16T21:19:58.594407 | 2013-12-02T19:55:56 | 2013-12-02T19:55:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 822 | cpp | #include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
srand(time(0));
int count = 0;
int num = 0;
int temp = 0;
int day = 0;
string type;
cin >> num;
for(char a = 'a'; a <= 'z'; a++){
for(char b = 'a'; b <= 'z'; b++){
for(char c = 'a'; c <= 'z'; c++){
if(count++ >= num) break;
cout << "RQ " << a << b << c << " ";
temp = rand() % 3;
if(temp == 0){
type = "hi";
}
else if(temp == 1){
type = "lo";
}
else{
type = "any";
}
// change mod value to higher than 12 to get "bad number
// errors
cout << (rand() % 13) << " " << type << " ";
day = ((rand() % 10));
if(day <= 6){
cout << day << endl;
}
else{
cout << "any" << endl;
}
}
}
}
cout << "PR all QU";
}
| [
"Ian.Gray@tufts.edu"
] | Ian.Gray@tufts.edu |
5d718293cdb87687b2110f543f022c44aafe77fa | 722dbd1d338eb5f1dc7a4400c80a5573668a73a5 | /Tools/Editor/GameClientWidget.h | 6d9165e65efa7ee89687a64d349c3682210e1123 | [] | no_license | hamfirst/LD44 | a89ffff07489d204a5b0ad7dae70006adfb6f58b | 07daf301b65aa77299861afd37cb0ee135352ab1 | refs/heads/master | 2022-12-23T04:34:15.859103 | 2021-01-24T21:33:17 | 2021-01-24T21:33:17 | 183,854,134 | 0 | 0 | null | 2022-12-08T23:54:18 | 2019-04-28T04:07:20 | C | UTF-8 | C++ | false | false | 1,547 | h | #pragma once
#include <QOpenGLWidget>
#include "Foundation/Time/FrameClock.h"
#include "Engine/Window/FakeWindow.h"
#include "Engine/Rendering/RenderState.h"
#include "Project/GameShared/Level/GameLevelList.h"
#include "Project/GameShared/Level/GameStageManager.h"
#include "GameClient/GameContainer.h"
class EditorContainer;
class GameClientWidget : public QOpenGLWidget
{
Q_OBJECT
public:
GameClientWidget(EditorContainer * editor, int client_index, bool bot_game, QWidget *parent = Q_NULLPTR);
~GameClientWidget();
protected:
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
void showEvent(QShowEvent * ev) override;
void closeEvent(QCloseEvent * ev) override;
void keyPressEvent(QKeyEvent * event) override;
void keyReleaseEvent(QKeyEvent * event) override;
void mousePressEvent(QMouseEvent * event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent * event) override;
void moveEvent(QMoveEvent * event) override;
void wheelEvent(QWheelEvent * event) override;
void focusInEvent(QFocusEvent * event) override;
void focusOutEvent(QFocusEvent * event) override;
void enterEvent(QEvent * event) override;
void leaveEvent(QEvent * event) override;
void Update();
private:
NotNullPtr<EditorContainer> m_Editor;
Optional<FakeWindow> m_FakeWindow;
Optional<GameContainer> m_GameContainer;
DelegateLink<void> m_UpdateDelegate;
int m_ClientIndex;
bool m_BotGame;
bool m_ImeMode = false;
};
| [
"nick.weihs@gmail.com"
] | nick.weihs@gmail.com |
b6927a843936b32f9235a698eb1f43e010ee8968 | 524dc82e0ee3ad0c67779bdc5a6a3688edd54a11 | /include/PVX_Math3D.h | b680df50ae58b9d93b77440a1534ce89a372d397 | [] | no_license | nmpasdekis/PVX_General | da7e1a4b3a49076eccf88341aefe88533aabe138 | eb06c57c42a8bdef17235a03ec9c4149c1926f89 | refs/heads/master | 2020-08-05T03:13:11.694280 | 2020-02-12T07:13:44 | 2020-02-12T07:13:44 | 212,371,792 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67,155 | h | #pragma once
#include <xmmintrin.h>
#include <cmath>
#include <utility>
namespace PVX {
constexpr double PI = 3.14159265358979323846;
#pragma intrinsic(sinf, cosf)
constexpr float ToRAD(float x) { return ((float)(x*PI/180.0)); }
constexpr float ToDEGREES(float x) { return ((float)(x*180.0/PI)); }
union ucVector2D {
struct {
unsigned char r, g;
};
struct {
unsigned char x, y;
};
struct {
unsigned char u, v;
};
unsigned short Word;
unsigned char Array[2];
};
union ucVector3D {
struct {
unsigned char r, g, b;
};
struct {
unsigned char _b, _g, _r;
};
struct {
unsigned char x, y, z;
};
unsigned char Array[3];
};
union ucVector4D {
struct {
unsigned char r, g, b, a;
};
struct {
unsigned char x, y, z, w;
};
unsigned char Array[4];
unsigned int dWord;
};
union cVector2D {
struct {
char r, g;
};
struct {
char x, y;
};
unsigned short Word;
char Array[2];
};
union cVector3D {
struct {
char r, g, b;
};
struct {
char x, y, z;
};
char Array[3];
};
union cVector4D {
struct {
char r, g, b, a;
};
struct {
char x, y, z, w;
};
char Array[4];
unsigned int dWord;
};
union Vector2D {
enum Traits {
HasX = true,
HasY = true,
HasZ = false,
HasW = false
};
//Vector2D() :x{ 0 }, y{ 0 }{}
Vector2D() = default;
Vector2D(float x, float y) : x{ x }, y{ y } {}
struct {
float x, y;
};
struct {
float u, v;
};
struct {
float Width, Height;
};
float Array[2];
inline Vector2D operator-() const { return Vector2D{ -x, -y }; }
inline float Length() const { return sqrtf(x*x+y*y); }
inline float Length2() const { return (x*x+y*y); }
inline float Dot(const Vector2D& v) const { return x*v.x + y*v.y; }
inline Vector2D& Normalize() { float w = 1.0f / Length(); x *= w; y *= w; return *this; }
inline Vector2D Normalized() const { float w = 1.0f / Length(); return{ x * w, y * w }; }
inline float Cross(const Vector2D& v2) { return x*v2.y - y*v2.x; }
};
union Vector3D {
enum Traits {
HasX = true,
HasY = true,
HasZ = true,
HasW = false
};
Vector3D() = default;
//Vector3D() : x{ 0 }, y{ 0 }, z{ 0 } {}
Vector3D(float x, float y, float z) : x{ x }, y{ y }, z{ z } {}
struct {
float x, y, z;
};
struct {
float r, g, b;
};
struct {
float b, g, r;
} BGR;
struct {
float Pitch, Yaw, Roll;
};
struct {
float H, L, S;
};
struct {
float Width, Height, Depth;
};
float Array[3];
inline Vector3D operator-() const { return Vector3D{ -x, -y, -z }; }
inline float Length() const { return sqrtf(x*x+y*y+z*z); }
inline float Length2() const { return (x*x+y*y+z*z); }
inline float Dot(const Vector3D& v) const { return x*v.x + y*v.y+z*v.z; }
inline Vector3D& Normalize() { float w = 1.0f / Length(); x *= w; y *= w; z *= w; return *this; }
inline Vector3D Normalized() const { float w = 1.0f / Length(); return{ x * w, y * w, z * w }; }
inline Vector3D Cross(const Vector3D& v) const { return { y* v.z - z*v.y, v.x* z - v.z*x, x* v.y - y*v.x }; }
};
__declspec(align(16))
union Vector4D {
enum Traits {
HasX = true,
HasY = true,
HasZ = true,
HasW = true
};
Vector4D() = default;
//Vector4D() : x{ 0 }, y{ 0 }, z{ 0 }, w{ 0 } {}
Vector4D(float x, float y, float z, float w) : x{ x }, y{ y }, z{ z }, w{ w } {}
struct {
float x, y, z, w;
};
struct {
float r, g, b, a;
};
struct {
Vector3D Vec3;
float Scalar;
};
struct {
float Width, Height, Depth, Imagination;
};
float Array[4];
inline Vector4D operator-() const { return Vector4D{ -x, -y, -z, -w }; }
inline float Length() const { return sqrtf(x*x+y*y+z*z+w*w); }
inline float Length2() const { return (x*x+y*y+z*z+w*w); }
inline float Dot(const Vector4D& v) const { return x*v.x + y*v.y+z*v.z+w*v.w; }
inline Vector4D& Normalize() { float i = 1.0f / Length(); x *= i; y *= i; z *= i; w *= i; return *this; }
inline Vector4D Normalized() const { float i = 1.0f / Length(); return{ x * i, y * i, z * i, w * i }; }
};
//////////////////////////////////////////////////////////////////////////////
union iVector2D {
struct {
int x, y;
};
struct {
int u, v;
};
struct {
int Width, Height;
};
int Array[2];
inline iVector2D operator-() const { return iVector2D{ -x, -y }; }
};
union iVector3D {
struct {
int x, y, z;
};
struct {
int r, g, b;
};
struct {
int Pitch, Yaw, Roll;
};
struct {
int Width, Height, Depth;
};
int Array[3];
inline iVector3D operator-() const { return iVector3D{ -x, -y, -z }; }
};
__declspec(align(16))
union iVector4D {
struct {
int x, y, z, w;
};
struct {
int r, g, b, a;
};
struct {
Vector3D Vec3;
int Scalar;
};
struct {
int Width, Height, Depth, Imagination;
};
int Array[4];
inline iVector4D operator-() const { return iVector4D{ -x, -y, -z, -w }; }
};
//////////////////////////////////////////////////////////////////////////////
union Rect2D {
struct {
float x, y, Width, Height;
};
Vector4D Vec4;
float Array[4];
};
union Quaternion {
float Array[4];
struct {
float i, j, k, r;
};
Vector4D Vec;
inline Quaternion& Normalize() {
float w = 1.0f / sqrtf(i*i + j*j + k * k + r * r);
i *= w;
j *= w;
k *= w;
r *= w;
return *this;
}
inline Quaternion Normalized() const {
float w = 1.0f / sqrtf(i*i + j*j + k * k + r * r);
return { i * w, j * w, k * w, r * w };
}
};
union DualQuaternion {
float Array[8];
struct {
Quaternion Real, Dual;
};
Quaternion q[2];
struct {
float r_i, r_j, r_k, r_r, d_i, d_j, d_k, d_r;
};
inline DualQuaternion& Normalize() {
float l = 1.0f / Real.Vec.Length();
Real.Vec.x *= l;
Real.Vec.y *= l;
Real.Vec.z *= l;
Real.Vec.w *= l;
Dual.Vec.x *= l;
Dual.Vec.y *= l;
Dual.Vec.z *= l;
Dual.Vec.w *= l;
return *this;
}
inline DualQuaternion Normalized(DualQuaternion& q) const {
float l = 1.0f / Real.Vec.Length();
return {
Real.Vec.x * l,
Real.Vec.y * l,
Real.Vec.z * l,
Real.Vec.w * l,
Dual.Vec.x * l,
Dual.Vec.y * l,
Dual.Vec.z * l,
Dual.Vec.w * l
};
}
};
#pragma warning(disable:4201)
union Matrix4x4 {
Matrix4x4() = default;
float m[4][4];
float m16[16];
struct {
float m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33;
};
struct {
Vector4D Vec0, Vec1, Vec2, Vec3;
};
Vector4D m4[4];
static constexpr Matrix4x4 Identity() {
return {
1.0f, 0, 0, 0,
0, 1.0f, 0, 0,
0, 0, 1.0f, 0,
0, 0, 0, 1.0f
};
}
template<typename T, typename std::enable_if_t<T::Traits::HasZ, int> = 0>
inline void TranslateBefore(const T& p) {
m30 = -p.x * m00 + p.y * m10 + p.z * m20;
m31 = -p.x * m01 + p.y * m11 + p.z * m21;
m32 = -p.x * m02 + p.y * m12 + p.z * m22;
}
template<typename T, typename std::enable_if_t<T::Traits::HasZ, int> = 0>
inline void MatStoreX(const T& vec){
m00=(vec).x;
m10=(vec).y;
m20=(vec).z;
}
template<typename T, typename std::enable_if_t<T::Traits::HasZ, int> = 0>
inline void MatStoreY(const T& vec) {
m01 = (vec).x;
m11 = (vec).y;
m21 = (vec).z;
}
template<typename T, typename std::enable_if_t<T::Traits::HasZ, int> = 0>
inline void MatStoreZ(const T& vec) {
m02 = (vec).x;
m12 = (vec).y;
m22 = (vec).z;
}
};
union Matrix3x3 {
float m[3][3];
float m9[9];
struct {
float m00, m01, m02,
m10, m11, m12,
m20, m21, m22;
};
Vector3D m3[3];
struct {
Vector3D v0, v1, v2;
};
static constexpr Matrix3x3 Identity() {
return {
1.0f, 0, 0,
0, 1.0f, 0,
0, 0, 1.0f
};
}
};
union Matrix3x4 {
float m[3][4];
float m_12[12];
struct {
float m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23;
};
struct {
Vector4D Vec0, Vec1, Vec2;
};
Vector4D m3[3];
static constexpr Matrix3x4 Identity() {
return {
1.0f, 0, 0, 0,
0, 1.0f, 0, 0,
0, 0, 1.0f, 0
};
}
};
union Matrix2x2 {
float m[2][2];
float m4[4];
struct {
float m00, m01,
m10, m11;
};
Vector2D m2[2];
struct {
Vector2D v0, v1;
};
static constexpr Matrix2x2 Identity() {
return {
1.0f, 0,
0, 1.0f
};
}
};
struct Ray {
Vector3D Position;
Vector3D Direction;
};
struct Ray2D {
Vector2D Position;
Vector2D Direction;
};
struct Weight {
float W[4];
unsigned char I[4];
};
struct Plane {
Vector3D Normal;
float Distance;
};
union AABB {
struct {
Vector3D Min, Max;
};
float Array[6];
};
union Triangle {
int Index[3];
struct {
int Index0, Index1, Index2;
};
};
union Quad {
int Index[4];
struct {
int Index0, Index1, Index2, Index3;
};
};
#define DET3(m00, m01, m02, m10, m11, m12, m20, m21, m22) \
(\
((m00)*((m11)*(m22)-(m21)*(m12))) - \
((m01)*((m10)*(m22)-(m20)*(m12))) + \
((m02)*((m10)*(m21)-(m20)*(m11))) \
)
#define DET4_00(m) DET3(\
/*(m).m00, (m).m01, (m).m02, (m).m03,*/ \
/*(m).m10,*/ (m).m11, (m).m12, (m).m13, \
/*(m).m20,*/ (m).m21, (m).m22, (m).m23, \
/*(m).m30,*/ (m).m31, (m).m32, (m).m33 \
)
#define DET4_01(m) DET3(\
/*(m).m00, (m).m01, (m).m02, (m).m03,*/ \
(m).m10, /*(m).m11,*/ (m).m12, (m).m13, \
(m).m20, /*(m).m21,*/ (m).m22, (m).m23, \
(m).m30, /*(m).m31,*/ (m).m32, (m).m33 \
)
#define DET4_02(m) DET3(\
/*(m).m00, (m).m01, (m).m02, (m).m03,*/ \
(m).m10, (m).m11, /*(m).m12,*/ (m).m13, \
(m).m20, (m).m21, /*(m).m22,*/ (m).m23, \
(m).m30, (m).m31, /*(m).m32,*/ (m).m33 \
)
#define DET4_03(m) DET3(\
/*(m).m00, (m).m01, (m).m02, (m).m03,*/ \
(m).m10, (m).m11, (m).m12, /*(m).m13,*/ \
(m).m20, (m).m21, (m).m22, /*(m).m23,*/ \
(m).m30, (m).m31, (m).m32, /*(m).m33)*/ \
)
#define DET4_10(m) DET3(\
/*(m).m00,*/ (m).m01, (m).m02, (m).m03, \
/*(m).m10, (m).m11, (m).m12, (m).m13,*/\
/*(m).m20,*/ (m).m21, (m).m22, (m).m23, \
/*(m).m30,*/ (m).m31, (m).m32, (m).m33 \
)
#define DET4_11(m) DET3(\
(m).m00, /*(m).m01,*/ (m).m02, (m).m03, \
/*(m).m10, (m).m11, (m).m12, (m).m13,*/\
(m).m20, /*(m).m21,*/ (m).m22, (m).m23, \
(m).m30, /*(m).m31,*/ (m).m32, (m).m33 \
)
#define DET4_12(m) DET3(\
(m).m00, (m).m01, /*(m).m02,*/ (m).m03, \
/*(m).m10, (m).m11, (m).m12, (m).m13,*/\
(m).m20, (m).m21, /*(m).m22,*/ (m).m23, \
(m).m30, (m).m31, /*(m).m32,*/ (m).m33 \
)
#define DET4_13(m) DET3(\
(m).m00, (m).m01, (m).m02, /*(m).m03,*/ \
/*(m).m10, (m).m11, (m).m12, (m).m13,*/ \
(m).m20, (m).m21, (m).m22, /*(m).m23,*/ \
(m).m30, (m).m31, (m).m32, /*(m).m33)*/ \
)
#define DET4_20(m) DET3(\
/*(m).m00,*/ (m).m01, (m).m02, (m).m03, \
/*(m).m10,*/ (m).m11, (m).m12, (m).m13, \
/*(m).m20, (m).m21, (m).m22, (m).m23,*/ \
/*(m).m30,*/ (m).m31, (m).m32, (m).m33 \
)
#define DET4_21(m) DET3(\
(m).m00, /*(m).m01,*/ (m).m02, (m).m03, \
(m).m10, /*(m).m11,*/ (m).m12, (m).m13, \
/*(m).m20, (m).m21, (m).m22, (m).m23,*/ \
(m).m30, /*(m).m31,*/ (m).m32, (m).m33 \
)
#define DET4_22(m) DET3(\
(m).m00, (m).m01, /*(m).m02,*/ (m).m03, \
(m).m10, (m).m11, /*(m).m12,*/ (m).m13, \
/*(m).m20, (m).m21, (m).m22, (m).m23,*/ \
(m).m30, (m).m31, /*(m).m32,*/ (m).m33 \
)
#define DET4_23(m) DET3(\
(m).m00, (m).m01, (m).m02, /*(m).m03,*/ \
(m).m10, (m).m11, (m).m12, /*(m).m13,*/ \
/*(m).m20, (m).m21, (m).m22, (m).m23,*/ \
(m).m30, (m).m31, (m).m32, /*(m).m33)*/ \
)
#define DET4_30(m) DET3(\
/*(m).m00,*/ (m).m01, (m).m02, (m).m03, \
/*(m).m10,*/ (m).m11, (m).m12, (m).m13, \
/*(m).m20,*/ (m).m21, (m).m22, (m).m23, \
/*(m).m30, (m).m31, (m).m32, (m).m33*/ \
)
#define DET4_31(m) DET3(\
(m).m00, /*(m).m01,*/ (m).m02, (m).m03, \
(m).m10, /*(m).m11,*/ (m).m12, (m).m13, \
(m).m20, /*(m).m21,*/ (m).m22, (m).m23, \
/*(m).m30, (m).m31, (m).m32, (m).m33*/ \
)
#define DET4_32(m) DET3(\
(m).m00, (m).m01, /*(m).m02,*/ (m).m03, \
(m).m10, (m).m11, /*(m).m12,*/ (m).m13, \
(m).m20, (m).m21, /*(m).m22,*/ (m).m23, \
/*(m).m30, (m).m31, (m).m32, (m).m33*/ \
)
#define DET4_33(m) DET3(\
(m).m00, (m).m01, (m).m02, /*(m).m03,*/ \
(m).m10, (m).m11, (m).m12, /*(m).m13,*/ \
(m).m20, (m).m21, (m).m22, /*(m).m23,*/ \
/*(m).m30, (m).m31, (m).m32, (m).m33)*/ \
)
#define DET4(m) (\
(m).m00 * DET4_00(m)\
-(m).m01 * DET4_01(m)\
+(m).m02 * DET4_02(m)\
-(m).m03 * DET4_03(m)\
)
inline float MatrixDet4(const Matrix4x4& m) {
char Comb[24][5] = {
{ 0, 1, 2, 3, 1 },
{ 1, 0, 2, 3, -1 },
{ 0, 2, 1, 3, -1 },
{ 2, 0, 1, 3, 1 },
{ 1, 2, 0, 3, 1 },
{ 2, 1, 0, 3, -1 },
{ 0, 1, 3, 2, -1 },
{ 1, 0, 3, 2, 1 },
{ 0, 3, 1, 2, 1 },
{ 3, 0, 1, 2, -1 },
{ 1, 3, 0, 2, -1 },
{ 3, 1, 0, 2, 1 },
{ 0, 2, 3, 1, 1 },
{ 2, 0, 3, 1, -1 },
{ 0, 3, 2, 1, -1 },
{ 3, 0, 2, 1, 1 },
{ 2, 3, 0, 1, 1 },
{ 3, 2, 0, 1, -1 },
{ 1, 2, 3, 0, -1 },
{ 2, 1, 3, 0, 1 },
{ 1, 3, 2, 0, 1 },
{ 3, 1, 2, 0, -1 },
{ 2, 3, 1, 0, -1 },
{ 3, 2, 1, 0, 1 },
};
float sum = 0, mul;
int i, j;
for (i = 0; i < 24; i++) {
mul = Comb[i][4];
for (j = 0; j < 4; j++) {
mul *= m.m[j][Comb[i][j]];
}
sum += mul;
}
return(sum);
}
inline void sincosf(float d, float* sin, float* cos) {
(*sin) = sinf(d);
(*cos) = cosf(d);
}
inline Matrix4x4& RotateXYZ(Matrix4x4& ypr, Vector3D& r) {
float cy = cosf(r.Yaw);
float sy = sinf(r.Yaw);
float cp = cosf(r.Pitch);
float sp = sinf(r.Pitch);
float cr = cosf(r.Roll);
float sr = sinf(r.Roll);
ypr.m00 = cr*cy;
ypr.m01 = cy*sr;
ypr.m02 = -sy;
ypr.m03 = 0;
ypr.m10 = cr*sp*sy - cp*sr;
ypr.m11 = cp*cr + sp*sr*sy;
ypr.m12 = cy*sp;
ypr.m13 = 0;
ypr.m20 = sp*sr + cp*cr*sy;
ypr.m21 = cp*sr*sy - cr*sp;
ypr.m22 = cp*cy;
ypr.m23 = 0;
ypr.m30 = 0;
ypr.m31 = 0;
ypr.m32 = 0;
ypr.m33 = 1;
return ypr;
}
inline Matrix4x4& RotateXZY(Matrix4x4& ypr, Vector3D& r) {
float cy = cosf(r.Yaw);
float sy = sinf(r.Yaw);
float cp = cosf(r.Pitch);
float sp = sinf(r.Pitch);
float cr = cosf(r.Roll);
float sr = sinf(r.Roll);
ypr.m00 = cr*cy;
ypr.m01 = sr;
ypr.m02 = -cr*sy;
ypr.m03 = 0;
ypr.m10 = sp*sy - cp*cy*sr;
ypr.m11 = cp*cr;
ypr.m12 = cy*sp + cp*sr*sy;
ypr.m13 = 0;
ypr.m20 = cp*sy + cy*sp*sr;
ypr.m21 = -cr*sp;
ypr.m22 = cp*cy - sp*sr*sy;
ypr.m23 = 0;
ypr.m30 = 0;
ypr.m31 = 0;
ypr.m32 = 0;
ypr.m33 = 1;
return ypr;
}
inline Matrix4x4& RotateYXZ(Matrix4x4& ypr, Vector3D& r) {
float cy = cosf(r.Yaw);
float sy = sinf(r.Yaw);
float cp = cosf(r.Pitch);
float sp = sinf(r.Pitch);
float cr = cosf(r.Roll);
float sr = sinf(r.Roll);
ypr.m00 = cr*cy - sp*sr*sy;
ypr.m01 = cy*sr + cr*sp*sy;
ypr.m02 = -cp*sy;
ypr.m03 = 0;
ypr.m10 = -cp*sr;
ypr.m11 = cp*cr;
ypr.m12 = sp;
ypr.m13 = 0;
ypr.m20 = cr*sy + cy*sp*sr;
ypr.m21 = sr*sy - cr*cy*sp;
ypr.m22 = cp*cy;
ypr.m23 = 0;
ypr.m30 = 0;
ypr.m31 = 0;
ypr.m32 = 0;
ypr.m33 = 1;
return ypr;
}
inline Matrix4x4& RotateYZX(Matrix4x4& ypr, Vector3D& r) {
float cy = cosf(r.Yaw);
float sy = sinf(r.Yaw);
float cp = cosf(r.Pitch);
float sp = sinf(r.Pitch);
float cr = cosf(r.Roll);
float sr = sinf(r.Roll);
ypr.m00 = cr*cy;
ypr.m01 = sp*sy + cp*cy*sr;
ypr.m02 = cy*sp*sr - cp*sy;
ypr.m03 = 0;
ypr.m10 = -sr;
ypr.m11 = cp*cr;
ypr.m12 = cr*sp;
ypr.m13 = 0;
ypr.m20 = cr*sy;
ypr.m21 = cp*sr*sy - cy*sp;
ypr.m22 = cp*cy + sp*sr*sy;
ypr.m23 = 0;
ypr.m30 = 0;
ypr.m31 = 0;
ypr.m32 = 0;
ypr.m33 = 1;
return ypr;
}
inline Matrix4x4& RotateZXY(Matrix4x4& ypr, Vector3D& r) {
float cy = cosf(r.Yaw);
float sy = sinf(r.Yaw);
float cp = cosf(r.Pitch);
float sp = sinf(r.Pitch);
float cr = cosf(r.Roll);
float sr = sinf(r.Roll);
ypr.m00 = cr*cy + sp*sr*sy;
ypr.m01 = cp*sr;
ypr.m02 = cy*sp*sr - cr*sy;
ypr.m03 = 0;
ypr.m10 = cr*sp*sy - cy*sr;
ypr.m11 = cp*cr;
ypr.m12 = sr*sy + cr*cy*sp;
ypr.m13 = 0;
ypr.m20 = cp*sy;
ypr.m21 = -sp;
ypr.m22 = cp*cy;
ypr.m23 = 0;
ypr.m30 = 0;
ypr.m31 = 0;
ypr.m32 = 0;
ypr.m33 = 1;
return ypr;
}
inline Matrix4x4& RotateZYX(Matrix4x4& ypr, Vector3D& r) {
float cy = cosf(r.Yaw);
float sy = sinf(r.Yaw);
float cp = cosf(r.Pitch);
float sp = sinf(r.Pitch);
float cr = cosf(r.Roll);
float sr = sinf(r.Roll);
ypr.m00 = cr*cy;
ypr.m01 = cp*sr + cr*sp*sy;
ypr.m02 = sp*sr - cp*cr*sy;
ypr.m03 = 0;
ypr.m10 = -cy*sr;
ypr.m11 = cp*cr - sp*sr*sy;
ypr.m12 = cr*sp + cp*sr*sy;
ypr.m13 = 0;
ypr.m20 = sy;
ypr.m21 = -cy*sp;
ypr.m22 = cp*cy;
ypr.m23 = 0;
ypr.m30 = 0;
ypr.m31 = 0;
ypr.m32 = 0;
ypr.m33 = 1;
return ypr;
}
inline void RotateRoll(Matrix4x4& m, float Roll) {
float cr = cosf(Roll);
float sr = sinf(Roll);
m = {
cr, sr, 0, 0,
-sr, cr, 0, 0,
0, 0, 1.0f, 0,
0, 0, 0, 1.0
};
}
inline void RotateYawPitchRoll(Matrix4x4& ypr, const Vector3D& r) {
float cy = cosf(r.Yaw);
float sy = sinf(r.Yaw);
float cp = cosf(r.Pitch);
float sp = sinf(r.Pitch);
float cr = cosf(r.Roll);
float sr = sinf(r.Roll);
ypr.m00 = cr*cy - sp*sr*sy;
ypr.m01 = cy*sr + cr*sp*sy;
ypr.m02 = -cp*sy;
ypr.m03 = 0;
ypr.m10 = -cp*sr;
ypr.m11 = cp*cr;
ypr.m12 = sp;
ypr.m13 = 0;
ypr.m20 = cr*sy + cy*sp*sr;
ypr.m21 = sr*sy - cr*cy*sp;
ypr.m22 = cp*cy;
ypr.m23 = 0;
ypr.m30 = 0;
ypr.m31 = 0;
ypr.m32 = 0;
ypr.m33 = 1;
}
inline void RotateYawPitch(Matrix4x4& ypr, const Vector3D& r) {
float cy = cosf(r.Yaw);
float sy = sinf(r.Yaw);
float cp = cosf(r.Pitch);
float sp = sinf(r.Pitch);
ypr.m00 = cy;
ypr.m01 = sp*sy;
ypr.m02 = -cp*sy;
ypr.m03 = 0;
ypr.m10 = 0;
ypr.m11 = cp;
ypr.m12 = sp;
ypr.m13 = 0;
ypr.m20 = sy;
ypr.m21 = -cy*sp;
ypr.m22 = cp*cy;
ypr.m23 = 0;
ypr.m30 = 0;
ypr.m31 = 0;
ypr.m32 = 0;
ypr.m33 = 1;
}
/*Sets only the 3x3 part of the matrix*/
inline void RotateYawPitchRoll2(Matrix4x4& ypr, const Vector3D& r) {
double cy = cos(r.Yaw);
double sy = sin(r.Yaw);
double cp = cos(r.Pitch);
double sp = sin(r.Pitch);
double cr = cos(r.Roll);
double sr = sin(r.Roll);
ypr.m00 = (float)(cr*cy - sp*sr*sy);
ypr.m01 = (float)(cy*sr + cr*sp*sy);
ypr.m02 = (float)(-cp*sy);
ypr.m10 = (float)(-cp*sr);
ypr.m11 = (float)(cp*cr);
ypr.m12 = (float)(sp);
ypr.m20 = (float)(cr*sy + cy*sp*sr);
ypr.m21 = (float)(sr*sy - cr*cy*sp);
ypr.m22 = (float)(cp*cy);
}
/*Sets only the 3x3 part of the matrix*/
inline void RotateYawPitch2(Matrix4x4& ypr, const Vector3D& r) {
double cy = cos(r.Yaw);
double sy = sin(r.Yaw);
double cp = cos(r.Pitch);
double sp = sin(r.Pitch);
ypr.m00 = (float)(cy);
ypr.m01 = (float)(sp*sy);
ypr.m02 = (float)(-cp*sy);
ypr.m10 = 0;
ypr.m11 = (float)(cp);
ypr.m12 = (float)(sp);
ypr.m20 = (float)(sy);
ypr.m21 = (float)(-cy*sp);
ypr.m22 = (float)(cp*cy);
}
inline void GetRotation(const Matrix3x3& m, Vector3D& Rot) {
Rot.Pitch = asinf(-m.m21);
Rot.Yaw = atan2f(m.m20, m.m22);
if (m.m01 == m.m11&&m.m01 == 0)
Rot.Roll = -3.1415926535897932384626433832795f;
else
Rot.Roll = atan2f(m.m01, m.m11);
}
inline void GetRotation(const Matrix3x4& m, Vector3D& Rot) {
Rot.Pitch = asinf(-m.m12);
Rot.Yaw = atan2f(m.m02, m.m22);
if (m.m01 == m.m11&&m.m10 == 0)
Rot.Roll = -3.1415926535897932384626433832795f;
else
Rot.Roll = atan2f(m.m10, m.m11);
}
inline void GetRotation(const Matrix4x4& m, Vector3D& Rot) {
Rot.Pitch = asinf(-m.m21);
Rot.Yaw = atan2f(m.m20, m.m22);
if (m.m01 == m.m11&&m.m01 == 0)
Rot.Roll = -3.1415926535897932384626433832795f;
else
Rot.Roll = atan2f(m.m01, m.m11);
}
inline float Det3(const Matrix4x4& m, int r, int c) {
char Comb[24][5] = {
{ 0, 1, 2, 3, 1 },
{ 1, 0, 2, 3, -1 },
{ 0, 2, 1, 3, -1 },
{ 2, 0, 1, 3, 1 },
{ 1, 2, 0, 3, 1 },
{ 2, 1, 0, 3, -1 },
{ 0, 1, 3, 2, -1 },
{ 1, 0, 3, 2, 1 },
{ 0, 3, 1, 2, 1 },
{ 3, 0, 1, 2, -1 },
{ 1, 3, 0, 2, -1 },
{ 3, 1, 0, 2, 1 },
{ 0, 2, 3, 1, 1 },
{ 2, 0, 3, 1, -1 },
{ 0, 3, 2, 1, -1 },
{ 3, 0, 2, 1, 1 },
{ 2, 3, 0, 1, 1 },
{ 3, 2, 0, 1, -1 },
{ 1, 2, 3, 0, -1 },
{ 2, 1, 3, 0, 1 },
{ 1, 3, 2, 0, 1 },
{ 3, 1, 2, 0, -1 },
{ 2, 3, 1, 0, -1 },
{ 3, 2, 1, 0, 1 },
};
char Map[4][3] = { { 1, 2, 3 }, { 0, 2, 3 }, { 0, 1, 3 }, { 0, 1, 2 } };
float sum = 0, mul;
int i, j;
for (i = 0; i < 6; i++) {
mul = Comb[i][4];
for (j = 0; j < 3; j++) {
mul *= m.m[Map[r][j]][Map[c][Comb[i][j]]];
}
sum += mul;
}
return(sum);
}
inline void MatrixInv(const Matrix4x4& in, Matrix4x4& out) {
float idet = 1.0f / MatrixDet4(in);
int i, j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
out.m[j][i] = Det3(in, i, j)*idet;
*(int*)& out.m[j][i] ^= ((i + j) << 31);
}
}
}
#define Det2x2(a,b,c,d) ((a)*(d)-(c)*(b))
inline void MatrixInv(const Matrix3x3& Mat, Matrix3x3& Inv) {
float idet = 1.0f / (
(Det2x2(Mat.m00, Mat.m01,
Mat.m10, Mat.m11) * Mat.m22)
- (Det2x2(Mat.m00, Mat.m02,
Mat.m10, Mat.m12) * Mat.m21)
+ (Det2x2(Mat.m01, Mat.m02,
Mat.m11, Mat.m12) * Mat.m20)
);
Inv.m00 = Det2x2(Mat.m11, Mat.m21, Mat.m12, Mat.m22)*idet;
Inv.m01 = -Det2x2(Mat.m01, Mat.m21, Mat.m02, Mat.m22)*idet;
Inv.m02 = Det2x2(Mat.m01, Mat.m11, Mat.m02, Mat.m12)*idet;
Inv.m10 = -Det2x2(Mat.m10, Mat.m20, Mat.m12, Mat.m22)*idet;
Inv.m11 = Det2x2(Mat.m00, Mat.m20, Mat.m02, Mat.m22)*idet;
Inv.m12 = -Det2x2(Mat.m00, Mat.m10, Mat.m02, Mat.m12)*idet;
Inv.m20 = Det2x2(Mat.m10, Mat.m20, Mat.m11, Mat.m21)*idet;
Inv.m21 = -Det2x2(Mat.m00, Mat.m20, Mat.m01, Mat.m21)*idet;
Inv.m22 = Det2x2(Mat.m00, Mat.m10, Mat.m01, Mat.m11)*idet;
}
inline void MatrixInverse(const Matrix3x4& in, Matrix3x4& out) {
Vector3D cr = in.Vec0.Vec3.Cross(in.Vec1.Vec3);
float idet = 1.0f / in.Vec2.Vec3.Dot(cr);
out.m00 = (in.m11 * in.m22 - in.m12 * in.m21) * idet;
out.m10 = -(in.m10 * in.m22 - in.m12 * in.m20) * idet;
out.m20 = (in.m10 * in.m21 - in.m11 * in.m20) * idet;
out.m01 = -(in.m01 * in.m22 - in.m02 * in.m21) * idet;
out.m11 = (in.m00 * in.m22 - in.m02 * in.m20) * idet;
out.m21 = -(in.m00 * in.m21 - in.m01 * in.m20) * idet;
out.m02 = (in.m01 * in.m12 - in.m02 * in.m11) * idet;
out.m12 = -(in.m00 * in.m12 - in.m02 * in.m10) * idet;
out.m22 = (in.m00 * in.m11 - in.m01 * in.m10) * idet;
out.m03 = -(in.m01 * in.m12 * in.m23 - in.m02 * in.m11 * in.m23 - in.m01 * in.m13 * in.m22 + in.m03 * in.m11 * in.m22 + in.m02 * in.m13 * in.m21 - in.m03 * in.m12 * in.m21) * idet;
out.m13 = (in.m00 * in.m12 * in.m23 - in.m02 * in.m10 * in.m23 - in.m00 * in.m13 * in.m22 + in.m03 * in.m10 * in.m22 + in.m02 * in.m13 * in.m20 - in.m03 * in.m12 * in.m20) * idet;
out.m23 = -(in.m00 * in.m11 * in.m23 - in.m01 * in.m10 * in.m23 - in.m00 * in.m13 * in.m21 + in.m03 * in.m10 * in.m21 + in.m01 * in.m13 * in.m20 - in.m03 * in.m11 * in.m20) * idet;
}
inline void MatrixInverse(const Matrix3x4& in, Matrix3x4& out, float det) {
float idet = 1.0f / det;
out.m00 = (in.m11 * in.m22 - in.m12 * in.m21) * idet;
out.m10 = -(in.m10 * in.m22 - in.m12 * in.m20) * idet;
out.m20 = (in.m10 * in.m21 - in.m11 * in.m20) * idet;
out.m01 = -(in.m01 * in.m22 - in.m02 * in.m21) * idet;
out.m11 = (in.m00 * in.m22 - in.m02 * in.m20) * idet;
out.m21 = -(in.m00 * in.m21 - in.m01 * in.m20) * idet;
out.m02 = (in.m01 * in.m12 - in.m02 * in.m11) * idet;
out.m12 = -(in.m00 * in.m12 - in.m02 * in.m10) * idet;
out.m22 = (in.m00 * in.m11 - in.m01 * in.m10) * idet;
out.m03 = -(in.m01 * in.m12 * in.m23 - in.m02 * in.m11 * in.m23 - in.m01 * in.m13 * in.m22 + in.m03 * in.m11 * in.m22 + in.m02 * in.m13 * in.m21 - in.m03 * in.m12 * in.m21) * idet;
out.m13 = (in.m00 * in.m12 * in.m23 - in.m02 * in.m10 * in.m23 - in.m00 * in.m13 * in.m22 + in.m03 * in.m10 * in.m22 + in.m02 * in.m13 * in.m20 - in.m03 * in.m12 * in.m20) * idet;
out.m23 = -(in.m00 * in.m11 * in.m23 - in.m01 * in.m10 * in.m23 - in.m00 * in.m13 * in.m21 + in.m03 * in.m10 * in.m21 + in.m01 * in.m13 * in.m20 - in.m03 * in.m11 * in.m20) * idet;
}
inline void FastMatrixInverse(const Matrix3x4& in, Matrix3x4& out, float det) {
float idet = 1.0f / det;
out.m00 = in.m00 * idet;
out.m10 = in.m01 * idet;
out.m20 = in.m02 * idet;
out.m01 = in.m10 * idet;
out.m11 = in.m11 * idet;
out.m21 = in.m12 * idet;
out.m02 = in.m20 * idet;
out.m12 = in.m21 * idet;
out.m22 = in.m22 * idet;
out.m03 = -(in.m00 * in.m03 + in.m10 * in.m13 + in.m20 * in.m23) * idet;
out.m13 = -(in.m01 * in.m03 + in.m11 * in.m13 + in.m21 * in.m23) * idet;
out.m23 = -(in.m02 * in.m03 + in.m12 * in.m13 + in.m22 * in.m23) * idet;
}
inline void FastMatrixInverse(const Matrix3x4& in, Matrix3x4& out) {
Vector3D cr = in.Vec0.Vec3.Cross(in.Vec1.Vec3);
float idet = 1.0f / in.Vec2.Vec3.Dot(cr);
out.m00 = in.m00 * idet;
out.m10 = in.m01 * idet;
out.m20 = in.m02 * idet;
out.m01 = in.m10 * idet;
out.m11 = in.m11 * idet;
out.m21 = in.m12 * idet;
out.m02 = in.m20 * idet;
out.m12 = in.m21 * idet;
out.m22 = in.m22 * idet;
out.m03 = -(in.m00 * in.m03 + in.m10 * in.m13 + in.m20 * in.m23) * idet;
out.m13 = -(in.m01 * in.m03 + in.m11 * in.m13 + in.m21 * in.m23) * idet;
out.m23 = -(in.m02 * in.m03 + in.m12 * in.m13 + in.m22 * in.m23) * idet;
}
inline void FasterMatrixInverse(const Matrix3x4& in, Matrix3x4& out) {
out.m00 = in.m00;
out.m01 = in.m10;
out.m02 = in.m20;
out.m10 = in.m01;
out.m11 = in.m11;
out.m12 = in.m21;
out.m20 = in.m02;
out.m21 = in.m12;
out.m22 = in.m22;
out.m03 = -(in.m00 * in.m03 + in.m10 * in.m13 + in.m20 * in.m23);
out.m13 = -(in.m01 * in.m03 + in.m11 * in.m13 + in.m21 * in.m23);
out.m23 = -(in.m02 * in.m03 + in.m12 * in.m13 + in.m22 * in.m23);
}
inline void FastMatrixInverse(const Matrix4x4& in, Matrix4x4& out, float det) {
float idet = 1.0f / det;
out.m00 = in.m00 * idet;
out.m10 = in.m01 * idet;
out.m20 = in.m02 * idet;
out.m01 = in.m10 * idet;
out.m11 = in.m11 * idet;
out.m21 = in.m12 * idet;
out.m02 = in.m20 * idet;
out.m12 = in.m21 * idet;
out.m22 = in.m22 * idet;
out.m03 = -(in.m00 * in.m03 + in.m10 * in.m13 + in.m20 * in.m23) * idet;
out.m13 = -(in.m01 * in.m03 + in.m11 * in.m13 + in.m21 * in.m23) * idet;
out.m23 = -(in.m02 * in.m03 + in.m12 * in.m13 + in.m22 * in.m23) * idet;
out.m30 = -(in.m00 * in.m30 + in.m01 * in.m31 + in.m02 * in.m32) * idet;
out.m31 = -(in.m10 * in.m30 + in.m11 * in.m31 + in.m12 * in.m32) * idet;
out.m32 = -(in.m20 * in.m30 + in.m21 * in.m31 + in.m22 * in.m32) * idet;
out.m33 = 1.0f;
}
inline void FastMatrixInverse(const Matrix4x4& in, Matrix4x4& out) {
Vector3D cr = in.Vec0.Vec3.Cross(in.Vec1.Vec3);
float idet = 1.0f / in.Vec2.Vec3.Dot(cr);
out.m00 = in.m00 * idet;
out.m01 = in.m10 * idet;
out.m02 = in.m20 * idet;
out.m03 = -(in.m00 * in.m03 + in.m10 * in.m13 + in.m20 * in.m23) * idet;
out.m10 = in.m01 * idet;
out.m11 = in.m11 * idet;
out.m12 = in.m21 * idet;
out.m13 = -(in.m01 * in.m03 + in.m11 * in.m13 + in.m21 * in.m23) * idet;
out.m20 = in.m02 * idet;
out.m21 = in.m12 * idet;
out.m22 = in.m22 * idet;
out.m23 = -(in.m02 * in.m03 + in.m12 * in.m13 + in.m22 * in.m23) * idet;
out.m30 = -(in.m00 * in.m30 + in.m01 * in.m31 + in.m02 * in.m32) * idet;
out.m31 = -(in.m10 * in.m30 + in.m11 * in.m31 + in.m12 * in.m32) * idet;
out.m32 = -(in.m20 * in.m30 + in.m21 * in.m31 + in.m22 * in.m32) * idet;
out.m33 = 1.0f;
}
inline void FasterMatrixInverse(const Matrix4x4& in, Matrix4x4& out) {
out.m00 = in.m00;
out.m10 = in.m01;
out.m20 = in.m02;
out.m01 = in.m10;
out.m11 = in.m11;
out.m21 = in.m12;
out.m02 = in.m20;
out.m12 = in.m21;
out.m22 = in.m22;
out.m03 = -(in.m00 * in.m03 + in.m10 * in.m13 + in.m20 * in.m23);
out.m13 = -(in.m01 * in.m03 + in.m11 * in.m13 + in.m21 * in.m23);
out.m23 = -(in.m02 * in.m03 + in.m12 * in.m13 + in.m22 * in.m23);
out.m30 = -(in.m00 * in.m30 + in.m01 * in.m31 + in.m02 * in.m32);
out.m31 = -(in.m10 * in.m30 + in.m11 * in.m31 + in.m12 * in.m32);
out.m32 = -(in.m20 * in.m30 + in.m21 * in.m31 + in.m22 * in.m32);
out.m33 = 1.0f;
}
inline void FastestMatrixInverse(const Matrix4x4& in, Matrix4x4& out) {
out.m00 = in.m00;
out.m10 = in.m01;
out.m20 = in.m02;
out.m01 = in.m10;
out.m11 = in.m11;
out.m21 = in.m12;
out.m02 = in.m20;
out.m12 = in.m21;
out.m22 = in.m22;
out.m03 = 0;
out.m13 = 0;
out.m23 = 0;
out.m30 = -(in.m00 * in.m30 + in.m01 * in.m31 + in.m02 * in.m32);
out.m31 = -(in.m10 * in.m30 + in.m11 * in.m31 + in.m12 * in.m32);
out.m32 = -(in.m20 * in.m30 + in.m21 * in.m31 + in.m22 * in.m32);
out.m33 = 1.0f;
}
inline Vector3D Mul3x3(const Vector3D& v, const Matrix4x4& m) {
Vector3D out;
out.x = v.x*m.m00 + v.y*m.m10 + v.z*m.m20;
out.y = v.x*m.m01 + v.y*m.m11 + v.z*m.m21;
out.z = v.x*m.m02 + v.y*m.m12 + v.z*m.m22;
return out;
}
inline Vector3D Mul3x3(const Matrix4x4& m, const Vector3D& v) {
Vector3D out;
out.x = v.x*m.m00 + v.y*m.m01 + v.z*m.m02;
out.y = v.x*m.m10 + v.y*m.m11 + v.z*m.m12;
out.z = v.x*m.m20 + v.y*m.m21 + v.z*m.m22;
return out;
}
/// Vector2
inline void operator+=(Vector2D& v1, const Vector2D& v2) {
v1.x += v2.x;
v1.y += v2.y;
}
inline void operator-=(Vector2D& v1, const Vector2D& v2) {
v1.x -= v2.x;
v1.y -= v2.y;
}
inline void operator*=(Vector2D& v1, const Vector2D& v2) {
v1.x *= v2.x;
v1.y *= v2.y;
}
inline void operator*=(Vector2D& v1, float f) {
v1.x *= f;
v1.y *= f;
}
inline Vector2D operator+(const Vector2D& v1, const Vector2D& v2) {
Vector2D out = v1;
out.x += v2.x;
out.y += v2.y;
return out;
}
inline Vector2D operator-(const Vector2D& v1, const Vector2D& v2) {
Vector2D out = v1;
out.x -= v2.x;
out.y -= v2.y;
return out;
}
inline Vector2D operator*(const Vector2D& v1, const Vector2D& v2) {
Vector2D out = v1;
out.x *= v2.x;
out.y *= v2.y;
return out;
}
inline Vector2D operator*(const Vector2D& v1, float f) {
Vector2D out = v1;
out.x *= f;
out.y *= f;
return out;
}
inline Vector2D operator*(float f, const Vector2D& v1) {
Vector2D out = v1;
out.x *= f;
out.y *= f;
return out;
}
inline Vector2D operator/(const Vector2D& v1, float f) {
Vector2D out = v1;
f = 1.0f / f;
out.x *= f;
out.y *= f;
return out;
}
// Vector3
inline Vector3D& operator+=(Vector3D& v1, const Vector3D& v2) {
v1.x += v2.x;
v1.y += v2.y;
v1.z += v2.z;
return v1;
}
inline Vector3D& operator-=(Vector3D& v1, const Vector3D& v2) {
v1.x -= v2.x;
v1.y -= v2.y;
v1.z -= v2.z;
return v1;
}
inline Vector4D& operator-=(Vector4D& v1, const Vector4D& v2) {
v1.x -= v2.x;
v1.y -= v2.y;
v1.z -= v2.z;
v1.w -= v2.w;
return v1;
}
inline Vector3D& operator*=(Vector3D& v1, const Vector3D& v2) {
v1.x *= v2.x;
v1.y *= v2.y;
v1.z *= v2.z;
return v1;
}
inline Vector3D& operator*=(Vector3D& v1, float f) {
v1.x *= f;
v1.y *= f;
v1.z *= f;
return v1;
}
inline Vector4D& operator*=(Vector4D& v1, float f) {
v1.x *= f;
v1.y *= f;
v1.z *= f;
v1.w *= f;
return v1;
}
inline Vector3D& operator/=(Vector3D& v1, float d) {
float f = 1.0f / d;
v1.x *= f;
v1.y *= f;
v1.z *= f;
return v1;
}
inline Vector4D& operator/=(Vector4D& v1, float d) {
float f = 1.0f / d;
v1.x *= f;
v1.y *= f;
v1.z *= f;
v1.w *= f;
return v1;
}
inline Vector3D operator+(const Vector3D& v1, const Vector3D& v2) {
return { v1.x + v2.x, v1.y + v2.y, v1.z + v2.z };
}
inline Vector3D operator-(const Vector3D& v1, const Vector3D& v2) {
return { v1.x - v2.x, v1.y - v2.y, v1.z - v2.z };
}
inline Vector3D operator*(const Vector3D& v1, const Vector3D& v2) {
return { v1.x * v2.x, v1.y * v2.y, v1.z * v2.z };
}
inline Vector3D operator/(const Vector3D& v1, const Vector3D& v2) {
return { v1.x / v2.x, v1.y / v2.y, v1.z / v2.z };
}
inline Vector3D operator*(const Vector3D& v1, float f) {
Vector3D out = v1;
out.x *= f;
out.y *= f;
out.z *= f;
return out;
}
inline Vector3D operator*(float f, const Vector3D& v1) {
Vector3D out = v1;
out.x *= f;
out.y *= f;
out.z *= f;
return out;
}
inline Vector3D operator/(const Vector3D& v1, float f) {
Vector3D out = v1;
out.x /= f;
out.y /= f;
out.z /= f;
return out;
}
inline Vector3D GramSchmit(const Vector3D& BaseVector, const Vector3D& toBeOrthoCorrected) {
return (toBeOrthoCorrected - BaseVector.Dot(toBeOrthoCorrected) * BaseVector).Normalized();
}
inline Quaternion Conjugate(const Quaternion& q) {
return{ -q.i, -q.j, -q.k, q.r };
}
inline DualQuaternion Conjugate(const DualQuaternion& q) {
return{ -q.r_i, -q.r_j, -q.r_k, q.r_r, -q.d_i, -q.d_j, -q.d_k, q.d_r };
}
inline Quaternion& GetMatrixQuaternion(const Matrix4x4& m, Quaternion& Out) {
//Out.r = sqrtf(1.0f + m.m00 + m.m11 + m.m22) * 0.5f;
//float w4 = Out.r * 4.0f;
//Out.i = (m.m21 - m.m12) / w4;
//Out.j = (m.m02 - m.m20) / w4;
//Out.k = (m.m10 - m.m01) / w4;
float tr = m.m00 + m.m11 + m.m22;
if (tr > 0) {
float S = sqrtf(tr + 1.0f) * 2.0f; // S=4*qw
Out.r = 0.25f * S;
Out.i = (m.m21 - m.m12) / S;
Out.j = (m.m02 - m.m20) / S;
Out.k = (m.m10 - m.m01) / S;
} else if ((m.m00 > m.m11)&(m.m00 > m.m22)) {
float S = sqrt(1.0f + m.m00 - m.m11 - m.m22) * 2.0f; // S=4*Out.i
Out.r = (m.m21 - m.m12) / S;
Out.i = 0.25f * S;
Out.j = (m.m01 + m.m10) / S;
Out.k = (m.m02 + m.m20) / S;
} else if (m.m11 > m.m22) {
float S = sqrt(1.0f + m.m11 - m.m00 - m.m22) * 2.0f; // S=4*Out.j
Out.r = (m.m02 - m.m20) / S;
Out.i = (m.m01 + m.m10) / S;
Out.j = 0.25f * S;
Out.k = (m.m12 + m.m21) / S;
} else {
float S = sqrt(1.0f + m.m22 - m.m00 - m.m11) * 2.0f; // S=4*Out.k
Out.r = (m.m10 - m.m01) / S;
Out.i = (m.m02 + m.m20) / S;
Out.j = (m.m12 + m.m21) / S;
Out.k = 0.25f * S;
}
return Out;
}
/*
inline Vector operator*(Vector & v, Matrix4x4 & m){
Vector out;
out.x=v.x*m.m[0][0] + v.y*m.m[1][0] + v.z*m.m[2][0] + m.m[3][0];
out.y=v.x*m.m[0][1] + v.y*m.m[1][1] + v.z*m.m[2][1] + m.m[3][1];
out.z=v.x*m.m[0][2] + v.y*m.m[1][2] + v.z*m.m[2][2] + m.m[3][2];
return out;
}*/
inline Vector3D operator*(const Vector3D& v, const Matrix4x4& m) {
float out[4];
__m128 to, t;
__m128 vc = _mm_load_ps1(&v.x);
__m128 mc = _mm_loadu_ps(&m.m00);
to = _mm_mul_ps(vc, mc);
vc = _mm_load_ps1(&v.y);
mc = _mm_loadu_ps(&m.m10);
t = _mm_mul_ps(vc, mc);
to = _mm_add_ps(to, t);
vc = _mm_load_ps1(&v.z);
mc = _mm_loadu_ps(&m.m20);
t = _mm_mul_ps(vc, mc);
to = _mm_add_ps(to, t);
mc = _mm_loadu_ps(&m.m30);
to = _mm_add_ps(to, mc);
_mm_storeu_ps(out, to);
return *(Vector3D*)out;
}
inline Vector2D operator*(const Vector2D& v, const Matrix4x4& m) {
Vector2D out = {
v.x*m.m00 + v.y*m.m10 + m.m30,
v.x*m.m01 + v.y*m.m11 + m.m31
};
return out;
}
inline Vector2D operator*(const Matrix4x4& m, const Vector2D& v) {
Vector2D out = {
v.x*m.m00 + v.y*m.m01 + m.m03,
v.x*m.m10 + v.y*m.m11 + m.m13
};
return out;
}
inline Vector3D operator*(const Vector3D& v, const Matrix3x4& m) {
Vector3D out;
out.x = m.Vec0.Vec3.Dot(v) + m.Vec0.w;
out.y = m.Vec1.Vec3.Dot(v) + m.Vec1.w;
out.z = m.Vec2.Vec3.Dot(v) + m.Vec2.w;
return out;
}
inline Vector3D operator*(const Matrix3x4& m, const Vector3D& v) {
Vector3D out;
out.x = m.Vec0.Vec3.Dot(v) + m.Vec0.w;
out.y = m.Vec1.Vec3.Dot(v) + m.Vec1.w;
out.z = m.Vec2.Vec3.Dot(v) + m.Vec2.w;
return out;
}
inline Vector4D operator*(const Vector4D& c, float f) {
Vector4D out;
__m128 tf = _mm_load_ps1(&f);
__m128 tc = _mm_loadu_ps(&c.r);
__m128 to = _mm_mul_ps(tf, tc);
_mm_storeu_ps(&out.r, to);
return out;
}
inline Vector3D operator*(const Vector3D& v, const Matrix3x3& m) {
Vector3D out;
out.x = v.x*m.m00 + v.y*m.m10 + v.z*m.m20;
out.y = v.x*m.m01 + v.y*m.m11 + v.z*m.m21;
out.z = v.x*m.m02 + v.y*m.m12 + v.z*m.m22;
return out;
}
inline Vector3D operator*(const Matrix3x3& m, const Vector3D& v) {
Vector3D out;
out.x = v.x*m.m00 + v.y*m.m01 + v.z*m.m02;
out.y = v.x*m.m10 + v.y*m.m11 + v.z*m.m12;
out.z = v.x*m.m20 + v.y*m.m21 + v.z*m.m22;
return out;
}
inline bool operator==(const Vector4D& v1, const Vector4D& v2) {
return((v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z) && (v1.w == v2.w));
}
inline bool operator!=(const Vector4D& v1, const Vector4D& v2) {
return((v1.x != v2.x) || (v1.y != v2.y) || (v1.z != v2.z) || (v1.w != v2.w));
}
inline bool operator==(const Vector3D& v1, const Vector3D& v2) {
return((v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z));
}
inline bool operator!=(const Vector3D& v1, const Vector3D& v2) {
return((v1.x != v2.x) || (v1.y != v2.y) || (v1.z != v2.z));
}
inline bool operator==(const Vector2D& v1, const Vector2D& v2) {
return((v1.u == v2.u) && (v1.v == v2.v));
}
inline bool operator!=(const Vector2D& v1, const Vector2D& v2) {
return((v1.u != v2.u) || (v1.v != v2.v));
}
inline bool operator==(const Weight& w1, const Weight& w2) {
int i;
for (i = 0; (i < 3) && (w1.I[i] == w2.I[i]) && (w1.W[i] == w2.W[i]); i++);
return(w1.I[i] == w2.I[i] && w1.W[i] == w2.W[i]);
}
inline Matrix4x4 operator*(const Matrix4x4& m1, const Matrix4x4& m2) {
return Matrix4x4{
m2.m00*m1.m00 + m2.m01*m1.m10 + m2.m02*m1.m20 + m2.m03 * m1.m30,
m2.m00*m1.m01 + m2.m01*m1.m11 + m2.m02*m1.m21 + m2.m03 * m1.m31,
m2.m00*m1.m02 + m2.m01*m1.m12 + m2.m02*m1.m22 + m2.m03 * m1.m32,
m2.m00*m1.m03 + m2.m01*m1.m13 + m2.m02*m1.m23 + m2.m03 * m1.m33,
m2.m10*m1.m00 + m2.m11*m1.m10 + m2.m12*m1.m20 + m2.m13 * m1.m30,
m2.m10*m1.m01 + m2.m11*m1.m11 + m2.m12*m1.m21 + m2.m13 * m1.m31,
m2.m10*m1.m02 + m2.m11*m1.m12 + m2.m12*m1.m22 + m2.m13 * m1.m32,
m2.m10*m1.m03 + m2.m11*m1.m13 + m2.m12*m1.m23 + m2.m13 * m1.m33,
m2.m20*m1.m00 + m2.m21*m1.m10 + m2.m22*m1.m20 + m2.m23 * m1.m30,
m2.m20*m1.m01 + m2.m21*m1.m11 + m2.m22*m1.m21 + m2.m23 * m1.m31,
m2.m20*m1.m02 + m2.m21*m1.m12 + m2.m22*m1.m22 + m2.m23 * m1.m32,
m2.m20*m1.m03 + m2.m21*m1.m13 + m2.m22*m1.m23 + m2.m23 * m1.m33,
m2.m30*m1.m00 + m2.m31*m1.m10 + m2.m32*m1.m20 + m2.m33 * m1.m30,
m2.m30*m1.m01 + m2.m31*m1.m11 + m2.m32*m1.m21 + m2.m33 * m1.m31,
m2.m30*m1.m02 + m2.m31*m1.m12 + m2.m32*m1.m22 + m2.m33 * m1.m32,
m2.m30*m1.m03 + m2.m31*m1.m13 + m2.m32*m1.m23 + m2.m33 * m1.m33
};
//Matrix4x4 out;
//out.m00 = m2.m00*m1.m00 + m2.m01*m1.m10 + m2.m02*m1.m20 + m2.m03 * m1.m30;
//out.m01 = m2.m00*m1.m01 + m2.m01*m1.m11 + m2.m02*m1.m21 + m2.m03 * m1.m31;
//out.m02 = m2.m00*m1.m02 + m2.m01*m1.m12 + m2.m02*m1.m22 + m2.m03 * m1.m32;
//out.m03 = m2.m00*m1.m03 + m2.m01*m1.m13 + m2.m02*m1.m23 + m2.m03 * m1.m33;
//out.m10 = m2.m10*m1.m00 + m2.m11*m1.m10 + m2.m12*m1.m20 + m2.m13 * m1.m30;
//out.m11 = m2.m10*m1.m01 + m2.m11*m1.m11 + m2.m12*m1.m21 + m2.m13 * m1.m31;
//out.m12 = m2.m10*m1.m02 + m2.m11*m1.m12 + m2.m12*m1.m22 + m2.m13 * m1.m32;
//out.m13 = m2.m10*m1.m03 + m2.m11*m1.m13 + m2.m12*m1.m23 + m2.m13 * m1.m33;
//out.m20 = m2.m20*m1.m00 + m2.m21*m1.m10 + m2.m22*m1.m20 + m2.m23 * m1.m30;
//out.m21 = m2.m20*m1.m01 + m2.m21*m1.m11 + m2.m22*m1.m21 + m2.m23 * m1.m31;
//out.m22 = m2.m20*m1.m02 + m2.m21*m1.m12 + m2.m22*m1.m22 + m2.m23 * m1.m32;
//out.m23 = m2.m20*m1.m03 + m2.m21*m1.m13 + m2.m22*m1.m23 + m2.m23 * m1.m33;
//out.m30 = m2.m30*m1.m00 + m2.m31*m1.m10 + m2.m32*m1.m20 + m2.m33 * m1.m30;
//out.m31 = m2.m30*m1.m01 + m2.m31*m1.m11 + m2.m32*m1.m21 + m2.m33 * m1.m31;
//out.m32 = m2.m30*m1.m02 + m2.m31*m1.m12 + m2.m32*m1.m22 + m2.m33 * m1.m32;
//out.m33 = m2.m30*m1.m03 + m2.m31*m1.m13 + m2.m32*m1.m23 + m2.m33 * m1.m33;
//return out;
}
inline void MatrixMutily(Matrix4x4& out, const Matrix4x4& m1, const Matrix4x4& m2) {
out.m00 = m2.m00*m1.m00 + m2.m01*m1.m10 + m2.m02*m1.m20 + m2.m03 * m1.m30;
out.m01 = m2.m00*m1.m01 + m2.m01*m1.m11 + m2.m02*m1.m21 + m2.m03 * m1.m31;
out.m02 = m2.m00*m1.m02 + m2.m01*m1.m12 + m2.m02*m1.m22 + m2.m03 * m1.m32;
out.m03 = m2.m00*m1.m03 + m2.m01*m1.m13 + m2.m02*m1.m23 + m2.m03 * m1.m33;
out.m10 = m2.m10*m1.m00 + m2.m11*m1.m10 + m2.m12*m1.m20 + m2.m13 * m1.m30;
out.m11 = m2.m10*m1.m01 + m2.m11*m1.m11 + m2.m12*m1.m21 + m2.m13 * m1.m31;
out.m12 = m2.m10*m1.m02 + m2.m11*m1.m12 + m2.m12*m1.m22 + m2.m13 * m1.m32;
out.m13 = m2.m10*m1.m03 + m2.m11*m1.m13 + m2.m12*m1.m23 + m2.m13 * m1.m33;
out.m20 = m2.m20*m1.m00 + m2.m21*m1.m10 + m2.m22*m1.m20 + m2.m23 * m1.m30;
out.m21 = m2.m20*m1.m01 + m2.m21*m1.m11 + m2.m22*m1.m21 + m2.m23 * m1.m31;
out.m22 = m2.m20*m1.m02 + m2.m21*m1.m12 + m2.m22*m1.m22 + m2.m23 * m1.m32;
out.m23 = m2.m20*m1.m03 + m2.m21*m1.m13 + m2.m22*m1.m23 + m2.m23 * m1.m33;
out.m30 = m2.m30*m1.m00 + m2.m31*m1.m10 + m2.m32*m1.m20 + m2.m33 * m1.m30;
out.m31 = m2.m30*m1.m01 + m2.m31*m1.m11 + m2.m32*m1.m21 + m2.m33 * m1.m31;
out.m32 = m2.m30*m1.m02 + m2.m31*m1.m12 + m2.m32*m1.m22 + m2.m33 * m1.m32;
out.m33 = m2.m30*m1.m03 + m2.m31*m1.m13 + m2.m32*m1.m23 + m2.m33 * m1.m33;
}
inline void MatrixMutily_M4x3_x_M3x3(Matrix4x4& out, const Matrix4x4& m1, const Matrix4x4& m2) {
out.m00 = m2.m00*m1.m00 + m2.m01*m1.m10 + m2.m02*m1.m20;
out.m01 = m2.m00*m1.m01 + m2.m01*m1.m11 + m2.m02*m1.m21;
out.m02 = m2.m00*m1.m02 + m2.m01*m1.m12 + m2.m02*m1.m22;
out.m03 = 0;
out.m10 = m2.m10*m1.m00 + m2.m11*m1.m10 + m2.m12*m1.m20;
out.m11 = m2.m10*m1.m01 + m2.m11*m1.m11 + m2.m12*m1.m21;
out.m12 = m2.m10*m1.m02 + m2.m11*m1.m12 + m2.m12*m1.m22;
out.m13 = 0;
out.m20 = m2.m20*m1.m00 + m2.m21*m1.m10 + m2.m22*m1.m20;
out.m21 = m2.m20*m1.m01 + m2.m21*m1.m11 + m2.m22*m1.m21;
out.m22 = m2.m20*m1.m02 + m2.m21*m1.m12 + m2.m22*m1.m22;
out.m23 = 0;
out.m30 = m1.m30;
out.m31 = m1.m31;
out.m32 = m1.m32;
out.m33 = 1.0f;
}
#define _M4x3_x_M3x3_Init(m1, m2){\
m2.m00*m1.m00 + m2.m01*m1.m10 + m2.m02*m1.m20,\
m2.m00*m1.m01 + m2.m01*m1.m11 + m2.m02*m1.m21,\
m2.m00*m1.m02 + m2.m01*m1.m12 + m2.m02*m1.m22,\
0,\
m2.m10*m1.m00 + m2.m11*m1.m10 + m2.m12*m1.m20,\
m2.m10*m1.m01 + m2.m11*m1.m11 + m2.m12*m1.m21,\
m2.m10*m1.m02 + m2.m11*m1.m12 + m2.m12*m1.m22,\
0,\
m2.m20*m1.m00 + m2.m21*m1.m10 + m2.m22*m1.m20,\
m2.m20*m1.m01 + m2.m21*m1.m11 + m2.m22*m1.m21,\
m2.m20*m1.m02 + m2.m21*m1.m12 + m2.m22*m1.m22,\
0,\
m1.m30,\
m1.m31,\
m1.m32,\
1.0f\
}
#define _ScaleMatrix(mat, s){\
(mat).m00 *= (s).x;\
(mat).m01 *= (s).x;\
(mat).m02 *= (s).x;\
(mat).m03 *= (s).x;\
\
(mat).m10 *= (s).y;\
(mat).m11 *= (s).y;\
(mat).m12 *= (s).y;\
(mat).m13 *= (s).y;\
\
(mat).m20 *= (s).z;\
(mat).m21 *= (s).z;\
(mat).m22 *= (s).z;\
(mat).m23 *= (s).z;\
}
#define _TranslateMatrix(mat, p){\
(mat).m30+=((p).x * (mat).m00 + (p).y * (mat).m10 + (p).z * (mat).m20);\
(mat).m31+=((p).x * (mat).m01 + (p).y * (mat).m11 + (p).z * (mat).m21);\
(mat).m32+=((p).x * (mat).m02 + (p).y * (mat).m12 + (p).z * (mat).m22);\
}
#define _ScaleMatrix_Init(mat, s){\
(mat).m00 * (s).x,\
(mat).m01 * (s).x,\
(mat).m02 * (s).x,\
(mat).m03 * (s).x,\
\
(mat).m10 * (s).y,\
(mat).m11 * (s).y,\
(mat).m12 * (s).y,\
(mat).m13 * (s).y,\
\
(mat).m20 * (s).z,\
(mat).m21 * (s).z,\
(mat).m22 * (s).z,\
(mat).m23 * (s).z,\
\
(mat).m30,\
(mat).m31,\
(mat).m32,\
(mat).m33\
}
/*
ret = mat * | 1 0 0 0 |
| 0 1 0 0 |
| 0 0 1 0 |
| p.x p.y p.z 1 |
*/
#define _TranslateMatrix_Init(mat, p){\
(mat).m00,\
(mat).m01,\
(mat).m02,\
(mat).m03,\
\
(mat).m10,\
(mat).m11,\
(mat).m12,\
(mat).m13,\
\
(mat).m20,\
(mat).m21,\
(mat).m22,\
(mat).m23,\
\
(mat).m30+((p).x * (mat).m00 + (p).y * (mat).m10 + (p).z * (mat).m20),\
(mat).m31+((p).x * (mat).m01 + (p).y * (mat).m11 + (p).z * (mat).m21),\
(mat).m32+((p).x * (mat).m02 + (p).y * (mat).m12 + (p).z * (mat).m22),\
(mat).m33\
}
inline Matrix3x4 operator*(const Matrix3x4& m1, const Matrix3x4& m2) {
return Matrix3x4{
m1.m00*m2.m00 + m1.m01*m2.m10 + m1.m02*m2.m20,
m1.m00*m2.m01 + m1.m01*m2.m11 + m1.m02*m2.m21,
m1.m00*m2.m02 + m1.m01*m2.m12 + m1.m02*m2.m22,
m1.m00*m2.m03 + m1.m01*m2.m13 + m1.m02*m2.m23 + m1.m03,
m1.m10*m2.m00 + m1.m11*m2.m10 + m1.m12*m2.m20,
m1.m10*m2.m01 + m1.m11*m2.m11 + m1.m12*m2.m21,
m1.m10*m2.m02 + m1.m11*m2.m12 + m1.m12*m2.m22,
m1.m10*m2.m03 + m1.m11*m2.m13 + m1.m12*m2.m23 + m1.m13,
m1.m20*m2.m00 + m1.m21*m2.m10 + m1.m22*m2.m20,
m1.m20*m2.m01 + m1.m21*m2.m11 + m1.m22*m2.m21,
m1.m20*m2.m02 + m1.m21*m2.m12 + m1.m22*m2.m22,
m1.m20*m2.m03 + m1.m21*m2.m13 + m1.m22*m2.m23 + m1.m23
};
//Matrix3x4 out;
//out.m00 = m1.m00*m2.m00 + m1.m01*m2.m10 + m1.m02*m2.m20;
//out.m01 = m1.m00*m2.m01 + m1.m01*m2.m11 + m1.m02*m2.m21;
//out.m02 = m1.m00*m2.m02 + m1.m01*m2.m12 + m1.m02*m2.m22;
//out.m03 = m1.m00*m2.m03 + m1.m01*m2.m13 + m1.m02*m2.m23 + m1.m03;
//out.m10 = m1.m10*m2.m00 + m1.m11*m2.m10 + m1.m12*m2.m20;
//out.m11 = m1.m10*m2.m01 + m1.m11*m2.m11 + m1.m12*m2.m21;
//out.m12 = m1.m10*m2.m02 + m1.m11*m2.m12 + m1.m12*m2.m22;
//out.m13 = m1.m10*m2.m03 + m1.m11*m2.m13 + m1.m12*m2.m23 + m1.m13;
//out.m20 = m1.m20*m2.m00 + m1.m21*m2.m10 + m1.m22*m2.m20;
//out.m21 = m1.m20*m2.m01 + m1.m21*m2.m11 + m1.m22*m2.m21;
//out.m22 = m1.m20*m2.m02 + m1.m21*m2.m12 + m1.m22*m2.m22;
//out.m23 = m1.m20*m2.m03 + m1.m21*m2.m13 + m1.m22*m2.m23 + m1.m23;
//return out;
}
inline Vector3D VectorMin(const Vector3D& a, const Vector3D& b) {
Vector3D min;
*((unsigned int*)&min.x) = (*(unsigned int*)&a.x & -(a.x < b.x)) | (*(unsigned int*)&b.x & -(b.x <= a.x));
*((unsigned int*)&min.y) = (*(unsigned int*)&a.y & -(a.y < b.y)) | (*(unsigned int*)&b.y & -(b.y <= a.y));
*((unsigned int*)&min.z) = (*(unsigned int*)&a.z & -(a.z < b.z)) | (*(unsigned int*)&b.z & -(b.z <= a.z));
return min;
}
inline Vector3D VectorMax(const Vector3D& a, const Vector3D& b) {
Vector3D max;
*((unsigned int*)&max.x) = (*(unsigned int*)&a.x & -(a.x > b.x)) | (*(unsigned int*)&b.x & -(b.x >= a.x));
*((unsigned int*)&max.y) = (*(unsigned int*)&a.y & -(a.y > b.y)) | (*(unsigned int*)&b.y & -(b.y >= a.y));
*((unsigned int*)&max.z) = (*(unsigned int*)&a.z & -(a.z > b.z)) | (*(unsigned int*)&b.z & -(b.z >= a.z));
return max;
}
inline Vector4D VectorMin(const Vector4D& a, const Vector4D& b) {
Vector4D min;
*((unsigned int*)&min.x) = (*(unsigned int*)&a.x & -(a.x < b.x)) | (*(unsigned int*)&b.x & -(b.x <= a.x));
*((unsigned int*)&min.y) = (*(unsigned int*)&a.y & -(a.y < b.y)) | (*(unsigned int*)&b.y & -(b.y <= a.y));
*((unsigned int*)&min.z) = (*(unsigned int*)&a.z & -(a.z < b.z)) | (*(unsigned int*)&b.z & -(b.z <= a.z));
*((unsigned int*)&min.w) = (*(unsigned int*)&a.w & -(a.w < b.w)) | (*(unsigned int*)&b.w & -(b.w <= a.w));
return min;
}
inline Vector4D VectorMax(const Vector4D& a, const Vector4D& b) {
Vector4D max;
*((unsigned int*)&max.x) = (*(unsigned int*)&a.x & -(a.x > b.x)) | (*(unsigned int*)&b.x & -(b.x >= a.x));
*((unsigned int*)&max.y) = (*(unsigned int*)&a.y & -(a.y > b.y)) | (*(unsigned int*)&b.y & -(b.y >= a.y));
*((unsigned int*)&max.z) = (*(unsigned int*)&a.z & -(a.z > b.z)) | (*(unsigned int*)&b.z & -(b.z >= a.z));
*((unsigned int*)&max.z) = (*(unsigned int*)&a.z & -(a.z > b.z)) | (*(unsigned int*)&b.z & -(b.z >= a.z));
return max;
}
inline Vector3D Orbit(float u, float v) {
Vector3D Ret;
float usin, ucos, vsin, vcos;
sincosf(u, &usin, &ucos);
sincosf(v, &vsin, &vcos);
Ret.x = usin*vcos;
Ret.y = vsin;
Ret.z = vcos*ucos;
return Ret;
}
inline Matrix4x4 rYaw(float y) {
float c, s;
sincosf(y, &s, &c);
Matrix4x4 out = { c, 0, -s, 0,
0, 1, 0, 0,
s, 0, c, 0,
0, 0, 0, 1 };
return out;
}
inline Matrix4x4 rPitch(float p) {
float c, s;
sincosf(p, &s, &c);
Matrix4x4 out = { 1, 0, 0, 0,
0, c, s, 0,
0, -s, c, 0,
0, 0, 0, 1 };
return out;
}
inline Matrix4x4 rRoll(float r) {
float c, s;
sincosf(r, &s, &c);
Matrix4x4 out = { c, s, 0, 0,
-s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
return out;
}
inline Matrix4x4 mTran(Vector3D& p) {
Matrix4x4 out = { 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
p.x, p.y, p.z, 1 };
return out;
}
inline void MatrixTranspose(Matrix4x4& m) {
std::swap(m.m01, m.m10);
std::swap(m.m02, m.m20);
std::swap(m.m03, m.m30);
std::swap(m.m12, m.m21);
std::swap(m.m13, m.m31);
std::swap(m.m23, m.m32);
}
//#define MatStoreDiagonal(mat, v){\
// (mat).m00=(v).x;\
// (mat).m11=(v).y;\
// (mat).m22=(v).z;}
//#define _MatStoreDiagonal(mat, x, y, z){\
// (mat).m00=x;\
// (mat).m11=y;\
// (mat).m22=z;}
inline Quaternion operator+(const Quaternion& q1, const Quaternion& q2) {
return{ q1.i + q2.i, q1.j + q2.j, q1.k + q2.k, q1.r + q2.r };
}
inline Quaternion operator-(const Quaternion& q1, const Quaternion& q2) {
return{ q1.i - q2.i, q1.j - q2.j, q1.k - q2.k, q1.r - q2.r };
}
inline Quaternion operator*(float x, const Quaternion& q) {
return{ q.i*x, q.j*x, q.k*x, q.r*x };
}
inline Quaternion operator*(const Quaternion& q, float x) {
return{ q.i*x, q.j*x, q.k*x, q.r*x };
}
inline Quaternion operator*(const Quaternion& q1, const Quaternion& q2) {
return{
q1.i*q2.r + q1.r*q2.i + q1.j*q2.k - q1.k*q2.j,
q1.r*q2.j - q1.i*q2.k + q1.j*q2.r + q1.k*q2.i,
q1.r*q2.k + q1.i*q2.j - q1.j*q2.i + q1.k*q2.r,
q1.r*q2.r - q1.i*q2.i - q1.j*q2.j - q1.k*q2.k
};
}
inline Quaternion& operator*=(Quaternion& q1, const Quaternion& q2) {
q1 = {
q1.i*q2.r + q1.r*q2.i + q1.j*q2.k - q1.k*q2.j,
q1.r*q2.j - q1.i*q2.k + q1.j*q2.r + q1.k*q2.i,
q1.r*q2.k + q1.i*q2.j - q1.j*q2.i + q1.k*q2.r,
q1.r*q2.r - q1.i*q2.i - q1.j*q2.j - q1.k*q2.k
};
return q1;
}
inline DualQuaternion operator*(const DualQuaternion& dq1, const DualQuaternion& dq2) {
return {
dq1.r_i*dq2.r_r + dq1.r_j*dq2.r_k + dq1.r_r*dq2.r_i - dq1.r_k*dq2.r_j,
dq1.r_r*dq2.r_j - dq1.r_i*dq2.r_k + dq1.r_j*dq2.r_r + dq1.r_k*dq2.r_i,
dq1.r_r*dq2.r_k + dq1.r_i*dq2.r_j - dq1.r_j*dq2.r_i + dq1.r_k*dq2.r_r,
dq1.r_r*dq2.r_r - dq1.r_i*dq2.r_i - dq1.r_j*dq2.r_j - dq1.r_k*dq2.r_k,
dq1.d_j*dq2.r_k - dq1.d_k*dq2.r_j - dq1.r_k*dq2.d_j + dq1.r_j*dq2.d_k + dq1.d_i*dq2.r_r + dq1.r_r*dq2.d_i + dq1.d_r*dq2.r_i + dq1.r_i*dq2.d_r,
dq1.r_k*dq2.d_i - dq1.d_i*dq2.r_k + dq1.d_k*dq2.r_i - dq1.r_i*dq2.d_k + dq1.d_j*dq2.r_r + dq1.r_r*dq2.d_j + dq1.d_r*dq2.r_j + dq1.r_j*dq2.d_r,
dq1.d_i*dq2.r_j - dq1.d_j*dq2.r_i - dq1.r_j*dq2.d_i + dq1.r_i*dq2.d_j + dq1.d_k*dq2.r_r + dq1.r_r*dq2.d_k + dq1.d_r*dq2.r_k + dq1.r_k*dq2.d_r,
dq1.d_r*dq2.r_r - dq1.r_i*dq2.d_i - dq1.d_j*dq2.r_j - dq1.r_j*dq2.d_j - dq1.d_k*dq2.r_k - dq1.r_k*dq2.d_k - dq1.d_i*dq2.r_i + dq1.r_r*dq2.d_r
};
}
inline void toEulerianAngle(const Quaternion& q, Vector3D& Rotation) {
float ysqr = q.j * q.j;
float t2 = 2.0f * (q.r * q.j - q.k * q.i);
t2 = t2 > 1.0f ? 1.0f : t2;
t2 = t2 < -1.0f ? -1.0f : t2;
Rotation.Pitch = asin(t2);
Rotation.Yaw = atan2(2.0f * (q.r * q.k + q.i * q.j), 1.0f - 2.0f * (ysqr + q.k * q.k));
Rotation.Roll = atan2(2.0f * (q.r * q.i + q.j * q.k), 1.0f - 2.0f * (q.i * q.i + ysqr));
}
inline Quaternion CreateQuaternionXYZ(const Vector3D& rot) {
float cosRoll, cosYaw, cosPitch, sinRoll, sinYaw, sinPitch;
sincosf(rot.Yaw * 0.5f, &sinYaw, &cosYaw);
sincosf(rot.Pitch * 0.5f, &sinPitch, &cosPitch);
sincosf(rot.Roll * 0.5f, &sinRoll, &cosRoll);
return{
cosYaw*cosRoll*sinPitch - cosPitch*sinYaw*sinRoll,
cosRoll*cosPitch*sinYaw + cosYaw*sinRoll*sinPitch,
cosYaw*cosPitch*sinRoll - cosRoll*sinYaw*sinPitch,
cosYaw*cosRoll*cosPitch + sinYaw*sinRoll*sinPitch
};
}
inline Quaternion CreateQuaternionXZY(const Vector3D& rot) {
float cosRoll, cosYaw, cosPitch, sinRoll, sinYaw, sinPitch;
sincosf(rot.Yaw * 0.5f, &sinYaw, &cosYaw);
sincosf(rot.Pitch * 0.5f, &sinPitch, &cosPitch);
sincosf(rot.Roll * 0.5f, &sinRoll, &cosRoll);
return{
cosYaw*cosRoll*sinPitch + cosPitch*sinYaw*sinRoll,
cosRoll*cosPitch*sinYaw + cosYaw*sinRoll*sinPitch,
cosYaw*cosPitch*sinRoll - cosRoll*sinYaw*sinPitch,
cosYaw*cosRoll*cosPitch - sinYaw*sinRoll*sinPitch
};
}
inline Quaternion CreateQuaternionYXZ(const Vector3D& rot) {
float cosRoll, cosYaw, cosPitch, sinRoll, sinYaw, sinPitch;
sincosf(rot.Yaw * 0.5f, &sinYaw, &cosYaw);
sincosf(rot.Pitch * 0.5f, &sinPitch, &cosPitch);
sincosf(rot.Roll * 0.5f, &sinRoll, &cosRoll);
return{
cosYaw*cosRoll*sinPitch - cosPitch*sinYaw*sinRoll,
cosRoll*cosPitch*sinYaw + cosYaw*sinRoll*sinPitch,
cosYaw*cosPitch*sinRoll + cosRoll*sinYaw*sinPitch,
cosYaw*cosRoll*cosPitch - sinYaw*sinRoll*sinPitch
};
}
inline Quaternion CreateQuaternionYZX(const Vector3D& rot) {
float cosRoll, cosYaw, cosPitch, sinRoll, sinYaw, sinPitch;
sincosf(rot.Yaw * 0.5f, &sinYaw, &cosYaw);
sincosf(rot.Pitch * 0.5f, &sinPitch, &cosPitch);
sincosf(rot.Roll * 0.5f, &sinRoll, &cosRoll);
return{
cosYaw*cosRoll*sinPitch - cosPitch*sinYaw*sinRoll,
cosRoll*cosPitch*sinYaw - cosYaw*sinRoll*sinPitch,
cosYaw*cosPitch*sinRoll + cosRoll*sinYaw*sinPitch,
cosYaw*cosRoll*cosPitch + sinYaw*sinRoll*sinPitch
};
}
inline Quaternion CreateQuaternionZXY(const Vector3D& rot) {
float cosRoll, cosYaw, cosPitch, sinRoll, sinYaw, sinPitch;
sincosf(rot.Yaw * 0.5f, &sinYaw, &cosYaw);
sincosf(rot.Pitch * 0.5f, &sinPitch, &cosPitch);
sincosf(rot.Roll * 0.5f, &sinRoll, &cosRoll);
return{
cosYaw*cosRoll*sinPitch + cosPitch*sinYaw*sinRoll,
cosRoll*cosPitch*sinYaw - cosYaw*sinRoll*sinPitch,
cosYaw*cosPitch*sinRoll - cosRoll*sinYaw*sinPitch,
cosYaw*cosRoll*cosPitch + sinYaw*sinRoll*sinPitch
};
}
inline Quaternion CreateQuaternionZYX(const Vector3D& rot) {
float cosRoll, cosYaw, cosPitch, sinRoll, sinYaw, sinPitch;
sincosf(rot.Yaw * 0.5f, &sinYaw, &cosYaw);
sincosf(rot.Pitch * 0.5f, &sinPitch, &cosPitch);
sincosf(rot.Roll * 0.5f, &sinRoll, &cosRoll);
return{
cosYaw*cosRoll*sinPitch + cosPitch*sinYaw*sinRoll,
cosRoll*cosPitch*sinYaw - cosYaw*sinRoll*sinPitch,
cosYaw*cosPitch*sinRoll + cosRoll*sinYaw*sinPitch,
cosYaw*cosRoll*cosPitch - sinYaw*sinRoll*sinPitch
};
}
/////////////// Dual /////////////////////////////
inline DualQuaternion CreateDualQuaternionXYZ(const Vector3D& rot, const Vector3D& pos) {
Quaternion Real = CreateQuaternionXYZ(rot);
return{
Real.i,
Real.j,
Real.k,
Real.r,
(pos.x*Real.r + pos.y*Real.k - pos.z*Real.j)*0.5f,
(-pos.x*Real.k + pos.y*Real.r + pos.z*Real.i)*0.5f,
(pos.x*Real.j - pos.y*Real.i + pos.z*Real.r)*0.5f,
(-pos.x*Real.i - pos.y*Real.j - pos.z*Real.k)*0.5f
};
}
inline DualQuaternion CreateDualQuaternionXZY(const Vector3D& rot, const Vector3D& pos) {
Quaternion Real = CreateQuaternionXZY(rot);
return{
Real.i,
Real.j,
Real.k,
Real.r,
(pos.x * Real.r + pos.y * Real.k - pos.z * Real.j) * 0.5f,
(-pos.x * Real.k + pos.y * Real.r + pos.z * Real.i) * 0.5f,
(pos.x * Real.j - pos.y * Real.i + pos.z * Real.r) * 0.5f,
(-pos.x * Real.i - pos.y * Real.j - pos.z * Real.k) * 0.5f
};
}
inline DualQuaternion CreateDualQuaternionYXZ(const Vector3D& rot, const Vector3D& pos) {
Quaternion Real = CreateQuaternionYXZ(rot);
return{
Real.i,
Real.j,
Real.k,
Real.r,
(pos.x * Real.r + pos.y * Real.k - pos.z * Real.j) * 0.5f,
(-pos.x * Real.k + pos.y * Real.r + pos.z * Real.i) * 0.5f,
(pos.x * Real.j - pos.y * Real.i + pos.z * Real.r) * 0.5f,
(-pos.x * Real.i - pos.y * Real.j - pos.z * Real.k) * 0.5f
};
}
inline DualQuaternion CreateDualQuaternionYZX(const Vector3D& rot, const Vector3D& pos) {
Quaternion Real = CreateQuaternionYZX(rot);
return{
Real.i,
Real.j,
Real.k,
Real.r,
(pos.x * Real.r + pos.y*Real.k - pos.z * Real.j) * 0.5f,
(-pos.x * Real.k + pos.y*Real.r + pos.z * Real.i) * 0.5f,
(pos.x * Real.j - pos.y*Real.i + pos.z * Real.r) * 0.5f,
(-pos.x * Real.i - pos.y*Real.j - pos.z * Real.k) * 0.5f
};
}
inline DualQuaternion CreateDualQuaternionZXY(const Vector3D& rot, const Vector3D& pos) {
Quaternion Real = CreateQuaternionZXY(rot);
return{
Real.i,
Real.j,
Real.k,
Real.r,
(pos.x*Real.r + pos.y*Real.k - pos.z*Real.j) * 0.5f,
(-pos.x*Real.k + pos.y*Real.r + pos.z*Real.i) * 0.5f,
(pos.x*Real.j - pos.y*Real.i + pos.z*Real.r) * 0.5f,
(-pos.x*Real.i - pos.y*Real.j - pos.z*Real.k) * 0.5f
};
}
inline DualQuaternion CreateDualQuaternionZYX(const Vector3D& rot, const Vector3D& pos) {
float cy, cp, cr, sy, sp, sr;
sincosf(rot.Yaw*0.5f, &sy, &cy);
sincosf(rot.Pitch*0.5f, &sp, &cp);
sincosf(rot.Roll*0.5f, &sr, &cr);
Quaternion Real = {
cp*cy*sr - cr*sp*sy,
cr*cy*sp - cp*sr*sy,
cp*cr*sy + cy*sp*sr,
cp*cr*cy + sp*sr*sy
};
return{
Real.i,
Real.j,
Real.k,
Real.r,
(pos.x*Real.r + pos.y*Real.k - pos.z*Real.j)*0.5f,
(-pos.x*Real.k + pos.y*Real.r + pos.z*Real.i)*0.5f,
(pos.x*Real.j - pos.y*Real.i + pos.z*Real.r)*0.5f,
(-pos.x*Real.i - pos.y*Real.j - pos.z*Real.k)*0.5f
};
}
////////////////////////////////////////////////////////////////////
inline float RayPointDistance(const Ray& r, const Vector3D& p) {
auto dif = (r.Position - p);
return (dif - r.Direction * r.Direction.Dot(dif)).Length();
}
inline float RayPointDistanceSquared(const Ray& r, const Vector3D& p) {
auto dif = (r.Position - p);
return (dif - r.Direction * r.Direction.Dot(dif)).Length2();
}
inline float RayPointDistance(const Ray2D& r, const Vector2D& p) {
auto dif = r.Position - p;
return (dif - r.Direction * r.Direction.Dot(dif)).Length();
}
inline float RayPointDistanceSquared(const Ray2D& r, const Vector2D& p) {
auto dif = (r.Position - p);
return (dif - r.Direction * r.Direction.Dot(dif)).Length2();
}
inline float PointPlaneDistanse(const Vector3D& p, const Plane& Plane) {
return fabsf(p.Dot(Plane.Normal) + Plane.Distance);
}
inline float PointPlaneSignedDistanse(const Vector3D& p, const Plane& Plane) {
return p.Dot(Plane.Normal) + Plane.Distance;
}
inline float RayRayDistance(const Ray& r1, const Ray& r2) {
if (fabsf(r1.Direction.Dot(r2.Direction)) < 1.0f) {
Vector3D dir = r1.Direction.Cross(r2.Direction).Normalized();
Vector3D dif = r1.Position - r2.Position;
return fabsf(dif.Dot(dir));
} else {
return RayPointDistance(r1, r2.Position);
}
}
inline Vector3D RayPlaneIntersection(const Ray& Ray, const Plane& Plane) {
float num = Plane.Distance + Ray.Position.Dot(Plane.Normal);
float denom = Ray.Direction.Dot(Plane.Normal);
return (-num / denom)*Ray.Direction + Ray.Position;
}
inline Vector3D RayPlaneIntersectionZ(const Ray& Ray, const Matrix4x4& Plane) {
Vector3D d = Plane.Vec3.Vec3 - Ray.Position;
float num = d.Dot(Plane.Vec2.Vec3);
float denom = Ray.Direction.Dot(Plane.Vec2.Vec3);
Vector3D ret = { 0, 0, num / denom };
if (denom) {
Vector3D inter = {
(ret.z * Ray.Direction.x - d.x),
(ret.z * Ray.Direction.y - d.y),
(ret.z * Ray.Direction.z - d.z)
};
ret.x = inter.Dot(Plane.Vec0.Vec3);
ret.y = inter.Dot(Plane.Vec1.Vec3);
}
return ret;
}
inline Vector3D RayPlaneIntersectionY(const Ray& Ray, const Matrix4x4& Plane) {
Vector3D d = Plane.Vec3.Vec3 - Ray.Position;
float num = d.Dot(Plane.Vec1.Vec3);
float denom = Ray.Direction.Dot(Plane.Vec1.Vec3);
Vector3D ret = { 0, 0, num / denom };
if (denom) {
Vector3D inter = {
(ret.z * Ray.Direction.x - d.x),
(ret.z * Ray.Direction.y - d.y),
(ret.z * Ray.Direction.z - d.z)
};
ret.x = inter.Dot(Plane.Vec0.Vec3);
ret.y = inter.Dot(Plane.Vec2.Vec3);
}
return ret;
}
inline float RayPlaneIntersectionDistance(const Ray& Ray, const Plane& Plane) {
float num = Plane.Distance + Ray.Position.Dot(Plane.Normal);
float denom = Ray.Direction.Dot(Plane.Normal);
return (-num / denom);
}
inline Plane CreatePlane(const Vector3D& a, const Vector3D& b, const Vector3D& c) {
auto vec = (c - a).Cross(b - a).Normalized();
return { vec, -vec.Dot(a) };
}
inline Vector3D TriangleNormal(const Vector3D& a, const Vector3D& b, const Vector3D& c) {
return (c - a).Cross(b - a).Normalized();
}
inline float TriangleArea(const Vector3D& a, const Vector3D& b, const Vector3D& c) {
return (c - a).Cross(b - a).Length() *0.5f;
}
inline Plane CreatePlaneZ(const Vector3D& Position, const Vector3D& Rotation) {
Plane ret;
float cy = cosf(Rotation.Yaw);
float sy = sinf(Rotation.Yaw);
float cp = cosf(Rotation.Pitch);
float sp = sinf(Rotation.Pitch);
ret.Normal.x = -cp*sy;
ret.Normal.y = sp;
ret.Normal.z = cp*cy;
ret.Distance = -Position.Dot(ret.Normal);
return ret;
}
inline Plane CreatePlaneY(const Vector3D& Position, const Vector3D& Rotation) {
Plane ret;
float cy = cosf(Rotation.Yaw);
float sy = sinf(Rotation.Yaw);
float cp = cosf(Rotation.Pitch);
float sp = sinf(Rotation.Pitch);
ret.Normal.x = sp*sy;
ret.Normal.y = cp;
ret.Normal.z = -cy*sp;
ret.Distance = -Position.Dot(ret.Normal);
return ret;
}
inline Plane Matrix_PlaneZ(const Matrix4x4& m) {
Plane ret;
ret.Normal.x = m.m02;
ret.Normal.y = m.m12;
ret.Normal.z = m.m22;
ret.Distance = -m.Vec3.Vec3.Dot(ret.Normal);
return ret;
}
inline Plane Matrix_PlaneY(const Matrix4x4& m) {
Plane ret;
ret.Normal.x = m.m01;
ret.Normal.y = m.m11;
ret.Normal.z = m.m21;
ret.Distance = -m.Vec3.Vec3.Dot(ret.Normal);
return ret;
}
inline Plane Matrix_PlaneX(const Matrix4x4& m) {
Plane ret;
ret.Normal.x = m.m00;
ret.Normal.y = m.m10;
ret.Normal.z = m.m20;
ret.Distance = -m.Vec3.Vec3.Dot(ret.Normal);
return ret;
}
inline Matrix4x4 MatrixFromPlaneZ(const Plane& Plane, const Vector3D& Position) {
Vector3D Pos = RayPlaneIntersection(Ray{ Position, Plane.Normal }, Plane);
Vector3D Y{ 0, 1.0f, 0 };
Vector3D X{ 1.0f, 0, 0 };
if (fabsf(Y.Dot(Plane.Normal)) < 0.9f) {
X = Y.Cross(Plane.Normal).Normalized();
Y = Plane.Normal.Cross(X).Normalized();
return Matrix4x4{
X.x, Y.x, Plane.Normal.x, 0,
X.y, Y.y, Plane.Normal.y, 0,
X.z, Y.z, Plane.Normal.z, 0,
Pos.x, Pos.y, Pos.z, 1.0f
};
} else {
Y = Plane.Normal.Cross(X).Normalized();
X = Y.Cross(Plane.Normal).Normalized();
return Matrix4x4{
X.x, Y.x, Plane.Normal.x, 0,
X.y, Y.y, Plane.Normal.y, 0,
X.z, Y.z, Plane.Normal.z, 0,
Pos.x, Pos.y, Pos.z, 1.0f
};
}
}
inline Vector3D Vector_Average(const Vector3D* List, size_t Size) {
Vector3D Sum{ 0, 0, 0 };
for (auto i = 0; i < Size; i++) {
Sum.x += List[i].x;
Sum.y += List[i].y;
Sum.z += List[i].z;
}
float ic = 1.0f / Size;
return Vector3D{ Sum.x*ic, Sum.y*ic, Sum.y*ic };
}
inline float Vector_Variance(const Vector3D* List, size_t Size, Vector3D& Mean) {
float ret = 0;
for (auto i = 0; i < Size; i++) {
ret += (Mean - List[i]).Length2();
}
return ret / Size;
}
inline float Vector_Variance(const Vector3D* List, size_t Size) {
Vector3D Sum{ 0, 0, 0 };
for (auto i = 0; i < Size; i++) {
Sum.x += List[i].x;
Sum.y += List[i].y;
Sum.z += List[i].z;
}
float ic = 1.0f / Size;
Vector3D Mean{ Sum.x*ic, Sum.y*ic, Sum.z*ic };
float ret = 0;
for (auto i = 0; i < Size; i++) {
ret += (Mean - List[i]).Length2();
}
return ret * ic;
}
inline Matrix3x3& CovarienceMatrix(Matrix3x3& out, Vector3D& Avg, const Vector3D* Vertices, int Count) {
out = Matrix3x3{ 0 };
Avg = Vector3D{ 0,0,0 };
for (int i = 0; i < Count; i++) {
Avg.x += Vertices[i].x;
Avg.y += Vertices[i].y;
Avg.z += Vertices[i].z;
}
float invCount = 1.0f / Count;
Avg.x *= invCount;
Avg.y *= invCount;
Avg.z *= invCount;
Matrix3x3 m2{ 0 };
Vector3D m;
for (int i = 0; i < Count; i++) {
m.x = Vertices[i].x - Avg.x;
m.y = Vertices[i].y - Avg.y;
m.z = Vertices[i].z - Avg.z;
m2.m00 += m.x * m.x; m2.m01 += m.x * m.y; m2.m02 += m.x * m.z;
/* m10 */ m2.m11 += m.y * m.y; m2.m12 += m.y * m.z;
/* m20 */ /* m21 */ m2.m22 += m.z * m.z;
}
out.m00 = m2.m00 * invCount; out.m01 = m2.m01 * invCount; out.m02 = m2.m02 * invCount;
out.m10 = out.m01; /* m10 */ out.m11 = m2.m11 * invCount; out.m12 = m2.m12 * invCount;
out.m20 = out.m02; /* m20 */ out.m21 = out.m12; /* m21 */ out.m22 = m2.m22 * invCount;
return out;
}
inline Matrix4x4& GetQuaternionMatrix2(const Quaternion& q, Matrix4x4& Out) {
Out.m22 = 1.0f - 2.0f * q.j * q.j - 2.0f * q.k * q.k;
Out.m12 = 2.0f * q.i * q.j + 2.0f * q.k * q.r;
Out.m02 = 2.0f * q.i * q.k - 2.0f * q.j * q.r;
Out.m21 = 2.0f * q.i * q.j - 2.0f * q.k * q.r;
Out.m11 = 1.0f - 2.0f * q.i * q.i - 2.0f * q.k * q.k;
Out.m01 = 2.0f * q.j * q.k + 2.0f * q.i * q.r;
Out.m20 = 2.0f * q.i * q.k + 2.0f * q.j * q.r;
Out.m10 = 2.0f * q.j * q.k - 2.0f * q.i * q.r;
Out.m00 = 1.0f - 2.0f * q.i * q.i - 2.0f * q.j * q.j;
Out.m03 = Out.m13 = Out.m23 = Out.m30 = Out.m31 = Out.m32 = 0;
Out.m33 = 1.0f;
return Out;
}
inline Matrix4x4& GetQuaternionMatrix_3x3(const Quaternion& q, Matrix4x4& Out) {
Out.m00 = 1.0f - 2.0f * q.j * q.j - 2.0f * q.k * q.k;
Out.m01 = 2.0f * q.i * q.j + 2.0f * q.k*q.r;
Out.m02 = 2.0f * q.i * q.k - 2.0f * q.j*q.r;
Out.m10 = 2.0f * q.i * q.j - 2.0f * q.k * q.r;
Out.m11 = 1.0f - 2.0f * q.i * q.i - 2.0f * q.k * q.k;
Out.m12 = 2.0f * q.j * q.k + 2.0f * q.i *q.r;
Out.m20 = 2.0f * q.i * q.k + 2.0f * q.j * q.r;
Out.m21 = 2.0f * q.j * q.k - 2.0f * q.i * q.r;
Out.m22 = 1.0f - 2.0f * q.i * q.i - 2.0f * q.j * q.j;
return Out;
}
inline Matrix4x4& GetQuaternionMatrix(const Quaternion& q, Matrix4x4& Out) {
Out.m00 = 1.0f - 2.0f * q.j * q.j - 2.0f * q.k * q.k;
Out.m01 = 2.0f * q.i * q.j + 2.0f * q.k*q.r;
Out.m02 = 2.0f * q.i * q.k - 2.0f * q.j*q.r;
Out.m03 = 0;
Out.m10 = 2.0f * q.i * q.j - 2.0f * q.k * q.r;
Out.m11 = 1.0f - 2.0f * q.i * q.i - 2.0f * q.k * q.k;
Out.m12 = 2.0f * q.j * q.k + 2.0f * q.i *q.r;
Out.m13 = 0;
Out.m20 = 2.0f * q.i * q.k + 2.0f * q.j * q.r;
Out.m21 = 2.0f * q.j * q.k - 2.0f * q.i * q.r;
Out.m22 = 1.0f - 2.0f * q.i * q.i - 2.0f * q.j * q.j;
Out.m23 = 0;
Out.m30 = 0;
Out.m31 = 0;
Out.m32 = 0;
Out.m33 = 1.0f;
return Out;
}
inline DualQuaternion CreateDualQuaternion(const Quaternion& Rotation, const Vector3D& Position) {
return{
Rotation.i,
Rotation.j,
Rotation.k,
Rotation.r,
(Position.x*Rotation.r + Position.y*Rotation.k - Position.z*Rotation.j)*0.5f,
(-Position.x*Rotation.k + Position.y*Rotation.r + Position.z*Rotation.i)*0.5f,
(Position.x*Rotation.j - Position.y*Rotation.i + Position.z*Rotation.r)*0.5f,
(-Position.x*Rotation.i - Position.y*Rotation.j - Position.z*Rotation.k)*0.5f
};
}
inline Matrix4x4 GetDualQuaternionMatrix(const DualQuaternion& q) {
Matrix4x4 ret;
GetQuaternionMatrix(q.Real, ret);
auto t = (q.Dual * 2.0f) * Conjugate(q.Real);
ret.m30 = t.i;
ret.m31 = t.j;
ret.m32 = t.k;
return ret;
}
inline Matrix4x4& GetDualQuaternionMatrix(const DualQuaternion& q, Matrix4x4& ret) {
GetQuaternionMatrix(q.Real, ret);
auto t = (q.Dual * 2.0f) * Conjugate(q.Real);
ret.m30 = t.i;
ret.m31 = t.j;
ret.m32 = t.k;
return ret;
}
} | [
"pervertexgr@gmail.com"
] | pervertexgr@gmail.com |
590d455487c10da7ea5704d033d81871da737fac | e1b2d76dca90b1480d7d62bc09385f35855d743d | /Project1/Utility/Keyboard.cpp | 04fe3ed18666be596b08a591891c30d8e5490c77 | [] | no_license | Dem-36/DirectXTestProject | 49e09b29b50fdc9a5cf5c44bda7e05417bcd52b8 | dbfd8d620130ee43235642a26d5c087f55db6981 | refs/heads/master | 2022-09-11T11:30:14.619416 | 2020-06-02T15:19:34 | 2020-06-02T15:19:34 | 260,963,319 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,533 | cpp | #include "Keyboard.h"
bool Keyboard::KeyIsPressed(unsigned char keyCode) const noexcept
{
return keyStates[keyCode];
}
//キーの読み込み
Keyboard::Event Keyboard::ReadKey() noexcept
{
if (keyBuffer.size() > 0u) {
//先頭の要素を取得
Event e = keyBuffer.front();
//先頭の要素を削除する(eに先頭要素がコピーされている)
keyBuffer.pop();
return e;
}
else {
return Event();
}
}
//中身が空 = 要素数が0かどうか
bool Keyboard::KeyIsEmpty() const noexcept
{
return keyBuffer.empty();
}
//新しいqueueを作成
void Keyboard::FlushKey() noexcept
{
keyBuffer = std::queue<Event>();
}
//char型のキーの読み込み
char Keyboard::ReadChar() noexcept
{
if (charBuffer.size() > 0u) {
//先頭の要素を取得
unsigned char charCode = charBuffer.front();
//先頭の要素を削除する(eに先頭要素がコピーされている)
charBuffer.pop();
return charCode;
}
else {
return 0;
}
}
//中身が空 = 要素数が0かどうか
bool Keyboard::CharIsEmpty() const noexcept
{
return charBuffer.empty();
}
//新しいqueueを作成
void Keyboard::FlushChar() noexcept
{
charBuffer = std::queue<char>();
}
//二つのqueueを新しく生成
void Keyboard::Flush()
{
FlushKey();
FlushChar();
}
void Keyboard::EnableAutoRepeat() noexcept
{
autoRepeaEnabled = true;
}
void Keyboard::DisableAutoRepeat() noexcept
{
autoRepeaEnabled = false;
}
bool Keyboard::AutoRepeatIsEnabled() const noexcept
{
return autoRepeaEnabled;
}
//private side
//キーが押されたときに呼ばれる
//queue = 後入れ先出
void Keyboard::OnKeyPressed(unsigned char keyCode) noexcept
{
keyStates[keyCode] = true;
//最後尾に要素を追加
keyBuffer.push(Keyboard::Event(Keyboard::Event::KeyType::Press, keyCode));
//バッファが大きすぎるときにそな得て呼ぶ
TrimBuffer(keyBuffer);
}
void Keyboard::OnKeyReleased(unsigned char keyCode) noexcept
{
keyStates[keyCode] = false;
keyBuffer.push(Keyboard::Event(Keyboard::Event::KeyType::Release, keyCode));
TrimBuffer(keyBuffer);
}
void Keyboard::OnChar(char character) noexcept
{
charBuffer.push(character);
TrimBuffer(charBuffer);
}
void Keyboard::ClearState() noexcept
{
keyStates.reset();
}
//バッファのサイズが最大許容を超えているかどうか
template<typename T>
void Keyboard::TrimBuffer(std::queue<T>& buffer)noexcept {
//基底のサイズになるまで先頭要素を削除する
while (buffer.size() > bufferSize) {
buffer.pop();
}
}
| [
"onoderadesk0402@gmail.com"
] | onoderadesk0402@gmail.com |
cfd5b2b8fe7f7297076742fd0f318d74124c3f99 | 0934782cc900ef32616d3c5204bca05b2aa34032 | /SDK/RC_SettingsInfo_VSyncEnabled_classes.hpp | 39cdc2247e35e70d89927b4b38db3839cb28f12f | [] | no_license | igromanru/RogueCompany-SDK-9-24-2020 | da959376e5464e505486cf0df01fff71dde212cf | fcab8fd45cf256c6f521d94f295e2a76701c411d | refs/heads/master | 2022-12-18T05:30:30.039119 | 2020-09-25T01:12:25 | 2020-09-25T01:12:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 684 | hpp | #pragma once
// RogueCompany (4.24) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass SettingsInfo_VSyncEnabled.SettingsInfo_VSyncEnabled_C
// 0x0000 (0x00F0 - 0x00F0)
class USettingsInfo_VSyncEnabled_C : public UKSSettingsInfo_Generic
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass SettingsInfo_VSyncEnabled.SettingsInfo_VSyncEnabled_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"60810131+frankie-11@users.noreply.github.com"
] | 60810131+frankie-11@users.noreply.github.com |
80fe3b9638ac2087f7c29776c307fcd24cae3fe5 | 2ecb69587447e1454f8c15f2fba3e21fbe8242c8 | /hw/cumulative_sum/main.cpp | 2b336cb7c3297802beec31e6d8b5bd31aeca01f1 | [] | no_license | isqnwtn/Parallel-Programming-sem6 | 493639a401221ba2a328a5a08861eb2005f3798a | e35c38405ef13eba2ddbc438192bab951e1086e7 | refs/heads/master | 2021-10-23T09:19:29.782744 | 2019-03-16T18:56:37 | 2019-03-16T18:56:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,430 | cpp | #include <iostream>
#include <stdio.h>
#include <thread>
#include <chrono>
#define SUM_LIMIT 1000000000
#define MAX_NUM_THREADS 1000
void partial_sum(int my_id,int my_start,int my_end);
long double partial_sum_holder[MAX_NUM_THREADS];
int main(int argc,char* argv[])
{
std::thread t_partial_sums[MAX_NUM_THREADS];
printf("Commencing program\n");
auto start = std::chrono::steady_clock::now();
for(int thread_id=0; thread_id<MAX_NUM_THREADS; thread_id++)
{
int thread_start=(SUM_LIMIT/MAX_NUM_THREADS)*thread_id;
int thread_end=(SUM_LIMIT/MAX_NUM_THREADS)*(thread_id+1);
t_partial_sums[thread_id] = std::thread(partial_sum,thread_id,thread_start,thread_end);
}
long double final_sum = 0.0;
for(int thread_id=0; thread_id < MAX_NUM_THREADS; thread_id++)
{
t_partial_sums[thread_id].join();
final_sum += partial_sum_holder[thread_id];
}
auto end = std::chrono::steady_clock::now();
printf("Sum is : %Lf \n",4.0*final_sum);
std::cout<<"time elapsed:"<<std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()<<"ns"<<std::endl;
}
void partial_sum(int my_id,int my_start,int my_end)
{
long double sum = 0.0;
double sign;
for(int my_i = my_start; my_i<my_end; my_i++)
{
sign = (my_i%2==0)?1.0:-1.0;
sum += sign*1.0/(2*(double)my_i+1);
}
partial_sum_holder[my_id] = sum;
} | [
"JarYamsiv"
] | JarYamsiv |
71457a0071cac41fca8483639551fdc84d2f000b | e3ac6d1aafff3fdfb95159c54925aded869711ed | /Temp/StagingArea/Data/il2cppOutput/t3067249560.h | 4a88087a07e32a954441c4b7298a5c004eb2998e | [] | no_license | charlantkj/refugeeGame- | 21a80d17cf5c82eed2112f04ac67d8f3b6761c1d | d5ea832a33e652ed7cdbabcf740e599497a99e4d | refs/heads/master | 2021-01-01T05:26:18.635755 | 2016-04-24T22:33:48 | 2016-04-24T22:33:48 | 56,997,457 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
struct t1145112466;
#include "Il2CppObject.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
struct t3067249560 : public Il2CppObject
{
public:
t1145112466 * f0;
public:
inline static int32_t fog0() { return static_cast<int32_t>(offsetof(t3067249560, f0)); }
inline t1145112466 * fg0() const { return f0; }
inline t1145112466 ** fag0() { return &f0; }
inline void fs0(t1145112466 * value)
{
f0 = value;
Il2CppCodeGenWriteBarrier(&f0, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"charlotteantschukovkjaer@Charlottes-MacBook-Air.local"
] | charlotteantschukovkjaer@Charlottes-MacBook-Air.local |
030d79ddf9dc3ccf015b56e4f62b75ea892057d5 | 466e3ae6b0cd31eedf86677e33bdd00eeb53efb9 | /liboh/plugins/ogre/resourceManager/GraphicsResourceManager.hpp | 02db94a5bc2c3ee7a2ac1893474c2dd350fd7231 | [
"BSD-3-Clause"
] | permissive | jordanmisiura/sirikata | eae9ea44c32510dae8689959efa1a5163d0b71ed | ce91b4cf2f250d43ae97f192e3f0a64040fb7d8b | refs/heads/master | 2021-01-20T20:15:06.927030 | 2009-04-24T11:38:13 | 2009-04-24T11:38:13 | 180,246 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,839 | hpp | /* Meru
* GraphicsResourceManager.hpp
*
* Copyright (c) 2009, Stanford University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _GRAPHICS_RESOURCE_MANAGER_HPP_
#define _GRAPHICS_RESOURCE_MANAGER_HPP_
#include "GraphicsResource.hpp"
#include "MeruDefs.hpp"
#include <oh/ProxyObject.hpp>
#include "Singleton.hpp"
#include "Event.hpp"
namespace Meru {
class DependencyManager;
class GraphicsEntity;
class GraphicsResourceManager : public ManualSingleton<GraphicsResourceManager>
{
protected:
struct GraphicsResourcePriorityLessThanFunctor
{
bool operator()(const std::pair<float, GraphicsResource*>& key1, const std::pair<float, GraphicsResource*>& key2) const {
if (key1.first != key2.first)
return key1.first > key2.first;
return key1.second < key2.second;
}
};
typedef std::set<std::pair<float, GraphicsResource *>, GraphicsResourcePriorityLessThanFunctor> ResourcePriorityQueue;
public:
GraphicsResourceManager();
virtual ~GraphicsResourceManager();
//virtual void loadMesh(WeakProxyPtr proxy, const String &meshName);
void computeLoadedSet();
SharedResourcePtr getResourceEntity(const SpaceObjectReference &id, GraphicsEntity *graphicsEntity);
SharedResourcePtr getResourceAsset(const URI &id, GraphicsResource::Type resourceType);
DependencyManager* getDependencyManager() {
return mDependencyManager;
}
void unregisterResource(GraphicsResource* resource);
float getBudget() {
return mBudget / (1024.0f * 1024.0f);
}
void setBudget(float budget) {
mBudget = budget * (1024.0f * 1024.0f);
}
void updateLoadValue(GraphicsResource* resource, float oldValue);
void registerLoad(GraphicsResource* resource, float oldValue);
void unregisterLoad(GraphicsResource* resource);
void setEnabled(bool enabled) {
mEnabled = enabled;
}
protected:
WeakResourcePtr getResource(const String &id);
EventResponse tick(const EventPtr &evtPtr);
std::map<String, WeakResourcePtr> mIDResourceMap;
std::set<GraphicsResource *> mResources;
std::set<GraphicsResource *> mToUnload;
std::set<GraphicsResource *> mEntities;
//std::set<GraphicsResource *> mMeshes;
ResourcePriorityQueue mQueue;
unsigned int mEpoch;
DependencyManager *mDependencyManager;
float mBudget;
SubscriptionId mTickListener;
bool mEnabled;
};
}
#endif
| [
"patrick.horn@gmail.com"
] | patrick.horn@gmail.com |
2845e8e546fc29d3fc77a3a134f38162d2d9f65d | 795d7e314131c498c000633bd4bf7cf8f3220254 | /Unreal/UnCoreCompression.cpp | c370bbda36bead8f271fc74225a23adda61d2225 | [
"BSD-3-Clause"
] | permissive | TokTil-Dev/UEViewer | 73479969adb37f9d18afccafc4e3b5b0511cba58 | d9a20efce7c495c00500e81956b63056a9640fd1 | refs/heads/master | 2022-12-16T11:07:27.021444 | 2020-09-19T12:41:01 | 2020-09-19T12:41:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,852 | cpp | #include "Core.h"
#include "UnCore.h"
// includes for package decompression
#include "lzo/lzo1x.h"
#include <zlib.h>
#if SUPPORT_XBOX360
# if !USE_XDK
# include "mspack/mspack.h"
# include "mspack/lzx.h"
# else // USE_XDK
# if _WIN32
# pragma comment(lib, "xcompress.lib")
extern "C"
{
int __stdcall XMemCreateDecompressionContext(int CodecType, const void* pCodecParams, unsigned Flags, void** pContext);
void __stdcall XMemDestroyDecompressionContext(void* Context);
int __stdcall XMemDecompress(void* Context, void* pDestination, size_t* pDestSize, const void* pSource, size_t SrcSize);
}
# else // _WIN32
# error XDK build is not supported on this platform
# endif // _WIN32
# endif // USE_XDK
#endif // SUPPORT_XBOX360
#if USE_LZ4
# include "lz4/lz4.h"
#endif
// AES code for UE4
#include "rijndael/rijndael.h"
/*-----------------------------------------------------------------------------
ZLib support
-----------------------------------------------------------------------------*/
// using Core memory manager
extern "C" void *zcalloc(void* opaque, int items, int size)
{
return appMalloc(items * size);
}
extern "C" void zcfree(void* opaque, void *ptr)
{
appFree(ptr);
}
// Constants from zutil.c (copy-pasted here to avoid including whole C file)
extern "C" const char * const z_errmsg[10] =
{
"need dictionary", /* Z_NEED_DICT 2 */
"stream end", /* Z_STREAM_END 1 */
"", /* Z_OK 0 */
"file error", /* Z_ERRNO (-1) */
"stream error", /* Z_STREAM_ERROR (-2) */
"data error", /* Z_DATA_ERROR (-3) */
"insufficient memory", /* Z_MEM_ERROR (-4) */
"buffer error", /* Z_BUF_ERROR (-5) */
"incompatible version",/* Z_VERSION_ERROR (-6) */
""
};
/*-----------------------------------------------------------------------------
LZX support
-----------------------------------------------------------------------------*/
#if !USE_XDK && SUPPORT_XBOX360
struct mspack_file
{
byte* buf;
int bufSize;
int pos;
int rest;
};
static int mspack_read(mspack_file *file, void *buffer, int bytes)
{
guard(mspack_read);
if (!file->rest)
{
// read block header
if (file->buf[file->pos] == 0xFF)
{
// [0] = FF
// [1,2] = uncompressed block size
// [3,4] = compressed block size
file->rest = (file->buf[file->pos+3] << 8) | file->buf[file->pos+4];
file->pos += 5;
}
else
{
// [0,1] = compressed size
file->rest = (file->buf[file->pos+0] << 8) | file->buf[file->pos+1];
file->pos += 2;
}
if (file->rest > file->bufSize - file->pos)
file->rest = file->bufSize - file->pos;
}
if (bytes > file->rest) bytes = file->rest;
if (bytes <= 0) return 0;
// copy block data
memcpy(buffer, file->buf + file->pos, bytes);
file->pos += bytes;
file->rest -= bytes;
return bytes;
unguard;
}
static int mspack_write(mspack_file *file, void *buffer, int bytes)
{
guard(mspack_write);
assert(file->pos + bytes <= file->bufSize);
memcpy(file->buf + file->pos, buffer, bytes);
file->pos += bytes;
return bytes;
unguard;
}
static void *mspack_alloc(mspack_system *self, size_t bytes)
{
return appMalloc(bytes);
}
static void mspack_free(void *ptr)
{
appFree(ptr);
}
static void mspack_copy(void *src, void *dst, size_t bytes)
{
memcpy(dst, src, bytes);
}
static struct mspack_system lzxSys =
{
NULL, // open
NULL, // close
mspack_read,
mspack_write,
NULL, // seek
NULL, // tell
NULL, // message
mspack_alloc,
mspack_free,
mspack_copy
};
static void appDecompressLZX(byte *CompressedBuffer, int CompressedSize, byte *UncompressedBuffer, int UncompressedSize)
{
guard(appDecompressLZX);
// setup streams
mspack_file src, dst;
src.buf = CompressedBuffer;
src.bufSize = CompressedSize;
src.pos = 0;
src.rest = 0;
dst.buf = UncompressedBuffer;
dst.bufSize = UncompressedSize;
dst.pos = 0;
// prepare decompressor
lzxd_stream *lzxd = lzxd_init(&lzxSys, &src, &dst, 17, 0, 256*1024, UncompressedSize);
assert(lzxd);
// decompress
int r = lzxd_decompress(lzxd, UncompressedSize);
if (r != MSPACK_ERR_OK)
appError("lzxd_decompress(%d,%d) returned %d", CompressedSize, UncompressedSize, r);
// free resources
lzxd_free(lzxd);
unguard;
}
#endif // USE_XDK
/*-----------------------------------------------------------------------------
appDecompress()
-----------------------------------------------------------------------------*/
// Decryptors for compressed data
void DecryptBladeAndSoul(byte* CompressedBuffer, int CompressedSize);
void DecryptTaoYuan(byte* CompressedBuffer, int CompressedSize);
void DecryptDevlsThird(byte* CompressedBuffer, int CompressedSize);
static int FoundCompression = -1;
int appDecompress(byte *CompressedBuffer, int CompressedSize, byte *UncompressedBuffer, int UncompressedSize, int Flags)
{
int OldFlags = Flags;
guard(appDecompress);
#if GEARSU
if (GForceGame == GAME_GoWU)
{
// It is strange, but this game has 2 Flags both used for LZ4 - probably they were used for different compression
// settings of the same algorithm.
if (Flags == 4 || Flags == 32) Flags = COMPRESS_LZ4;
}
#endif // GEARSU
#if BLADENSOUL
if (GForceGame == GAME_BladeNSoul && Flags == COMPRESS_LZO_ENC_BNS) // note: GForceGame is required (to not pass 'Game' here)
{
DecryptBladeAndSoul(CompressedBuffer, CompressedSize);
// overide compression
Flags = COMPRESS_LZO;
}
#endif // BLADENSOUL
#if SMITE
if (GForceGame == GAME_Smite)
{
if (Flags & 512)
{
// Simple encryption
for (int i = 0; i < CompressedSize; i++)
CompressedBuffer[i] ^= 0x2A;
// Remove encryption flag
Flags &= ~512;
}
#if USE_OODLE
if (Flags == 8)
{
// Overide compression, appeared in late 2019 builds
Flags = COMPRESS_OODLE;
}
#endif
}
#endif // SMITE
#if TAO_YUAN
if (GForceGame == GAME_TaoYuan) // note: GForceGame is required (to not pass 'Game' here);
{
DecryptTaoYuan(CompressedBuffer, CompressedSize);
}
#endif // TAO_YUAN
#if DEVILS_THIRD
if ((GForceGame == GAME_DevilsThird) && (Flags & 8))
{
DecryptDevlsThird(CompressedBuffer, CompressedSize);
// override compression
Flags &= ~8;
}
#endif // DEVILS_THIRD
if (Flags == COMPRESS_FIND && FoundCompression >= 0)
{
// Do not detect compression multiple times: there were cases (Sea of Thieves) when
// game is using LZ4 compression, however its first 2 bytes occasionally matched oodle,
// so one of blocks were mistakenly used oodle.
Flags = FoundCompression;
}
else if (Flags == COMPRESS_FIND && CompressedSize >= 2)
{
byte b1 = CompressedBuffer[0];
byte b2 = CompressedBuffer[1];
// detect compression
// zlib:
// http://tools.ietf.org/html/rfc1950
// http://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like
// oodle:
// https://github.com/powzix/ooz, kraken.cpp, Kraken_ParseHeader()
if ( b1 == 0x78 && // b1=CMF: 7=32k buffer (CINFO), 8=deflate (CM)
(b2 == 0x9C || b2 == 0xDA) ) // b2=FLG
{
Flags = COMPRESS_ZLIB;
}
#if USE_OODLE
else if ((b1 == 0x8C || b1 == 0xCC) && (b2 == 5 || b2 == 6 || b2 == 10 || b2 == 11 || b2 == 12))
{
Flags = COMPRESS_OODLE;
}
#endif // USE_OODLE
#if USE_LZ4
else if (GForceGame >= GAME_UE4_BASE)
{
Flags = COMPRESS_LZ4; // in most cases UE4 games are using either oodle or lz4 - the first one is explicitly recognizable
}
#endif // USE_LZ4
else
{
Flags = COMPRESS_LZO; // LZO was used only with UE3 games as standard compression method
}
// Cache detected compression method
FoundCompression = Flags;
}
if (Flags == COMPRESS_LZO)
{
int r;
r = lzo_init();
if (r != LZO_E_OK) appError("lzo_init() returned %d", r);
lzo_uint newLen = UncompressedSize;
r = lzo1x_decompress_safe(CompressedBuffer, CompressedSize, UncompressedBuffer, &newLen, NULL);
if (r != LZO_E_OK)
{
if (CompressedSize != UncompressedSize)
{
appError("lzo_decompress(%d,%d) returned %d", CompressedSize, UncompressedSize, r);
}
else
{
// This situation is unusual for UE3, it happened with Alice, and Batman 3
// TODO: probably extend this code for other compression methods too
memcpy(UncompressedBuffer, CompressedBuffer, UncompressedSize);
return UncompressedSize;
}
}
if (newLen != UncompressedSize) appError("len mismatch: %d != %d", newLen, UncompressedSize);
return newLen;
}
if (Flags == COMPRESS_ZLIB)
{
#if 0
appError("appDecompress: Zlib compression is not supported");
#else
unsigned long newLen = UncompressedSize;
int r = uncompress(UncompressedBuffer, &newLen, CompressedBuffer, CompressedSize);
if (r != Z_OK) appError("zlib uncompress(%d,%d) returned %d", CompressedSize, UncompressedSize, r);
// if (newLen != UncompressedSize) appError("len mismatch: %d != %d", newLen, UncompressedSize); -- needed by Bioshock
return newLen;
#endif
}
if (Flags == COMPRESS_LZX)
{
#if SUPPORT_XBOX360
# if !USE_XDK
appDecompressLZX(CompressedBuffer, CompressedSize, UncompressedBuffer, UncompressedSize);
return UncompressedSize;
# else
void *context;
int r;
r = XMemCreateDecompressionContext(0, NULL, 0, &context);
if (r < 0) appError("XMemCreateDecompressionContext failed");
unsigned int newLen = UncompressedSize;
r = XMemDecompress(context, UncompressedBuffer, &newLen, CompressedBuffer, CompressedSize);
if (r < 0) appError("XMemDecompress failed");
if (newLen != UncompressedSize) appError("len mismatch: %d != %d", newLen, UncompressedSize);
XMemDestroyDecompressionContext(context);
return newLen;
# endif // USE_XDK
#else // SUPPORT_XBOX360
appError("appDecompress: Lzx compression is not supported");
#endif // SUPPORT_XBOX360
}
#if USE_LZ4
if (Flags == COMPRESS_LZ4)
{
int newLen = LZ4_decompress_safe((const char*)CompressedBuffer, (char*)UncompressedBuffer, CompressedSize, UncompressedSize);
if (newLen <= 0)
appError("LZ4_decompress_safe returned %d\n", newLen);
if (newLen != UncompressedSize) appError("lz4 len mismatch: %d != %d", newLen, UncompressedSize);
return newLen;
}
#endif // USE_LZ4
#if USE_OODLE // defined for supported engine versions
if (Flags == COMPRESS_OODLE)
{
#if HAS_OODLE // defined in project file
int Kraken_Decompress(const byte *src, size_t src_len, byte *dst, size_t dst_len);
int newLen = Kraken_Decompress(CompressedBuffer, CompressedSize, UncompressedBuffer, UncompressedSize);
if (newLen <= 0)
appError("Kraken_Decompress returned %d (magic=%02X/%02X)\n", newLen, CompressedBuffer[0], CompressedBuffer[1]);
if (newLen != UncompressedSize) appError("oodle len mismatch: %d != %d", newLen, UncompressedSize);
return newLen;
#else
appError("appDecompress: Oodle compression is not supported");
#endif // HAS_OODLE
}
#endif // USE_OODLE
appError("appDecompress: unknown compression flags: %d", Flags);
return 0;
unguardf("CompSize=%d UncompSize=%d Flags=0x%X", CompressedSize, UncompressedSize, OldFlags);
}
/*-----------------------------------------------------------------------------
AES support
-----------------------------------------------------------------------------*/
#if UNREAL4
FString GAesKey;
#define AES_KEYBITS 256
void appDecryptAES(byte* Data, int Size, const char* Key, int KeyLen)
{
guard(appDecryptAES);
if (KeyLen <= 0)
{
KeyLen = strlen(Key);
}
if (KeyLen == 0)
{
appErrorNoLog("Trying to decrypt AES block without providing an AES key");
}
if (KeyLen < KEYLENGTH(AES_KEYBITS))
{
appErrorNoLog("AES key is too short");
}
assert((Size & 15) == 0);
unsigned long rk[RKLENGTH(AES_KEYBITS)];
int nrounds = rijndaelSetupDecrypt(rk, (const byte*)Key, AES_KEYBITS);
for (int pos = 0; pos < Size; pos += 16)
{
rijndaelDecrypt(rk, nrounds, Data + pos, Data + pos);
}
unguard;
}
#endif // UNREAL4
| [
"git@gildor.org"
] | git@gildor.org |
fc10cdcbc173f967a9b4b55c825094b048301eeb | 65a6656078c21433d58b2e41a2be7e63cf9863ca | /LocalDrive/DIO.h | e807da2135e7924b0069694367436f3068d43d8d | [] | no_license | duchuan1/DAT2C | e11b41e6e6efb4caf46dda6ac2c564e8a51d742c | f49d8a0209c30fc01cf518e5582cb516808941ef | refs/heads/master | 2021-01-16T17:53:35.614058 | 2014-02-01T20:44:02 | 2014-02-01T20:44:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 394 | h | #pragma once
namespace LocalDrive {
class CDIO
{
public:
CDIO(void);
virtual ~CDIO(void);
virtual int open() = 0;
virtual void close() = 0;
virtual int check_di(int index) = 0;
virtual int read_di(int index) = 0;
virtual int check_do(int index) = 0;
virtual unsigned char read_do(int index) = 0;
virtual int write_do(int index,bool bCloseOrOpen) = 0;
};
};//namespace LocalDrive
| [
"gf4t47@gmail.com"
] | gf4t47@gmail.com |
c64d93c00f2265d4f5d19c6f6a3730b565b07dc5 | 7c04b69b31485f22d5e5723ab586a34e2f6ef75e | /upnp.cpp | 35c9813bc64c2a45f2533bf9d5e7ae99a4f8f1a8 | [] | no_license | Dengue/Port-Forward | 35e6678bbb3f0f1350cc77da83ffe64ca8a45356 | 156c004b623b4dd54182659925a3bdc160a893eb | refs/heads/master | 2016-09-09T17:02:49.184040 | 2014-06-18T12:06:27 | 2014-06-18T12:06:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,226 | cpp | #include <iostream>
#include "boost\asio.hpp"
#include "boost\bind.hpp"
#include <boost\shared_ptr.hpp>
#include "boost\regex.hpp"
#include "boost\asio\deadline_timer.hpp"
#include "boost\date_time\posix_time\posix_time.hpp"
#include <list>
#include <stdlib.h>
#define OK 0
#define FAIL -1
using namespace boost::asio;
typedef boost::shared_ptr<ip::tcp::socket> socket_ptr;
class Upnp{
struct mapping_desc{
std::string external_ip;
std::string external_port;
std::string internal_ip;
std::string internal_port;
std::string protocol;
std::string port_forwading_description;
friend bool operator==(const mapping_desc& right,const mapping_desc &left)
{
return (right.external_port == left.external_port &&
right.external_ip == left.external_ip &&
right.protocol == left.protocol) ? 1 : 0;
}
};
io_service service;
boost::asio::ip::address rout_addr;
std::list<mapping_desc> mapping_list;
std::list<mapping_desc> my_mapping_list;
size_t ReadComplete(char* buff_, const boost::system::error_code & err, size_t bytes) {
if (err)
return 0;
char crlf[] = { '\r', '\n', '\r', '\n' };
bool found = std::find_end(buff_, buff_ + bytes, crlf, crlf + 4) < buff_ + bytes;
return found ? 0 : 1;
}
size_t ReadComplete2(int length, const boost::system::error_code & err, size_t bytes) {
if (err)
return 0;
if (bytes == length)
return 0;
return 1;
}
size_t ReadComplete3(char* buff_, const boost::system::error_code & err, size_t bytes) {
if (err)
return 0;
char crlf[] = { '\r', '\n' };
bool found = std::find_end(buff_, buff_ + bytes, crlf, crlf + 2) < buff_ + bytes;
return found ? 0 : 1;
}
int SendReqToRout(socket_ptr sock_ptr, const std::string request, std::string *responce)
{
int bytes_sent = sock_ptr->send(buffer(request));
char buff_[1024];
size_t bytes_recived = read(*sock_ptr, buffer(buff_), boost::bind(&Upnp::ReadComplete, this,buff_, _1, _2));
std::string responce_header(buff_, bytes_recived);
int Len_pos;
if (responce_header.find("HTTP/1.1 200 OK") >= bytes_recived)
{
*responce = responce_header;
return FAIL;
}
else if ((Len_pos = responce_header.find("Content-Length: ")) < bytes_recived)
{
Len_pos += 16;
int end_line = responce_header.find("\r\n", Len_pos);
int Len_len = end_line - Len_pos;
std::string Length = responce_header.substr(Len_pos, Len_len);
std::stringstream ss;
ss << Length;
int length;
ss >> length;
size_t bytes_recived = read(*sock_ptr, buffer(buff_), boost::bind(&Upnp::ReadComplete2, this, length, _1, _2));
*responce = std::string(buff_, bytes_recived);
}
else if (responce_header.find("Transfer-Encoding: chunked\r\n") < bytes_recived)
{
std::string result;
while (1)
{
int chunk_len_len = read(*sock_ptr, buffer(buff_), boost::bind(&Upnp::ReadComplete3, this, buff_, _1, _2));
chunk_len_len -= 2;
char* char_chunk_len = new char[chunk_len_len + 1];
for (int i = 0; buff_[i] != '\r'; i++)
char_chunk_len[i] = buff_[i];
char_chunk_len[chunk_len_len] = '\0';
char *next;
long int chunk_len = strtol(char_chunk_len, &next, 16);
free(char_chunk_len);
if (chunk_len == 0)
{
break;
}
chunk_len += 2;
char c[1];
char* chunk = new char[chunk_len + 1];
int j = 0;
while (read(*sock_ptr, buffer(c)) > 0)
{
chunk[j] = c[0];
j++;
if (j == chunk_len)
break;
}
chunk[chunk_len] = '\0';
result.append(chunk);
free(chunk);
}
*responce = result;
}
return OK;
}
public:
int SearchForRouter(std::string* search_result)
{
boost::asio::ip::tcp::resolver resolver(service);
boost::asio::ip::tcp::resolver::query query(boost::asio::ip::host_name(), "");
boost::asio::ip::tcp::resolver::iterator it = resolver.resolve(query);
boost::asio::ip::tcp::endpoint endpoint = *it;
boost::asio::ip::address addr;
while (it != boost::asio::ip::tcp::resolver::iterator())
{
addr = (it++)->endpoint().address();
if (addr.is_v4())
{
break;
}
}
ip::udp::endpoint ep(addr, 0);
ip::udp::socket multicast_socket(service, ep.protocol());
multicast_socket.bind(ep);
std::string search_req("M-SEARCH * HTTP/1.1\r\nHost:239.255.255.250:1900\r\nST:urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\nMan:\"ssdp:discover\"\r\nMX:3\r\n\r\n");
ip::udp::endpoint multicast_address(ip::address::from_string("239.255.255.250"), 1900);
int bytes_send = multicast_socket.send_to(buffer(search_req), multicast_address);
ip::udp::endpoint sender_ep;
char buff[1024];
int bytes_recieved = multicast_socket.receive_from(buffer(buff), sender_ep);
buff[bytes_recieved] = '\0';
*search_result = buff;
multicast_socket.close();
return OK;
}
int FindRouterLocation(const std::string Router, std::string* location)
{
boost::regex xRegEx("192.168(.(\\d){1,3}){2}:\\d+");
boost::smatch xResults;
boost::regex_search(Router, xResults, xRegEx);
*location = xResults[0];
xRegEx.assign("192.168(.(\\d){1,3}){2}");
boost::regex_search(*location, xResults, xRegEx);
rout_addr = boost::asio::ip::address(ip::address::from_string(xResults[0]));
return OK;
}
int GetDeviceDescription(const std::string location, std::string* device_description)
{
std::string responce;
ip::tcp::endpoint ep(rout_addr, 80);
socket_ptr sock_ptr(new ip::tcp::socket(service));
sock_ptr->connect(ep);
std::string get_request("GET http://" + location + "/DeviceDescription.xml HTTP/1.1 \r\n HOST:192.168.1.1:80 \r\n ACCEPT-LANGUAGE: EN-en \r\n\r\n");
if (SendReqToRout(sock_ptr, get_request, &responce) != OK)
{
sock_ptr->close();
return FAIL;
}
sock_ptr->close();
return OK;
}
int GetWanIpServiceDescrption(const std::string location, std::string* wan_ip_service_descrption)
{
std::string responce;
ip::tcp::endpoint ep(rout_addr, 80);
socket_ptr sock_ptr(new ip::tcp::socket(service));
sock_ptr->connect(ep);
std::string get_request("GET http://" + location + "/WanIpConn.xml HTTP/1.1 \r\n HOST:192.168.1.1:80 \r\n ACCEPT-LANGUAGE: EN-en \r\n\r\n");
if (SendReqToRout(sock_ptr, get_request, &responce) != OK)
{
sock_ptr->close();
return FAIL;
}
sock_ptr->close();
*wan_ip_service_descrption = responce;
return OK;
}
int GetExternalIpAddress(const std::string location, std::string* external_ip)
{
std::string responce;
ip::tcp::endpoint ep(rout_addr, 80);
socket_ptr sock_ptr(new ip::tcp::socket(service));
sock_ptr->connect(ep);
std::string get_request("POST /UD/?3 HTTP/1.1\r\n"
"Content-Type: text/xml; charset=\"utf-8\"\r\n"
"SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress\"\r\n"
"User-Agent: Mozilla/4.0 (compatible; UPnP/1.0; Windows 9x)\r\n"
"Host: " + location + "\r\n"
"Content-Length: 303\r\n"
"Connection: Close\r\n"
"Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\n\r\n"
"<?xml version=\"1.0\"?>"
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<SOAP-ENV:Body>"
"<m:GetExternalIPAddress xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"/>"
"</SOAP-ENV:Body>"
"</SOAP-ENV:Envelope>\r\n\r\n");
if (SendReqToRout(sock_ptr, get_request, &responce) != OK)
{
sock_ptr->close();
return FAIL;
}
sock_ptr->close();
int i = 0;
int begin = responce.find("<NewExternalIPAddress>") + 22;
int end = responce.find("</NewExternalIPAddress>");
*external_ip = responce.substr(begin, end - begin);
sock_ptr->close();
return OK;
}
int NewPortMapping(const std::string location, const std::string external_ip, const std::string external_port, const std::string internal_ip, const std::string internal_port, const std::string protocol, const std::string port_forwading_description)
{
std::string responce;
ip::tcp::endpoint ep(rout_addr, 80);
socket_ptr sock_ptr(new ip::tcp::socket(service));
sock_ptr->connect(ep);
std::string add_forwading_request("<?xml version=\"1.0\"?>\r\n"
"<SOAP-ENV:Envelope\r\n xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"
"<SOAP-ENV:Body>\r\n"
"<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n"
"<NewRemoteHost>"
+ external_ip +
"</NewRemoteHost>\r\n"
"<NewExternalPort>"
+ external_port +
"</NewExternalPort>\r\n"
"<NewProtocol>"
+ protocol +
"</NewProtocol>\r\n"
"<NewInternalPort>"
+ internal_port +
"</NewInternalPort>\r\n"
"<NewInternalClient>"
+ internal_ip +
"</NewInternalClient>\r\n"
"<NewEnabled>"
"1"
"</NewEnabled>\r\n"
"<NewPortMappingDescription>"
+ port_forwading_description +
"</NewPortMappingDescription>\r\n"
"<NewLeaseDuration>"
"0"
"</NewLeaseDuration>\r\n"
"</m:AddPortMapping>\r\n"
"</SOAP-ENV:Body>\r\n"
"</SOAP-ENV:Envelope>\r\n\r\n");
std::string request_header("POST /UD/?3 HTTP/1.1\r\n"
"Content-Type: text/xml; charset=\"utf-8\"\r\n"
"SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping\"\r\n"
"Host: " + location + "\r\n"
"Content-Length: " + std::to_string(add_forwading_request.length()) + "\r\n"
"Connection: Close\r\n"
"Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\n\r\n");
request_header.append(add_forwading_request);
if (SendReqToRout(sock_ptr, request_header, &responce) != OK)
{
if (responce.find("HTTP/1.1 500 Internal Server Error") != -1)
{
int Len_pos = responce.find("Content-Length:");
Len_pos += 16;
int end_line = responce.find("\r\n", Len_pos);
int Len_len = end_line - Len_pos;
std::string Length = responce.substr(Len_pos, Len_len);
std::stringstream ss;
ss << Length;
int length;
ss >> length;
char* error_responce = new char[length + 1];
char c[1];
int j = 0;
while (read(*sock_ptr, buffer(c)) > 0)
{
error_responce[j] = c[0];
j++;
if (j == length)
break;
}
error_responce[length] = '\0';
}
sock_ptr->close();
return FAIL;
}
sock_ptr->close();
mapping_desc m_desc;
m_desc.external_ip = external_ip;
m_desc.external_port = external_port;
m_desc.protocol = protocol;
m_desc.internal_port = internal_port;
m_desc.internal_ip = internal_ip;
m_desc.port_forwading_description = port_forwading_description;
my_mapping_list.push_back(m_desc);
mapping_list.push_back(m_desc);
return OK;
}
int GetPortMappingEntry(const std::string location, const std::string external_ip, const std::string external_port, const std::string protocol)
{
std::string responce;
ip::tcp::endpoint ep(rout_addr, 80);
socket_ptr sock_ptr(new ip::tcp::socket(service));
sock_ptr->connect(ep);
std::string get_forwading_request("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"
"<SOAP-ENV:Body>\r\n"
"<m:GetSpecificPortMappingEntry xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n"
"<NewRemoteHost>" + external_ip + "</NewRemoteHost>\r\n"
"<NewExternalPort>" + external_port + "</NewExternalPort>\r\n"
"<NewProtocol>" + protocol + "</NewProtocol>\r\n"
"</m:GetSpecificPortMappingEntry>\r\n"
"</SOAP-ENV:Body>\r\n"
"</SOAP-ENV:Envelope>\r\n\r\n");
std::string ger_forwading_request_header("POST /UD/?3 HTTP/1.1\r\n"
"Content-Type: text/xml; charset=\"utf-8\"\r\n"
"SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#GetSpecificPortMappingEntry\"\r\n"
"User-Agent: Mozilla/4.0 (compatible; UPnP/1.0; Windows 9x)\r\n"
"Host: " + location + "\r\n"
"Content-Length: " + std::to_string(get_forwading_request.length()) + "\r\n"
"Connection: Close\r\n"
"Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\n\r\n");
ger_forwading_request_header.append(get_forwading_request);
if (SendReqToRout(sock_ptr, ger_forwading_request_header, &responce) != OK)
{
if (responce.find("HTTP/1.1 500 Internal Server Error") != -1)
{
int Len_pos = responce.find("Content-Length:");
Len_pos += 16;
int end_line = responce.find("\r\n", Len_pos);
int Len_len = end_line - Len_pos;
std::string Length = responce.substr(Len_pos, Len_len);
std::stringstream ss;
ss << Length;
int length;
ss >> length;
char* error_responce = new char[length + 1];
char c[1];
int j = 0;
while (read(*sock_ptr, buffer(c)) > 0)
{
error_responce[j] = c[0];
j++;
if (j == length)
break;
}
error_responce[length] = '\0';
}
sock_ptr->close();
return FAIL;
}
sock_ptr->close();
return OK;
}
int GetGenericPortMappingEntry(const std::string location, const int port_mapping_index)
{
std::string responce;
ip::tcp::endpoint ep(rout_addr, 80);
socket_ptr sock_ptr(new ip::tcp::socket(service));
sock_ptr->connect(ep);
std::string get_forwading_request("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"
"<SOAP-ENV:Body>\r\n"
"<m:GetGenericPortMappingEntry xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n"
"<NewPortMappingIndex>" + std::to_string(port_mapping_index) + "</NewPortMappingIndex>\r\n"
"</m:GetGenericPortMappingEntry>\r\n"
"</SOAP-ENV:Body>\r\n"
"</SOAP-ENV:Envelope>\r\n\r\n");
std::string ger_forwading_request_header("POST /UD/?3 HTTP/1.1\r\n"
"Content-Type: text/xml; charset=\"utf-8\"\r\n"
"SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#GetGenericPortMappingEntry\"\r\n"
"User-Agent: Mozilla/4.0 (compatible; UPnP/1.0; Windows 9x)\r\n"
"Host: " + location + "\r\n"
"Content-Length: " + std::to_string(get_forwading_request.length()) + "\r\n"
"Connection: Close\r\n"
"Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\n\r\n");
ger_forwading_request_header.append(get_forwading_request);
if (SendReqToRout(sock_ptr, ger_forwading_request_header, &responce) != OK)
{
if (responce.find("HTTP/1.1 500 Internal Server Error") != -1)
{
int Len_pos = responce.find("Content-Length:");
Len_pos += 16;
int end_line = responce.find("\r\n", Len_pos);
int Len_len = end_line - Len_pos;
std::string Length = responce.substr(Len_pos, Len_len);
std::stringstream ss;
ss << Length;
int length;
ss >> length;
char* error_responce = new char[length + 1];
char c[1];
int j = 0;
while (read(*sock_ptr, buffer(c)) > 0)
{
error_responce[j] = c[0];
j++;
if (j == length)
break;
}
error_responce[length] = '\0';
}
sock_ptr->close();
return FAIL;
}
mapping_desc m_desc;
boost::regex xRegEx("\\s*<NewRemoteHost>(.*)</NewRemoteHost>"
"\\s*<NewExternalPort>(.*)</NewExternalPort>"
"\\s*<NewProtocol>(.*)</NewProtocol>"
"\\s*<NewInternalPort>(.*)</NewInternalPort>"
"\\s*<NewInternalClient>(.*)</NewInternalClient>"
"\\s*<NewEnabled>1</NewEnabled>"
"\\s*<NewPortMappingDescription>(.*)</NewPortMappingDescription>");
boost::smatch xResults;
boost::regex_search(responce, xResults, xRegEx);
m_desc.external_ip = xResults[1];
m_desc.external_port = xResults[2];
m_desc.protocol = xResults[3];
m_desc.internal_port = xResults[4];
m_desc.internal_ip = xResults[5];
m_desc.port_forwading_description = xResults[6];
mapping_list.push_back(m_desc);
sock_ptr->close();
return OK;
}
int DeletePortMapping(const std::string location, const std::string external_ip, const std::string external_port, const std::string protocol)
{
std::string responce;
ip::tcp::endpoint ep(rout_addr, 80);
socket_ptr sock_ptr(new ip::tcp::socket(service));
sock_ptr->connect(ep);
std::string delete_forwading_request("<?xml version=\"1.0\"?>\r\n"
"<SOAP-ENV:Envelope\r\n xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"
"<SOAP-ENV:Body>\r\n"
"<m:DeletePortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n"
"<NewRemoteHost>"
+ external_ip +
"</NewRemoteHost>\r\n"
"<NewExternalPort>"
+ external_port +
"</NewExternalPort>\r\n"
"<NewProtocol>"
+ protocol +
"</NewProtocol>\r\n"
"</m:DeletePortMapping>\r\n"
"</SOAP-ENV:Body>\r\n"
"</SOAP-ENV:Envelope>\r\n\r\n");
std::string delete_forwding_request_header("POST /UD/?3 HTTP/1.1\r\n"
"Content-Type: text/xml; charset=\"utf-8\"\r\n"
"SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#DeletePortMapping\"\r\n"
"User-Agent: Mozilla/4.0 (compatible; UPnP/1.0; Windows 9x)\r\n"
"Host: " + location + "\r\n"
"Content-Length: " + std::to_string(delete_forwading_request.length()) + "\r\n"
"Connection: Keep-Alive\r\n"
"Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\n\r\n");
delete_forwding_request_header.append(delete_forwading_request);
if (SendReqToRout(sock_ptr, delete_forwding_request_header, &responce) != OK)
{
if (responce.find("HTTP/1.1 500 Internal Server Error") != -1)
{
int Len_pos = responce.find("Content-Length:");
Len_pos += 16;
int end_line = responce.find("\r\n", Len_pos);
int Len_len = end_line - Len_pos;
std::string Length = responce.substr(Len_pos, Len_len);
std::stringstream ss;
ss << Length;
int length;
ss >> length;
char* error_responce = new char[length + 1];
char c[1];
int j = 0;
while (read(*sock_ptr, buffer(c)) > 0)
{
error_responce[j] = c[0];
j++;
if (j == length)
break;
}
error_responce[length] = '\0';
}
sock_ptr->close();
return FAIL;
}
sock_ptr->close();
mapping_desc m_desc;
m_desc.external_ip = external_ip;
m_desc.external_port = external_port;
m_desc.protocol = protocol;
my_mapping_list.remove(m_desc);
mapping_list.remove(m_desc);
return OK;
}
void SeeAllPortMappings()
{
for (std::list<mapping_desc>::iterator c_it = mapping_list.begin(); c_it != mapping_list.end(); c_it++)
{
std::cout << "Port mapping: " << c_it.operator*().port_forwading_description << std::endl;
std::cout << "External port: " << c_it.operator*().external_port << std::endl;
std::cout << "Protocol: " << c_it.operator*().protocol << std::endl;
std::cout << "Internal port: " << c_it.operator*().internal_port << std::endl;
std::cout << "Internal ip: " << c_it.operator*().internal_ip << std::endl;
std::cout << std::endl;
}
}
void SeeMyPortMapping()
{
for (std::list<mapping_desc>::iterator c_it = my_mapping_list.begin(); c_it != my_mapping_list.end(); c_it++)
{
std::cout << "Port mapping: " << c_it.operator*().port_forwading_description << std::endl;
std::cout << "External port: " << c_it.operator*().external_port << std::endl;
std::cout << "Protocol: " << c_it.operator*().protocol << std::endl;
std::cout << "Internal port: " << c_it.operator*().internal_port << std::endl;
std::cout << "Internal ip: " << c_it.operator*().internal_ip << std::endl;
std::cout << std::endl;
}
}
}; | [
"AntonKopilec@gmail.com"
] | AntonKopilec@gmail.com |
cbae13025dd7e158fb5383ecfc921577ebbe8b35 | 8739b721db20897c3729d3aa639f5d08e19b6a30 | /Leetcode-cpp-solution/92.cpp | f19bb190802f5b3adf7d3a731325b98aa7e5899b | [] | no_license | Leetcode-W010/Answers | 817414ca101f2d17050ebc471153fbed81f67cd0 | b4fff77ff3093fab76534d96b40e6bf98bef42c5 | refs/heads/master | 2021-01-19T22:13:49.134513 | 2015-12-13T01:30:36 | 2015-12-13T01:30:36 | 40,616,166 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,282 | cpp | /*
Reverse Linked List IIJun 27 '125508 / 18773
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode newh(0);
newh.next = head;
ListNode *pre = &newh, *preM, *cur=head;
for(int i=1; i<=n; ++i) {
if(i==m) preM = pre;
if(i>m) {
ListNode *tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
else {
pre = cur;
cur = cur->next;
}
}
preM->next->next = cur;
preM->next = pre;
return newh.next;
}
}; | [
"vincent.zhang.us@gmail.com"
] | vincent.zhang.us@gmail.com |
76e8707d8edd5f1a4232725f50c5e8bad95a81dc | 932ccd8e20edc9ca103af953919e6f2932fcf92d | /MegaTutorial C++/POZIOM 1 - Od Zera Do Gier Kodera (C++ w konsoli)/Megatutorial - przykłady/Rozdział 1.3/SimpleIf/main.cpp | a1b1e3cb3d51bc53585ca4a3075d0b016e54a757 | [] | no_license | patriquus/PROGRAMOWANIE-TOTAL | 99c412211b2888e93ba391d03b609bcc4d000448 | 914fd85bc3821941dd2dcb30ab352a39a1fea54e | refs/heads/master | 2020-06-03T19:39:00.356027 | 2014-11-30T20:56:16 | 2014-11-30T20:56:16 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 322 | cpp | // SimpleIf - prosty przykład instrukcji if
#include <iostream>
#include <conio.h>
void main()
{
int nLiczba;
std::cout << "Wprowadz liczbe wieksza od 10: ";
std::cin >> nLiczba;
if (nLiczba > 10)
{
std::cout << "Dziekuje." << std::endl;
std::cout << "Wcisnij dowolny klawisz, by zakonczyc.";
getch();
}
} | [
"patriquus@gmail.com"
] | patriquus@gmail.com |
5ebdcb62daea6513383fac69f445fcb39d7d946e | c31ad9981bb2760c6f389e9a6cf8a6893e9423e8 | /inexlib/ourex/HEPVis/include/HEPVis/nodes/SoTubs.h | a0f41ae775068370f5b6793ceb7bca528d8b6792 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | gbarrand/osc_vis_for_LHCb | 0582d7ed6734d9716619eb0fccc69904381529d8 | 2ba864c4475f988192c9799f5be85f1abf88c364 | refs/heads/master | 2021-10-25T21:32:51.600843 | 2021-10-17T07:45:20 | 2021-10-17T07:45:20 | 140,073,663 | 0 | 2 | null | 2021-10-17T07:45:20 | 2018-07-07T10:11:36 | C++ | UTF-8 | C++ | false | false | 3,726 | h | /*-----------------------------HEPVis----------------------------------------*/
/* */
/* Node: SoTubs */
/* Description: Represents the G4Tubs Geant Geometry entity */
/* Author: Joe Boudreau Nov 11 1996 */
/* */
/*---------------------------------------------------------------------------*/
#ifndef HEPVis_SoTubs_h
#define HEPVis_SoTubs_h
#include <Inventor/fields/SoSFFloat.h>
#include <Inventor/fields/SoSFNode.h>
#include <Inventor/fields/SoSFBool.h>
#include <Inventor/nodes/SoShape.h>
class SoSFNode;
//! SoTubs - Inventor version of the G4Tubs Geant Geometry entity
/*!
* Node: SoTubs
*
* Description: The Inventor version of the G4Tubs Geant Geometry entity
*
* Author: Joe Boudreau Nov 11 1996
*
* The documentation from Geant says:
*
* class G4Tubs
*
* A tube or tube segment with curved sides parallel to
* the z-axis. The tube has a specified half-length along
* the z axis, about which it is centred, and a given
* minimum and maximum radius. A minimum radius of 0
* signifies a filled tube /cylinder. The tube segment is
* specified by starting and delta
* angles for phi, with 0 being the +x axis, PI/2
* the +y axis. A delta angle of 2PI signifies a
* complete, unsegmented tube/cylinder
*
* Always use Inventor Fields. This allows Inventor to detect a change to
* the data field and take the appropriate action; e.g., redraw the scene.
*/
class SoTubs:public SoShape {
// The following is required:
SO_NODE_HEADER(SoTubs);
public:
//
//! Inside radius of the tube
//
SoSFFloat pRMin;
//
//! Outside radius of the tube
//
SoSFFloat pRMax;
//
//! Half-length in Z
//
SoSFFloat pDz;
//
//! Starting angle, in radians
//
SoSFFloat pSPhi;
//
//! Delta-angle, in radians
//
SoSFFloat pDPhi;
//
//! Alternate rep - required
//
SoSFNode alternateRep;
//
//! Constructor, required
//
SoTubs();
//
//! Class Initializer, required
//
static void initClass();
//
//! Generate AlternateRep, required. Generating an alternate representation
//! must be done upon users request. It allows an Inventor program to read
//! back the file without requiring *this* code to be dynamically linked.
//! If the users expects that *this* code will be dynamically linked, he
//! need not invoke this method.
//
virtual void generateAlternateRep(SoAction*);
//
//! We better be able to clear it, too!
//
virtual void clearAlternateRep();
protected:
//
//! compute bounding Box, required
//
virtual void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er );
//
//! Generate Primitives, required
//
virtual void generatePrimitives(SoAction *action);
//
//! GetChildList, required whenever the class has hidden children
//
virtual SoChildList *getChildren() const;
virtual void doAction(SoAction*);
virtual void write(SoWriteAction*);
protected:
//
//! Destructor, required
//
virtual ~SoTubs();
private:
//
//! Generate Children. Used to create the hidden children. Required whenever
//! the node has hidden children.
//
void generateChildren();
//
//! Used to modify hidden children when a data field is changed. Required
//! whenever the class has hidden children.
//
void updateChildren();
//
//! ChildList. Required whenever the class has hidden children.
//
SoChildList *children;
};
#endif
| [
"guy.barrand@gmail.com"
] | guy.barrand@gmail.com |
974c083fb369d4411520da0b506394158e8ea730 | 06af2b92b1e54c77585ef242bfc0659344543b74 | /GameOfLife/stdafx.h | 18001e123c50b02b8fd188526462393fd5713336 | [] | no_license | hanneshoettinger/GameOfLife-Sequential-OpenMP-OpenCL | 765ce7a414cf39320bbcbfe4d7d195ec9b4f19c1 | 56fa3180e40c12eac4e223f854cd166d7fb4724f | refs/heads/master | 2021-01-21T18:33:15.512598 | 2017-05-22T13:51:32 | 2017-05-22T13:51:32 | 92,052,922 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <windows.h>
// inlucde OpenMP
#include <omp.h>
// include OpenCL and also use deprecated functions as we target also OpenCL 1.2
//#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#include <CL\cl.h>
#include <CL\opencl.h>
// TODO: reference additional headers your program requires here
| [
"hannes.hoettinger@gmail.com"
] | hannes.hoettinger@gmail.com |
b58bd5dc03823a143e117df3111ae0f9bda62508 | 5a7d3db1f4dc544d47430dcecf9de5ae2990fe88 | /.emacs.d/undohist/!home!sirogami!Programming!compe!AtCoder!other!DISCO!b.cc | 1dd5f85ba31149e77349b474a6615b1b367ac644 | [] | no_license | sirogamichandayo/emacs_sirogami | d990da25e5b83b23799070b4d1b5c540b12023b9 | c646cfd1c4a69cef2762432ba4492e32c2c025c8 | refs/heads/master | 2023-01-24T12:38:56.308764 | 2020-12-07T10:42:35 | 2020-12-07T10:42:35 | 245,687,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,563 | cc |
((digest . "7abf269d83dea0a30850a3325621bdce") (undo-list nil (1551 . 1553) (1550 . 1553) nil (1548 . 1549) (" " . 1548) (1550 . 1552) ("{" . -1550) (1550 . 1551) nil (1547 . 1550) nil (" " . -1546) ((marker . 1553) . -1) ((marker . 1546) . -1) ((marker . 1546) . -1) 1547 nil (1543 . 1547) nil (1542 . 1544) ("(" . -1542) (1542 . 1543) nil (1541 . 1542) (" x" . -1541) (1541 . 1543) ("while" . 1541) ((marker . 1553) . -5) (1536 . 1541) 1541 nil (1536 . 1541) nil (1534 . 1536) nil ("
" . 1503) ((marker) . -1) ((marker) . -1) ((marker) . -1) nil ("
" . 1503) ((marker) . -1) ((marker) . -1) ((marker) . -1) (" " . -1503) ((marker . 1553) . -1) ((marker . 1503) . -1) ((marker . 1503) . -1) ((marker) . -1) 1504 nil (1502 . 1504) (" " . 1502) ((marker . 1553) . -1) 1503 nil (1501 . 1503) (t 24440 16861 911442 652000) nil (1426 . 1434) nil ("set" . -1426) ((marker . 1553) . -3) 1429 (t 24440 16803 715659 351000) nil (1529 . 1531) nil (1528 . 1529) nil (1525 . 1526) nil (")" . -1525) (1525 . 1526) (")" . -1525) (1525 . 1526) (1524 . 1526) ("(" . -1524) (1524 . 1525) nil (1521 . 1524) nil (1520 . 1522) ("(" . -1520) (1520 . 1521) nil (1509 . 1520) nil (1508 . 1509) nil ("max" . -1508) ((marker . 1553) . -3) 1511 nil (1499 . 1511) (t 24440 16784 947728 614000) nil (1497 . 1499) (" " . 1497) ((marker . 1553) . -1) 1498 nil (1496 . 1498) nil (" {
" . 1473) nil ("
" . 1500) ((marker*) . 1) (" }" . -1500) ((marker . 1553) . -2) ((marker*) . 1) ((marker) . -2) 1502 nil (1498 . 1499) nil (1495 . 1496) (1494 . 1496) ("[" . -1494) (1493 . 1495) nil (1492 . 1494) ("(" . -1492) (1492 . 1493) nil (1485 . 1492) nil (1482 . 1483) (1481 . 1483) ("[" . -1481) (1480 . 1482) nil ("t" . -1480) ((marker . 1553) . -1) 1481 nil (1480 . 1481) (1479 . 1481) ("[" . -1479) (1478 . 1480) nil (1476 . 1478) (1475 . 1478) nil (1473 . 1474) (" " . 1473) (1475 . 1477) ("{" . -1475) (1475 . 1476) nil (1472 . 1475) nil (1469 . 1471) nil (1468 . 1469) nil (1467 . 1468) nil (")" . -1467) (1467 . 1468) (")" . -1467) (1467 . 1468) (1466 . 1468) ("(" . -1466) (1466 . 1467) nil (1463 . 1466) (t 24440 16765 487800 83000) nil (1461 . 1463) nil (1460 . 1461) nil ("," . -1459) ((marker . 1553) . -1) ((marker . 1464) . -1) ((marker . 1464) . -1) (" " . -1460) ((marker . 1553) . -1) ((marker . 1464) . -1) ((marker . 1464) . -1) ("0" . -1461) ((marker . 1553) . -1) ((marker . 1464) . -1) ((marker . 1464) . -1) 1462 nil (1460 . 1462) nil (1459 . 1460) nil (1453 . 1459) nil (1450 . 1453) nil (1449 . 1451) ("(" . -1449) (1449 . 1450) nil (1448 . 1449) nil ("S" . -1448) ((marker . 1553) . -1) ((marker . 1453) . -1) ((marker . 1453) . -1) 1449 nil (1448 . 1449) nil (1447 . 1448) nil (1444 . 1445) nil (1442 . 1444) nil (1441 . 1442) nil (1433 . 1441) nil (" " . -1432) ((marker . 1553) . -1) ((marker . 1437) . -1) ((marker . 1437) . -1) 1433 nil (" " . -1434) ((marker . 1553) . -1) 1435 nil (1434 . 1435) nil (1433 . 1434) nil (1430 . 1433) nil (1429 . 1432) nil (1426 . 1429) nil (1425 . 1426) nil (1419 . 1425) (t 24440 16670 160144 643000) nil (1417 . 1419) (" " . 1417) ((marker . 1553) . -1) 1418 (t 24440 15383 90048 669000) nil (1411 . 1412) nil ("T" . -1411) ((marker . 1553) . -1) 1412 nil (1392 . 1417) 1367 nil (")
" . 1392) (" REP(i" . -1392) ((marker . 1553) . -6) 1398 nil (1397 . 1398) nil (")" . -1397) (1397 . 1398) (")" . -1397) (1397 . 1398) (1396 . 1398) ("(" . -1396) (1396 . 1397) nil (1393 . 1396) nil (1391 . 1393) nil (1361 . 1362) nil ("T" . -1361) ((marker . 1553) . -1) 1362 nil (1390 . 1391) nil (1388 . 1389) (1387 . 1389) ("[" . -1387) (1385 . 1388) nil (1383 . 1385) nil (1378 . 1383) nil (1375 . 1376) nil ("n" . -1375) ((marker . 1553) . -1) 1376 nil ("c" . -1378) ((marker . 1553) . -1) 1379 nil (1377 . 1379) nil (1375 . 1376) nil (1374 . 1375) nil (1373 . 1374) nil (1372 . 1373) nil (")" . -1372) (1372 . 1373) (")" . -1372) (1372 . 1373) (1371 . 1373) ("(" . -1371) (1371 . 1372) nil (1368 . 1371) nil (1366 . 1368) (" " . 1366) ((marker . 1553) . -1) 1367 nil (1366 . 1367) nil (1365 . 1366) nil (1363 . 1364) nil (1362 . 1364) ("(" . -1362) (1362 . 1363) nil (1360 . 1362) nil (1359 . 1360) nil (1357 . 1358) nil (1356 . 1358) ("(" . -1356) (1356 . 1357) nil (1355 . 1356) nil (1354 . 1355) nil (1353 . 1354) nil (1351 . 1353) nil (1350 . 1351) nil (1344 . 1350) nil (1342 . 1344) nil (1341 . 1342) nil (1339 . 1341) nil (1337 . 1339) nil (1334 . 1337) nil (1332 . 1334) nil (1327 . 1332) nil (1326 . 1327) nil (1324 . 1326) nil (1323 . 1324) nil (1319 . 1323) nil (1318 . 1319) (t 24440 15313 561792 238000) nil undo-tree-canary))
| [
"ssirogamicota@gmail.com"
] | ssirogamicota@gmail.com |
74a93bcdf970b43daff436863d6ef9e6399fe124 | e654c3ad6c7dff30e97b0339e5b0713ecf086749 | /Runtime/RHI/RHI_PipelineCache.cpp | ce589375e6cd2ed6bf63159334ac5750d402e11a | [
"MIT"
] | permissive | gmCAD/SpartanEngine | 12332f17c957dec39144abc77050bacf659907c8 | dc9c4ff73810c607b99a05160a227585a17b9c60 | refs/heads/master | 2020-12-21T10:14:05.369630 | 2020-01-26T23:33:35 | 2020-01-26T23:33:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,005 | cpp | /*
Copyright(c) 2016-2020 Panos Karabelas
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.
*/
//= INCLUDES =================
#include "RHI_PipelineCache.h"
#include "RHI_Texture.h"
#include "RHI_Pipeline.h"
#include "RHI_SwapChain.h"
#include "RHI_DescriptorSet.h"
//============================
//= NAMESPACES =====
using namespace std;
//==================
namespace Spartan
{
RHI_Pipeline* RHI_PipelineCache::GetPipeline(RHI_PipelineState& pipeline_state, RHI_CommandList* cmd_list)
{
// Validate it
if (!pipeline_state.IsValid())
{
LOG_ERROR("Invalid pipeline state");
return nullptr;
}
// Render target layout transitions
{
// Color
for (auto i = 0; i < state_max_render_target_count; i++)
{
if (RHI_Texture* texture = pipeline_state.render_target_color_textures[i])
{
texture->SetLayout(RHI_Image_Shader_Read_Only_Optimal, cmd_list);
}
}
// Depth
if (RHI_Texture* texture = pipeline_state.render_target_depth_texture)
{
texture->SetLayout(RHI_Image_Depth_Stencil_Attachment_Optimal, cmd_list);
}
// Swapchain
if (RHI_SwapChain* swapchain = pipeline_state.render_target_swapchain)
{
swapchain->SetLayout(RHI_Image_Present_Src, cmd_list);
}
}
// Compute a hash for it
pipeline_state.ComputeHash();
size_t hash = pipeline_state.GetHash();
// If no pipeline exists for this state, create one
if (m_cache.find(hash) == m_cache.end())
{
// Cache a new pipeline
m_cache.emplace(make_pair(hash, move(make_shared<RHI_Pipeline>(m_rhi_device, pipeline_state))));
}
RHI_Pipeline* pipeline = m_cache[hash].get();
pipeline->GetDescriptorSet()->MakeDirty();
return pipeline;
}
}
| [
"PanosConroe@hotmail.com"
] | PanosConroe@hotmail.com |
40ccc9c863cb78791165254e0525333fb009137d | ce7cd2b2f9709dbadf613583d9816c862003b38b | /SRC/engine/cskeletongroups.swg | 3cc31ab446819ce05078b7dc65cdaf2fc553cdec | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | usnistgov/OOF3D | 32b01a25154443d29d0c44d5892387e8ef6146fa | 7614f8ea98a095e78c62c59e8952c0eb494aacfc | refs/heads/master | 2023-05-25T13:01:20.604025 | 2022-02-18T20:24:54 | 2022-02-18T20:24:54 | 29,606,158 | 34 | 7 | null | 2015-02-06T19:56:26 | 2015-01-21T19:04:14 | Python | UTF-8 | C++ | false | false | 1,363 | swg | // -*- C++ -*-
/* This software was produced by NIST, an agency of the U.S. government,
* and by statute is not subject to copyright in the United States.
* Recipients of this software assume all responsibilities associated
* with its operation, modification and maintenance. However, to
* facilitate maintenance we ask that before distributing modified
* versions of this software, you first contact the authors at
* oof_manager@nist.gov.
*/
#ifndef CSKELETONGROUPS_SWG
#define CSKELETONGROUPS_SWG
%module cskeletongroups
%include "engine/typemaps.swg"
%{
#include <oofconfig.h>
#include "common/tostring.h"
#include "engine/cskeletongroups.h"
%}
%pragma(python) include="engine/cskeletongroups.spy"
class CGroupTrackerBase {
public:
CSkeletonSelectableSet* get_group(char*);
};
class CGroupTracker : public CGroupTrackerBase {
public:
CGroupTracker() {};
void add_group(char*);
void clear_group(char*);
void remove_group(char*);
void rename_group(char*, char*);
void add(char*, CSkeletonSelectable*);
void remove(char*, CSkeletonSelectable*);
int get_group_size(char*);
CGroupTracker* sheriff();
%addmethods {
%new string *__repr__() {
return new std::string(to_string(*self));
}
}
};
class CDeputyGroupTracker : public CGroupTrackerBase {
public:
CDeputyGroupTracker(CGroupTrackerBase*);
};
#endif
| [
"faical.congo@nist.gov"
] | faical.congo@nist.gov |
fb516631c1859da80a2f8aab4999fe1cc14475c3 | 1498831e001f6e6f630a2425c49dea12f51d6031 | /utFS.cpp | e5ab034a3cf04367b6b940b03ce3ba17f8042c54 | [] | no_license | yccheng66/itri-dp | d159bb6ee4c6565ce56551346411c7ebf0c72e9c | 4a1ec1ad0c843491cdbb4ed3d03afdf7f80ec8f6 | refs/heads/master | 2021-08-19T11:51:11.571761 | 2017-11-26T03:38:32 | 2017-11-26T03:38:32 | 110,942,555 | 3 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 161 | cpp | #include <gtest/gtest.h>
#include "utFS.h"
int main( int argc , char **argv )
{
testing :: InitGoogleTest( &argc , argv ) ;
return RUN_ALL_TESTS( ) ;
}
| [
"yccheng@csie.ntut.edu.tw"
] | yccheng@csie.ntut.edu.tw |
910d995a5ed3b99bfcc02cab67a3e21b7cfb459b | 6e27d62bedab14279c97347b02b34138a789d62b | /serial_arduino.cpp | 4dcfc0c52b9c2c3837cae8ec9df5eefd68122347 | [] | no_license | alivanz/micro-wallet | 6d96c39fd4ba742a62c8b3bc723bcd80aea7ac37 | 63579a668fe30083922bc4e5b7d61176df3537e4 | refs/heads/master | 2020-04-01T17:52:24.031475 | 2018-10-18T11:27:48 | 2018-10-18T11:27:48 | 153,455,809 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | cpp | #include <Arduino.h>
#include <string>
#include <map>
#include "serial.hpp"
using namespace std;
Protocol::Protocol(void){
Serial.begin(115200);
Serial.setTimeout(-1);
}
string Protocol::GetLine(void){
String line = Serial.readStringUntil('\n');
line.trim();
unsigned char s[1024];
line.getBytes(s,sizeof(s));
return string((const char*)s, line.length());
}
void Protocol::WriteLine(string line){
Serial.printf("%*s\n", line.length(), line.c_str());
}
static String sconv(string s){
return String(s.c_str());
}
std::map<string,string> Protocol::GetData(void){
std::map<string,string> out;
for(string line;; ){
line=GetLine();
if(line.length()==0){
break;
}
size_t pos = line.find(" ");
if(pos == string::npos){
throw "invalid format";
}
out[line.substr(0,pos)] = line.substr(pos+1, string::npos);
}
return out;
}
void Protocol::WriteData(std::map<string,string> data){
for(auto it=data.cbegin(); it!=data.cend(); it++){
Serial.printf(">>>");
Serial.print(sconv(it->first));
Serial.printf(" ");
Serial.print(sconv(it->second));
Serial.println();
}
Serial.println();
}
bool Protocol::available(void){
return Serial.available();
}
| [
"alivan1627@gmail.com"
] | alivan1627@gmail.com |
da58a643a38cbe16aa7c4accb08eb24d4c86df51 | 3a99384b2e825a7a86d9d4202f8c50c3ad245dc0 | /ZekeEngine2/HID/Mouse.h | 3c3de0fbaa1c674761b811a0c903cdd425626db9 | [] | no_license | ZekeZR1/ZekeEngine2 | 54ebf02839443f64975938c835fc83d412d2c23a | 97ddaeab96cdbc77c4e74855d237d6b2d9adef25 | refs/heads/master | 2020-05-07T17:12:30.149371 | 2019-11-29T03:47:40 | 2019-11-29T03:47:40 | 180,693,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | h | #pragma once
enum enMouseEve {
enLeftClick,
enMiddleClick,
enRightClick,
enNotchUp,
enNotchDown,
enNumMouseEve
};
namespace Mouse {
int GetMouseNotch();
void UpdateMouseInput();
bool IsTrigger(enMouseEve);
bool IsPress(enMouseEve);
CVector3 GetCursorPos();
}
| [
"hnta3574@gmail.com"
] | hnta3574@gmail.com |
28ff7cfef7def4c7b219453e13be45da99896493 | df01676aff883cadebdf4e6cbc9b42aa7845ed52 | /service/can_dbcparser/message.cpp | f88586c1faaa973713e99e6d92cb6fbca9b7c420 | [
"MIT"
] | permissive | airpod2/diva2 | 5327e757c87bdcf6cb89e40d1217e0c3c291a904 | 7cac21bff3f571bd11adee10f2e1de6ae2f897e9 | refs/heads/main | 2023-05-31T06:02:54.695276 | 2021-07-06T08:06:44 | 2021-07-06T08:06:44 | 352,242,957 | 0 | 0 | null | 2021-03-28T04:46:50 | 2021-03-28T04:46:50 | null | UTF-8 | C++ | false | false | 1,167 | cpp | /*
* message.cpp
*
* Created on: 04.10.2013
* Author: downtimes
*/
#include "header/message.hpp"
#include <istream>
#include <limits>
#include <algorithm>
std::istream& operator>>(std::istream& in, Message& msg) {
std::string preamble;
in >> preamble;
//Check if we are actually reading a Message otherwise fail the stream
if (preamble != "BO_") {
in.setstate(std::ios_base::failbit);
return in;
}
//Parse the message ID
in >> msg.id;
//Parse the name of the Message
std::string name;
in >> name;
msg.name = name.substr(0, name.length() - 1);
//Parse the Messages length
in >> msg.dlc;
//Parse the sender;
in >> msg.from;
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
//As long as there is a Signal, parse the Signal
while(in) {
Signal sig;
in >> sig;
if (in) {
msg.signals.push_back(sig);
}
}
in.clear();
return in;
}
std::set<std::string> Message::getTo() const {
std::set<std::string> collection;
for (auto sig : signals) {
auto toList = sig.getTo();
collection.insert(toList.begin(), toList.end());
}
return collection;
}
| [
"dasol@LAPTOP-U9IG4JC9.localdomain"
] | dasol@LAPTOP-U9IG4JC9.localdomain |
e16a2e3222f7fd9994a203c44fe05ad1c1c9d936 | 260e5dec446d12a7dd3f32e331c1fde8157e5cea | /Indi/SDK/Indi_SC_LightMachineGun_Weapon_T3_structs.hpp | 35e6bf9165c555d78c15c6eae67aa7b861088801 | [] | no_license | jfmherokiller/TheOuterWorldsSdkDump | 6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0 | 18a8c6b1f5d87bb1ad4334be4a9f22c52897f640 | refs/heads/main | 2023-08-30T09:27:17.723265 | 2021-09-17T00:24:52 | 2021-09-17T00:24:52 | 407,437,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | hpp | #pragma once
// TheOuterWorlds SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "Indi_Basic.hpp"
#include "Indi_SC_LightMachineGun_Weapon_Base_classes.hpp"
namespace SDK
{
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"peterpan0413@live.com"
] | peterpan0413@live.com |
1ef6ca073e11edb55ef912b7aa5e5d0095627141 | 0641d87fac176bab11c613e64050330246569e5c | /tags/release-2-8-update/source/test/intltest/tmsgfmt.cpp | 6d1e40a7094645b454536f326d41c39125f9ea50 | [
"ICU"
] | permissive | svn2github/libicu_full | ecf883cedfe024efa5aeda4c8527f227a9dbf100 | f1246dcb7fec5a23ebd6d36ff3515ff0395aeb29 | refs/heads/master | 2021-01-01T17:00:58.555108 | 2015-01-27T16:59:40 | 2015-01-27T16:59:40 | 9,308,333 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 36,482 | cpp | /********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2003, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
/*
* File TMSGFMT.CPP
*
* Modification History:
*
* Date Name Description
* 03/24/97 helena Converted from Java.
* 07/11/97 helena Updated to work on AIX.
* 08/04/97 jfitz Updated to intltest
********************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "tmsgfmt.h"
#include "unicode/format.h"
#include "unicode/decimfmt.h"
#include "unicode/locid.h"
#include "unicode/msgfmt.h"
#include "unicode/numfmt.h"
#include "unicode/choicfmt.h"
#include "unicode/gregocal.h"
void
TestMessageFormat::runIndexedTest(int32_t index, UBool exec,
const char* &name, char* /*par*/) {
switch (index) {
TESTCASE(0,testBug1);
TESTCASE(1,testBug2);
TESTCASE(2,sample);
TESTCASE(3,PatternTest);
TESTCASE(4,testStaticFormat);
TESTCASE(5,testSimpleFormat);
TESTCASE(6,testMsgFormatChoice);
TESTCASE(7,testCopyConstructor);
TESTCASE(8,testAssignment);
TESTCASE(9,testClone);
TESTCASE(10,testEquals);
TESTCASE(11,testNotEquals);
TESTCASE(12,testSetLocale);
TESTCASE(13,testFormat);
TESTCASE(14,testParse);
TESTCASE(15,testAdopt);
TESTCASE(16,testCopyConstructor2);
TESTCASE(17,TestUnlimitedArgsAndSubformats);
default: name = ""; break;
}
}
void TestMessageFormat::testBug3()
{
double myNumber = -123456;
DecimalFormat *form = 0;
Locale locale[] = {
Locale("ar", "", ""),
Locale("be", "", ""),
Locale("bg", "", ""),
Locale("ca", "", ""),
Locale("cs", "", ""),
Locale("da", "", ""),
Locale("de", "", ""),
Locale("de", "AT", ""),
Locale("de", "CH", ""),
Locale("el", "", ""), // 10
Locale("en", "CA", ""),
Locale("en", "GB", ""),
Locale("en", "IE", ""),
Locale("en", "US", ""),
Locale("es", "", ""),
Locale("et", "", ""),
Locale("fi", "", ""),
Locale("fr", "", ""),
Locale("fr", "BE", ""),
Locale("fr", "CA", ""), // 20
Locale("fr", "CH", ""),
Locale("he", "", ""),
Locale("hr", "", ""),
Locale("hu", "", ""),
Locale("is", "", ""),
Locale("it", "", ""),
Locale("it", "CH", ""),
Locale("ja", "", ""),
Locale("ko", "", ""),
Locale("lt", "", ""), // 30
Locale("lv", "", ""),
Locale("mk", "", ""),
Locale("nl", "", ""),
Locale("nl", "BE", ""),
Locale("no", "", ""),
Locale("pl", "", ""),
Locale("pt", "", ""),
Locale("ro", "", ""),
Locale("ru", "", ""),
Locale("sh", "", ""), // 40
Locale("sk", "", ""),
Locale("sl", "", ""),
Locale("sq", "", ""),
Locale("sr", "", ""),
Locale("sv", "", ""),
Locale("tr", "", ""),
Locale("uk", "", ""),
Locale("zh", "", ""),
Locale("zh", "TW", "") // 49
};
int32_t i;
for (i= 0; i < 49; i++) {
UnicodeString buffer;
logln(locale[i].getDisplayName(buffer));
UErrorCode success = U_ZERO_ERROR;
// form = (DecimalFormat*)NumberFormat::createCurrencyInstance(locale[i], success);
form = (DecimalFormat*)NumberFormat::createInstance(locale[i], success);
if (U_FAILURE(success)) {
errln("Err: Number Format ");
logln("Number format creation failed.");
continue;
}
Formattable result;
FieldPosition pos(0);
buffer.remove();
form->format(myNumber, buffer, pos);
success = U_ZERO_ERROR;
ParsePosition parsePos;
form->parse(buffer, result, parsePos);
logln(UnicodeString(" -> ") /* + << dec*/ + toString(result) + UnicodeString("[supposed output for result]"));
if (U_FAILURE(success)) {
errln("Err: Number Format parse");
logln("Number format parse failed.");
}
delete form;
}
}
void TestMessageFormat::testBug1()
{
const double limit[] = {0.0, 1.0, 2.0};
const UnicodeString formats[] = {"0.0<=Arg<1.0",
"1.0<=Arg<2.0",
"2.0<-Arg"};
ChoiceFormat *cf = new ChoiceFormat(limit, formats, 3);
FieldPosition status(0);
UnicodeString toAppendTo;
cf->format((int32_t)1, toAppendTo, status);
if (toAppendTo != "1.0<=Arg<2.0") {
errln("ChoiceFormat cmp in testBug1");
}
logln(toAppendTo);
delete cf;
}
void TestMessageFormat::testBug2()
{
UErrorCode status = U_ZERO_ERROR;
UnicodeString result;
// {sfb} use double format in pattern, so result will match (not strictly necessary)
const UnicodeString pattern = "There {0,choice,0.0#are no files|1.0#is one file|1.0<are {0, number} files} on disk {1}. ";
logln("The input pattern : " + pattern);
MessageFormat *fmt = new MessageFormat(pattern, status);
if (U_FAILURE(status)) {
errln("MessageFormat pattern creation failed.");
return;
}
logln("The output pattern is : " + fmt->toPattern(result));
if (pattern != result) {
errln("MessageFormat::toPattern() failed.");
}
delete fmt;
}
#if 0
#if defined(_DEBUG) && U_IOSTREAM_SOURCE!=0
//----------------------------------------------------
// console I/O
//----------------------------------------------------
#if U_IOSTREAM_SOURCE >= 199711
# include <iostream>
std::ostream& operator<<(std::ostream& stream, const Formattable& obj);
#elif U_IOSTREAM_SOURCE >= 198506
# include <iostream.h>
ostream& operator<<(ostream& stream, const Formattable& obj);
#endif
#include "unicode/datefmt.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
IntlTest&
operator<<( IntlTest& stream,
const Formattable& obj)
{
static DateFormat *defDateFormat = 0;
UnicodeString buffer;
switch(obj.getType()) {
case Formattable::kDate :
if (defDateFormat == 0) {
defDateFormat = DateFormat::createInstance();
}
defDateFormat->format(obj.getDate(), buffer);
stream << buffer;
break;
case Formattable::kDouble :
char convert[20];
sprintf( convert, "%lf", obj.getDouble() );
stream << convert << "D";
break;
case Formattable::kLong :
stream << obj.getLong() << "L";
break;
case Formattable::kString:
stream << "\"" << obj.getString(buffer) << "\"";
break;
case Formattable::kArray:
int32_t i, count;
const Formattable* array;
array = obj.getArray(count);
stream << "[";
for (i=0; i<count; ++i) stream << array[i] << ( (i==(count-1)) ? "" : ", " );
stream << "]";
break;
default:
stream << "INVALID_Formattable";
}
return stream;
}
#endif /* defined(_DEBUG) && U_IOSTREAM_SOURCE!=0 */
#endif
void TestMessageFormat::PatternTest()
{
Formattable testArgs[] = {
Formattable(double(1)), Formattable(double(3456)),
Formattable("Disk"), Formattable(UDate((int32_t)1000000000L), Formattable::kIsDate)
};
UnicodeString testCases[] = {
"Quotes '', '{', 'a' {0} '{0}'",
"Quotes '', '{', 'a' {0,number} '{0}'",
"'{'1,number,'#',##} {1,number,'#',##}",
"There are {1} files on {2} at {3}.",
"On {2}, there are {1} files, with {0,number,currency}.",
"'{1,number,percent}', {1,number,percent},",
"'{1,date,full}', {1,date,full},",
"'{3,date,full}', {3,date,full},",
"'{1,number,#,##}' {1,number,#,##}",
};
UnicodeString testResultPatterns[] = {
"Quotes '', '{', a {0} '{'0}",
"Quotes '', '{', a {0,number} '{'0}",
"'{'1,number,#,##} {1,number,'#'#,##}",
"There are {1} files on {2} at {3}.",
"On {2}, there are {1} files, with {0,number,currency}.",
"'{'1,number,percent}, {1,number,percent},",
"'{'1,date,full}, {1,date,full},",
"'{'3,date,full}, {3,date,full},",
"'{'1,number,#,##} {1,number,#,##}"
};
UnicodeString testResultStrings[] = {
"Quotes ', {, a 1 {0}",
"Quotes ', {, a 1 {0}",
"{1,number,#,##} #34,56",
"There are 3,456 files on Disk at 1/12/70 5:46 AM.",
"On Disk, there are 3,456 files, with $1.00.",
"{1,number,percent}, 345,600%,",
"{1,date,full}, Wednesday, December 31, 1969,",
"{3,date,full}, Monday, January 12, 1970,",
"{1,number,#,##} 34,56"
};
for (int32_t i = 0; i < 9; ++i) {
//it_out << "\nPat in: " << testCases[i]);
MessageFormat *form = 0;
UErrorCode success = U_ZERO_ERROR;
UnicodeString buffer;
form = new MessageFormat(testCases[i], Locale::getUS(), success);
if (U_FAILURE(success)) {
errln("MessageFormat creation failed.#1");
logln(((UnicodeString)"MessageFormat for ") + testCases[i] + " creation failed.\n");
continue;
}
if (form->toPattern(buffer) != testResultPatterns[i]) {
errln(UnicodeString("TestMessageFormat::PatternTest failed test #2, i = ") + i);
//form->toPattern(buffer);
errln(((UnicodeString)" Orig: ") + testCases[i]);
errln(((UnicodeString)" Exp: ") + testResultPatterns[i]);
errln(((UnicodeString)" Got: ") + buffer);
}
//it_out << "Pat out: " << form->toPattern(buffer));
UnicodeString result;
int32_t count = 4;
FieldPosition fieldpos(0);
form->format(testArgs, count, result, fieldpos, success);
if (U_FAILURE(success)) {
errln("MessageFormat failed test #3");
logln("TestMessageFormat::PatternTest failed test #3");
continue;
}
if (result != testResultStrings[i]) {
errln("TestMessageFormat::PatternTest failed test #4");
logln("TestMessageFormat::PatternTest failed #4.");
logln(UnicodeString(" Result: ") + result );
logln(UnicodeString(" Expected: ") + testResultStrings[i] );
}
//it_out << "Result: " << result);
#if 0
/* TODO: Look at this test and see if this is still a valid test */
logln("---------------- test parse ----------------");
form->toPattern(buffer);
logln("MSG pattern for parse: " + buffer);
int32_t parseCount = 0;
Formattable* values = form->parse(result, parseCount, success);
if (U_FAILURE(success)) {
errln("MessageFormat failed test #5");
logln(UnicodeString("MessageFormat failed test #5 with error code ")+(int32_t)success);
} else if (parseCount != count) {
errln("MSG count not %d as expected. Got %d", count, parseCount);
}
UBool failed = FALSE;
for (int32_t j = 0; j < parseCount; ++j) {
if (values == 0 || testArgs[j] != values[j]) {
errln(((UnicodeString)"MSG testargs[") + j + "]: " + toString(testArgs[j]));
errln(((UnicodeString)"MSG values[") + j + "] : " + toString(values[j]));
failed = TRUE;
}
}
if (failed)
errln("MessageFormat failed test #6");
#endif
delete form;
}
}
void TestMessageFormat::sample()
{
MessageFormat *form = 0;
UnicodeString buffer1, buffer2;
UErrorCode success = U_ZERO_ERROR;
form = new MessageFormat("There are {0} files on {1}", success);
if (U_FAILURE(success)) {
errln("Err: Message format creation failed");
logln("Sample message format creation failed.");
return;
}
UnicodeString abc("abc");
UnicodeString def("def");
Formattable testArgs1[] = { abc, def };
FieldPosition fieldpos(0);
logln(form->toPattern(buffer1) + "; " + form->format(testArgs1, 2, buffer2, fieldpos, success));
delete form;
}
/* Who knows what kind of static format we are talking about. */
void TestMessageFormat::testStaticFormat(/* char* par */)
{
logln("running TestMessageFormat::testStaticFormat");
UErrorCode err = U_ZERO_ERROR;
GregorianCalendar cal(err);
Formattable arguments[] = {
(int32_t)7,
Formattable(UDate(8.71068e+011), Formattable::kIsDate),
"a disturbance in the Force"
};
UnicodeString result;
result = MessageFormat::format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
arguments,
3,
result,
err);
if (U_FAILURE(err)) {
errln("TestMessageFormat::testStaticFormat #1");
logln(UnicodeString("TestMessageFormat::testStaticFormat failed test #1 with error code ")+(int32_t)err);
return;
}
const UnicodeString expected(
"At 12:20:00 PM on Aug 8, 1997, there was a disturbance in the Force on planet 7.", "");
if (result != expected) {
errln("TestMessageFormat::testStaticFormat failed on test");
logln( UnicodeString(" Result: ") + result );
logln( UnicodeString(" Expected: ") + expected );
}
}
void TestMessageFormat::testSimpleFormat(/* char* par */)
{
logln("running TestMessageFormat::testSimpleFormat");
UErrorCode err = U_ZERO_ERROR;
Formattable testArgs1[] = {(int32_t)0, "MyDisk"};
Formattable testArgs2[] = {(int32_t)1, "MyDisk"};
Formattable testArgs3[] = {(int32_t)12, "MyDisk"};
MessageFormat* form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).", err);
UnicodeString string;
FieldPosition ignore(FieldPosition::DONT_CARE);
form->format(testArgs1, 2, string, ignore, err);
if (U_FAILURE(err) || string != "The disk \"MyDisk\" contains 0 file(s).") {
errln(UnicodeString("TestMessageFormat::testSimpleFormat failed on test #1"));
}
ignore.setField(FieldPosition::DONT_CARE);
string.remove();
form->format(testArgs2, 2, string, ignore, err);
if (U_FAILURE(err) || string != "The disk \"MyDisk\" contains 1 file(s).") {
logln(string);
errln(UnicodeString("TestMessageFormat::testSimpleFormat failed on test #2")+string);
}
ignore.setField(FieldPosition::DONT_CARE);
string.remove();
form->format(testArgs3, 2, string, ignore, err);
if (U_FAILURE(err) || string != "The disk \"MyDisk\" contains 12 file(s).") {
errln(UnicodeString("TestMessageFormat::testSimpleFormat failed on test #3")+string);
}
delete form;
}
void TestMessageFormat::testMsgFormatChoice(/* char* par */)
{
logln("running TestMessageFormat::testMsgFormatChoice");
UErrorCode err = U_ZERO_ERROR;
MessageFormat* form = new MessageFormat("The disk \"{1}\" contains {0}.", err);
double filelimits[] = {0,1,2};
UnicodeString filepart[] = {"no files","one file","{0,number} files"};
ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3);
form->setFormat(1,*fileform); // NOT zero, see below
//is the format adopted?
FieldPosition ignore(FieldPosition::DONT_CARE);
UnicodeString string;
Formattable testArgs1[] = {(int32_t)0, "MyDisk"};
form->format(testArgs1, 2, string, ignore, err);
if (string != "The disk \"MyDisk\" contains no files.") {
errln("TestMessageFormat::testMsgFormatChoice failed on test #1");
}
ignore.setField(FieldPosition::DONT_CARE);
string.remove();
Formattable testArgs2[] = {(int32_t)1, "MyDisk"};
form->format(testArgs2, 2, string, ignore, err);
if (string != "The disk \"MyDisk\" contains one file.") {
errln("TestMessageFormat::testMsgFormatChoice failed on test #2");
}
ignore.setField(FieldPosition::DONT_CARE);
string.remove();
Formattable testArgs3[] = {(int32_t)1273, "MyDisk"};
form->format(testArgs3, 2, string, ignore, err);
if (string != "The disk \"MyDisk\" contains 1,273 files.") {
errln("TestMessageFormat::testMsgFormatChoice failed on test #3");
}
delete form;
delete fileform;
}
//---------------------------------
// API Tests
//---------------------------------
void TestMessageFormat::testCopyConstructor()
{
logln("TestMessageFormat::testCopyConstructor");
UErrorCode success = U_ZERO_ERROR;
MessageFormat *x = new MessageFormat("There are {0} files on {1}", success);
MessageFormat *z = new MessageFormat("There are {0} files on {1} created", success);
MessageFormat *y = 0;
y = new MessageFormat(*x);
if ( (*x == *y) &&
(*x != *z) &&
(*y != *z) )
logln("First test (operator ==): Passed!");
else {
errln("TestMessageFormat::testCopyConstructor failed #1");
logln("First test (operator ==): Failed!");
}
if ( ((*x == *y) && (*y == *x)) &&
((*x != *z) && (*z != *x)) &&
((*y != *z) && (*z != *y)) )
logln("Second test (equals): Passed!");
else {
errln("TestMessageFormat::testCopyConstructor failed #2");
logln("Second test (equals): Failed!");
}
delete x;
delete y;
delete z;
}
void TestMessageFormat::testAssignment()
{
logln("TestMessageFormat::testAssignment");
UErrorCode success = U_ZERO_ERROR;
MessageFormat *x = new MessageFormat("There are {0} files on {1}", success);
MessageFormat *z = new MessageFormat("There are {0} files on {1} created", success);
MessageFormat *y = new MessageFormat("There are {0} files on {1} created", success);
*y = *x;
if ( (*x == *y) &&
(*x != *z) &&
(*y != *z) )
logln("First test (operator ==): Passed!");
else {
errln( "TestMessageFormat::testAssignment failed #1");
logln("First test (operator ==): Failed!");
}
if ( ((*x == *y) && (*y == *x)) &&
((*x != *z) && (*z != *x)) &&
((*y != *z) && (*z != *y)) )
logln("Second test (equals): Passed!");
else {
errln("TestMessageFormat::testAssignment failed #2");
logln("Second test (equals): Failed!");
}
delete x;
delete y;
delete z;
}
void TestMessageFormat::testClone()
{
logln("TestMessageFormat::testClone");
UErrorCode success = U_ZERO_ERROR;
MessageFormat *x = new MessageFormat("There are {0} files on {1}", success);
MessageFormat *z = new MessageFormat("There are {0} files on {1} created", success);
MessageFormat *y = 0;
y = (MessageFormat*)x->clone();
if ( (*x == *y) &&
(*x != *z) &&
(*y != *z) )
logln("First test (operator ==): Passed!");
else {
errln("TestMessageFormat::testClone failed #1");
logln("First test (operator ==): Failed!");
}
if ( ((*x == *y) && (*y == *x)) &&
((*x != *z) && (*z != *x)) &&
((*y != *z) && (*z != *y)) )
logln("Second test (equals): Passed!");
else {
errln("TestMessageFormat::testClone failed #2");
logln("Second test (equals): Failed!");
}
delete x;
delete y;
delete z;
}
void TestMessageFormat::testEquals()
{
logln("TestMessageFormat::testClone");
UErrorCode success = U_ZERO_ERROR;
MessageFormat x("There are {0} files on {1}", success);
MessageFormat y("There are {0} files on {1}", success);
if (!(x == y)) {
errln( "TestMessageFormat::testEquals failed #1");
logln("First test (operator ==): Failed!");
}
}
void TestMessageFormat::testNotEquals()
{
UErrorCode success = U_ZERO_ERROR;
MessageFormat x("There are {0} files on {1}", success);
MessageFormat y(x);
y.setLocale(Locale("fr"));
if (!(x != y)) {
errln( "TestMessageFormat::testEquals failed #1");
logln("First test (operator !=): Failed!");
}
y = x;
y.applyPattern("There are {0} files on {1} the disk", success);
if (!(x != y)) {
errln( "TestMessageFormat::testEquals failed #1");
logln("First test (operator !=): Failed!");
}
}
void TestMessageFormat::testSetLocale()
{
UErrorCode err = U_ZERO_ERROR;
GregorianCalendar cal(err);
Formattable arguments[] = {
456.83,
Formattable(UDate(8.71068e+011), Formattable::kIsDate),
"deposit"
};
UnicodeString result;
//UnicodeString formatStr = "At {1,time} on {1,date}, you made a {2} of {0,number,currency}.";
UnicodeString formatStr = "At <time> on {1,date}, you made a {2} of {0,number,currency}.";
// {sfb} to get $, would need Locale::US, not Locale::ENGLISH
// Just use unlocalized currency symbol.
//UnicodeString compareStrEng = "At <time> on Aug 8, 1997, you made a deposit of $456.83.";
UnicodeString compareStrEng = "At <time> on Aug 8, 1997, you made a deposit of ";
compareStrEng += (UChar) 0x00a4;
compareStrEng += "456.83.";
// {sfb} to get DM, would need Locale::GERMANY, not Locale::GERMAN
// Just use unlocalized currency symbol.
//UnicodeString compareStrGer = "At <time> on 08.08.1997, you made a deposit of 456,83 DM.";
UnicodeString compareStrGer = "At <time> on 08.08.1997, you made a deposit of ";
compareStrGer += (UChar) 0x00a4;
compareStrGer += " 456,83.";
MessageFormat msg( formatStr, err);
result = "";
FieldPosition pos(0);
result = msg.format(
arguments,
3,
result,
pos,
err);
logln(result);
if (result != compareStrEng) {
errln("*** MSG format err.");
}
msg.setLocale(Locale::getEnglish());
UBool getLocale_ok = TRUE;
if (msg.getLocale() != Locale::getEnglish()) {
errln("*** MSG getLocal err.");
getLocale_ok = FALSE;
}
msg.setLocale(Locale::getGerman());
if (msg.getLocale() != Locale::getGerman()) {
errln("*** MSG getLocal err.");
getLocale_ok = FALSE;
}
msg.applyPattern( formatStr, err);
pos.setField(0);
result = "";
result = msg.format(
arguments,
3,
result,
pos,
err);
logln(result);
if (result == compareStrGer) {
logln("MSG setLocale tested.");
}else{
errln( "*** MSG setLocale err.");
}
if (getLocale_ok) {
logln("MSG getLocale tested.");
}
}
void TestMessageFormat::testFormat()
{
UErrorCode err = U_ZERO_ERROR;
GregorianCalendar cal(err);
const Formattable ftarray[] =
{
Formattable( UDate(8.71068e+011), Formattable::kIsDate )
};
const int32_t ft_cnt = sizeof(ftarray) / sizeof(Formattable);
Formattable ft_arr( ftarray, ft_cnt );
Formattable* fmt = new Formattable(UDate(8.71068e+011), Formattable::kIsDate);
UnicodeString result;
//UnicodeString formatStr = "At {1,time} on {1,date}, you made a {2} of {0,number,currency}.";
UnicodeString formatStr = "On {0,date}, it began.";
UnicodeString compareStr = "On Aug 8, 1997, it began.";
err = U_ZERO_ERROR;
MessageFormat msg( formatStr, err);
FieldPosition fp(0);
result = "";
fp = 0;
result = msg.format(
*fmt,
result,
//FieldPosition(0),
fp,
err);
if (err != U_ILLEGAL_ARGUMENT_ERROR) {
errln("*** MSG format without expected error code.");
}
err = U_ZERO_ERROR;
result = "";
fp = 0;
result = msg.format(
ft_arr,
result,
//FieldPosition(0),
fp,
err);
logln("MSG format( Formattable&, ... ) expected:" + compareStr);
logln("MSG format( Formattable&, ... ) result:" + result);
if (result != compareStr) {
errln("*** MSG format( Formattable&, .... ) err.");
}else{
logln("MSG format( Formattable&, ... ) tested.");
}
delete fmt;
}
void TestMessageFormat::testParse()
{
UErrorCode err = U_ZERO_ERROR;
int32_t count;
UnicodeString msgFormatString = "{0} =sep= {1}";
MessageFormat msg( msgFormatString, err);
UnicodeString source = "abc =sep= def";
UnicodeString tmp1, tmp2;
Formattable* fmt_arr = msg.parse( source, count, err );
if (U_FAILURE(err) || (!fmt_arr)) {
errln("*** MSG parse (ustring, count, err) error.");
}else{
logln("MSG parse -- count: %d", count);
if (count != 2) {
errln("*** MSG parse (ustring, count, err) count err.");
}else{
if ((fmt_arr[0].getType() == Formattable::kString)
&& (fmt_arr[1].getType() == Formattable::kString)
&& (fmt_arr[0].getString(tmp1) == "abc")
&& (fmt_arr[1].getString(tmp2) == "def")) {
logln("MSG parse (ustring, count, err) tested.");
}else{
errln("*** MSG parse (ustring, count, err) result err.");
}
}
}
delete[] fmt_arr;
ParsePosition pp(0);
fmt_arr = msg.parse( source, pp, count );
if ((pp == 0) || (!fmt_arr)) {
errln("*** MSG parse (ustring, parsepos., count) error.");
}else{
logln("MSG parse -- count: %d", count);
if (count != 2) {
errln("*** MSG parse (ustring, parsepos., count) count err.");
}else{
if ((fmt_arr[0].getType() == Formattable::kString)
&& (fmt_arr[1].getType() == Formattable::kString)
&& (fmt_arr[0].getString(tmp1) == "abc")
&& (fmt_arr[1].getString(tmp2) == "def")) {
logln("MSG parse (ustring, parsepos., count) tested.");
}else{
errln("*** MSG parse (ustring, parsepos., count) result err.");
}
}
}
delete[] fmt_arr;
pp = 0;
Formattable fmta;
msg.parseObject( source, fmta, pp );
if (pp == 0) {
errln("*** MSG parse (ustring, Formattable, parsepos ) error.");
}else{
logln("MSG parse -- count: %d", count);
fmta.getArray(count);
if (count != 2) {
errln("*** MSG parse (ustring, Formattable, parsepos ) count err.");
}else{
if ((fmta[0].getType() == Formattable::kString)
&& (fmta[1].getType() == Formattable::kString)
&& (fmta[0].getString(tmp1) == "abc")
&& (fmta[1].getString(tmp2) == "def")) {
logln("MSG parse (ustring, Formattable, parsepos ) tested.");
}else{
errln("*** MSG parse (ustring, Formattable, parsepos ) result err.");
}
}
}
}
void TestMessageFormat::testAdopt()
{
UErrorCode err = U_ZERO_ERROR;
UnicodeString formatStr("{0,date},{1},{2,number}", "");
UnicodeString formatStrChange("{0,number},{1,number},{2,date}", "");
err = U_ZERO_ERROR;
MessageFormat msg( formatStr, err);
MessageFormat msgCmp( formatStr, err);
int32_t count, countCmp;
const Format** formats = msg.getFormats(count);
const Format** formatsCmp = msgCmp.getFormats(countCmp);
const Format** formatsChg = 0;
const Format** formatsAct = 0;
int32_t countAct;
const Format* a;
const Format* b;
UnicodeString patCmp;
UnicodeString patAct;
Format** formatsToAdopt;
if (!formats || !formatsCmp || (count <= 0) || (count != countCmp)) {
errln("Error getting Formats");
return;
}
int32_t i;
for (i = 0; i < count; i++) {
a = formats[i];
b = formatsCmp[i];
if ((a != NULL) && (b != NULL)) {
if (*a != *b) {
errln("a != b");
return;
}
}else if ((a != NULL) || (b != NULL)) {
errln("(a != NULL) || (b != NULL)");
return;
}
}
msg.applyPattern( formatStrChange, err ); //set msg formats to something different
int32_t countChg;
formatsChg = msg.getFormats(countChg); // tested function
if (!formatsChg || (countChg != count)) {
errln("Error getting Formats");
return;
}
UBool diff;
diff = TRUE;
for (i = 0; i < count; i++) {
a = formatsChg[i];
b = formatsCmp[i];
if ((a != NULL) && (b != NULL)) {
if (*a == *b) {
logln("formatsChg != formatsCmp at index %d", i);
diff = FALSE;
}
}
}
if (!diff) {
errln("*** MSG getFormats diff err.");
return;
}
logln("MSG getFormats tested.");
msg.setFormats( formatsCmp, countCmp ); //tested function
formatsAct = msg.getFormats(countAct);
if (!formatsAct || (countAct <=0) || (countAct != countCmp)) {
errln("Error getting Formats");
return;
}
#if 1
msgCmp.toPattern( patCmp );
logln("MSG patCmp: " + patCmp);
msg.toPattern( patAct );
logln("MSG patAct: " + patAct);
#endif
for (i = 0; i < countAct; i++) {
a = formatsAct[i];
b = formatsCmp[i];
if ((a != NULL) && (b != NULL)) {
if (*a != *b) {
logln("formatsAct != formatsCmp at index %d", i);
errln("a != b");
return;
}
}else if ((a != NULL) || (b != NULL)) {
errln("(a != NULL) || (b != NULL)");
return;
}
}
logln("MSG setFormats tested.");
//----
msg.applyPattern( formatStrChange, err ); //set msg formats to something different
formatsToAdopt = new Format* [countCmp];
if (!formatsToAdopt) {
errln("memory allocation error");
return;
}
for (i = 0; i < countCmp; i++) {
if (formatsCmp[i] == NULL) {
formatsToAdopt[i] = NULL;
}else{
formatsToAdopt[i] = formatsCmp[i]->clone();
if (!formatsToAdopt[i]) {
errln("Can't clone format at index %d", i);
return;
}
}
}
msg.adoptFormats( formatsToAdopt, countCmp ); // function to test
delete[] formatsToAdopt;
#if 1
msgCmp.toPattern( patCmp );
logln("MSG patCmp: " + patCmp);
msg.toPattern( patAct );
logln("MSG patAct: " + patAct);
#endif
formatsAct = msg.getFormats(countAct);
if (!formatsAct || (countAct <=0) || (countAct != countCmp)) {
errln("Error getting Formats");
return;
}
for (i = 0; i < countAct; i++) {
a = formatsAct[i];
b = formatsCmp[i];
if ((a != NULL) && (b != NULL)) {
if (*a != *b) {
errln("a != b");
return;
}
}else if ((a != NULL) || (b != NULL)) {
errln("(a != NULL) || (b != NULL)");
return;
}
}
logln("MSG adoptFormats tested.");
//---- adoptFormat
msg.applyPattern( formatStrChange, err ); //set msg formats to something different
formatsToAdopt = new Format* [countCmp];
if (!formatsToAdopt) {
errln("memory allocation error");
return;
}
for (i = 0; i < countCmp; i++) {
if (formatsCmp[i] == NULL) {
formatsToAdopt[i] = NULL;
}else{
formatsToAdopt[i] = formatsCmp[i]->clone();
if (!formatsToAdopt[i]) {
errln("Can't clone format at index %d", i);
return;
}
}
}
for ( i = 0; i < countCmp; i++ ) {
msg.adoptFormat( i, formatsToAdopt[i] ); // function to test
}
delete[] formatsToAdopt; // array itself not needed in this case;
#if 1
msgCmp.toPattern( patCmp );
logln("MSG patCmp: " + patCmp);
msg.toPattern( patAct );
logln("MSG patAct: " + patAct);
#endif
formatsAct = msg.getFormats(countAct);
if (!formatsAct || (countAct <=0) || (countAct != countCmp)) {
errln("Error getting Formats");
return;
}
for (i = 0; i < countAct; i++) {
a = formatsAct[i];
b = formatsCmp[i];
if ((a != NULL) && (b != NULL)) {
if (*a != *b) {
errln("a != b");
return;
}
}else if ((a != NULL) || (b != NULL)) {
errln("(a != NULL) || (b != NULL)");
return;
}
}
logln("MSG adoptFormat tested.");
}
// This test is a regression test for a fixed bug in the copy constructor.
// It is kept as a global function rather than as a method since the test depends on memory values.
// (At least before the bug was fixed, whether it showed up or not depended on memory contents,
// which is probably why it didn't show up in the regular test for the copy constructor.)
// For this reason, the test isn't changed even though it contains function calls whose results are
// not tested and had no problems. Actually, the test failed by *crashing*.
static void _testCopyConstructor2()
{
UErrorCode status = U_ZERO_ERROR;
UnicodeString formatStr("Hello World on {0,date,full}", "");
UnicodeString resultStr(" ", "");
UnicodeString result;
FieldPosition fp(0);
UDate d = Calendar::getNow();
const Formattable fargs( d, Formattable::kIsDate );
MessageFormat* fmt1 = new MessageFormat( formatStr, status );
MessageFormat* fmt2 = new MessageFormat( *fmt1 );
MessageFormat* fmt3;
MessageFormat* fmt4;
if (fmt1 == NULL) it_err("testCopyConstructor2: (fmt1 != NULL)");
result = fmt1->format( &fargs, 1, resultStr, fp, status );
if (fmt2 == NULL) it_err("testCopyConstructor2: (fmt2 != NULL)");
fmt3 = (MessageFormat*) fmt1->clone();
fmt4 = (MessageFormat*) fmt2->clone();
if (fmt3 == NULL) it_err("testCopyConstructor2: (fmt3 != NULL)");
if (fmt4 == NULL) it_err("testCopyConstructor2: (fmt4 != NULL)");
result = fmt1->format( &fargs, 1, resultStr, fp, status );
result = fmt2->format( &fargs, 1, resultStr, fp, status );
result = fmt3->format( &fargs, 1, resultStr, fp, status );
result = fmt4->format( &fargs, 1, resultStr, fp, status );
delete fmt1;
delete fmt2;
delete fmt3;
delete fmt4;
}
void TestMessageFormat::testCopyConstructor2() {
_testCopyConstructor2();
}
/**
* Verify that MessageFormat accomodates more than 10 arguments and
* more than 10 subformats.
*/
void TestMessageFormat::TestUnlimitedArgsAndSubformats() {
UErrorCode ec = U_ZERO_ERROR;
const UnicodeString pattern =
"On {0,date} (aka {0,date,short}, aka {0,date,long}) "
"at {0,time} (aka {0,time,short}, aka {0,time,long}) "
"there were {1,number} werjes "
"(a {3,number,percent} increase over {2,number}) "
"despite the {4}''s efforts "
"and to delight of {5}, {6}, {7}, {8}, {9}, and {10} {11}.";
MessageFormat msg(pattern, ec);
if (U_FAILURE(ec)) {
errln("FAIL: constructor failed");
return;
}
const Formattable ARGS[] = {
Formattable(UDate(1e13), Formattable::kIsDate),
Formattable((int32_t)1303),
Formattable((int32_t)1202),
Formattable(1303.0/1202 - 1),
Formattable("Glimmung"),
Formattable("the printers"),
Formattable("Nick"),
Formattable("his father"),
Formattable("his mother"),
Formattable("the spiddles"),
Formattable("of course"),
Formattable("Horace"),
};
const int32_t ARGS_LENGTH = sizeof(ARGS) / sizeof(ARGS[0]);
Formattable ARGS_OBJ(ARGS, ARGS_LENGTH);
UnicodeString expected =
"On Nov 20, 2286 (aka 11/20/86, aka November 20, 2286) "
"at 9:46:40 AM (aka 9:46 AM, aka 9:46:40 AM PST) "
"there were 1,303 werjes "
"(a 8% increase over 1,202) "
"despite the Glimmung's efforts "
"and to delight of the printers, Nick, his father, "
"his mother, the spiddles, and of course Horace.";
UnicodeString result;
msg.format(ARGS_OBJ, result, ec);
if (result == expected) {
logln(result);
} else {
errln((UnicodeString)"FAIL: Got " + result +
", expected " + expected);
}
}
#endif /* #if !UCONFIG_NO_FORMATTING */
| [
"(no author)@251d0590-4201-4cf1-90de-194747b24ca1"
] | (no author)@251d0590-4201-4cf1-90de-194747b24ca1 |
316fb9e519406644c63d36d829da9a1f13f7623c | a158b5b0cc491912ad0166fd891efd5abb951f51 | /src/cc/meta/LogTransmitter.cc | d5f842255d46ccca08d997b1c1912e9cad893445 | [
"Apache-2.0"
] | permissive | quantcast/qfs | 467651a3af7e77e779f199429d74dde67cee8c10 | 0d9dab4e51b27dde5869dd948e26b62e769e7d95 | refs/heads/master | 2023-08-04T12:47:56.591858 | 2023-05-06T02:42:34 | 2023-05-06T02:42:34 | 5,447,814 | 372 | 136 | Apache-2.0 | 2023-05-06T01:22:44 | 2012-08-17T03:59:37 | C++ | UTF-8 | C++ | false | false | 77,431 | cc | //---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2015/04/27
// Author: Mike Ovsiannikov
//
// Copyright 2015 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// Transaction log replication transmitter.
//
//
//----------------------------------------------------------------------------
#include "LogTransmitter.h"
#include "MetaRequest.h"
#include "MetaVrOps.h"
#include "MetaVrLogSeq.h"
#include "MetaVrSM.h"
#include "util.h"
#include "common/kfstypes.h"
#include "common/MsgLogger.h"
#include "common/Properties.h"
#include "common/AverageFilter.h"
#include "kfsio/KfsCallbackObj.h"
#include "kfsio/NetConnection.h"
#include "kfsio/NetManager.h"
#include "kfsio/IOBuffer.h"
#include "kfsio/ClientAuthContext.h"
#include "kfsio/event.h"
#include "kfsio/checksum.h"
#include "qcdio/QCUtils.h"
#include "qcdio/qcdebug.h"
#include <string.h>
#include <limits>
#include <string>
#include <algorithm>
#include <set>
#include <deque>
#include <utility>
namespace KFS
{
using std::string;
using std::max;
using std::multiset;
using std::deque;
using std::pair;
using std::find;
class LogTransmitter::Impl : public ITimeout
{
private:
class Transmitter;
enum { kHeartbeatsPerTimeoutInterval = 2 };
public:
typedef MetaVrSM::Config Config;
typedef Config::NodeId NodeId;
typedef QCDLList<Transmitter> List;
typedef uint32_t Checksum;
Impl(
LogTransmitter& inTransmitter,
NetManager& inNetManager,
CommitObserver& inCommitObserver)
: ITimeout(),
mTransmitter(inTransmitter),
mNetManager(inNetManager),
mRetryInterval(2),
mMaxReadAhead(MAX_RPC_HEADER_LEN),
mHeartbeatInterval(16),
mMinAckToCommit(numeric_limits<int>::max()),
mMaxPending(16 << 20),
mCompactionInterval(256),
mCommitted(),
mPendingAckByteCount(0),
mAuthType(
kAuthenticationTypeKrb5 |
kAuthenticationTypeX509 |
kAuthenticationTypePSK),
mAuthTypeStr("Krb5 X509 PSK"),
mCommitObserver(inCommitObserver),
mIdsCount(0),
mNodeId(-1),
mSendingFlag(false),
mPendingUpdateFlag(false),
mUpFlag(false),
mSuspendedFlag(false),
mFileSystemId(-1),
mNextTimerRunTimeUsec(inNetManager.NowUsec()),
mMetaVrSMPtr(0),
mTransmitterAuthParamsPrefix(),
mTransmitterAuthParams()
{
List::Init(mTransmittersPtr);
mTmpBuf[kTmpBufSize] = 0;
mSeqBuf[kSeqBufSize] = 0;
mNetManager.RegisterTimeoutHandler(this);
}
~Impl()
{
mNetManager.UnRegisterTimeoutHandler(this);
Impl::Shutdown();
}
int SetParameters(
const char* inParamPrefixPtr,
const Properties& inParameters);
int TransmitBlock(
const MetaVrLogSeq& inBlockSeq,
int inBlockSeqLen,
const char* inBlockPtr,
size_t inBlockLen,
Checksum inChecksum,
size_t inChecksumStartPos);
void NotifyAck(
LogTransmitter::NodeId inNodeId,
const MetaVrLogSeq& inAckSeq,
NodeId inPrimaryNodeId);
static seq_t RandomSeq()
{
seq_t theReq = 0;
CryptoKeys::PseudoRand(&theReq, sizeof(theReq));
return ((theReq < 0 ? -theReq : theReq) >> 1);
}
void SetFileSystemId(
int64_t inFsId)
{ mFileSystemId = inFsId; }
char* GetParseBufferPtr()
{ return mParseBuffer; }
NetManager& GetNetManager()
{ return mNetManager; }
int GetRetryInterval() const
{ return mRetryInterval; }
int GetMaxReadAhead() const
{ return mMaxReadAhead; }
int GetHeartbeatInterval() const
{ return mHeartbeatInterval; }
void SetHeartbeatInterval(
int inPrimaryTimeoutSec)
{
mHeartbeatInterval = max(1, inPrimaryTimeoutSec /
kHeartbeatsPerTimeoutInterval - 1);
}
MetaVrLogSeq GetCommitted() const
{ return mCommitted; }
int GetMaxPending() const
{ return mMaxPending; }
int GetCompactionInterval() const
{ return mCompactionInterval; }
int GetChannelsCount() const
{ return mTransmittersCount; }
void Shutdown();
void Acked(
const MetaVrLogSeq& inPrevAck,
NodeId inPrevPrimaryNodeId,
Transmitter& inTransmitter);
void WriteBlock(
IOBuffer& inBuffer,
const MetaVrLogSeq& inBlockSeq,
int inBlockSeqLen,
const char* inBlockPtr,
size_t inBlockLen,
Checksum inChecksum,
size_t inChecksumStartPos)
{
if (inBlockSeqLen < 0) {
panic("log transmitter: invalid block sequence length");
return;
}
Checksum theChecksum = inChecksum;
if (inChecksumStartPos <= inBlockLen) {
theChecksum = ComputeBlockChecksum(
theChecksum,
inBlockPtr + inChecksumStartPos,
inBlockLen - inChecksumStartPos
);
}
// Block sequence is at the end of the header, and is part of the
// checksum.
char* const theSeqEndPtr = mSeqBuf + kSeqBufSize;
char* thePtr = theSeqEndPtr;
*--thePtr = '\n';
thePtr = IntToHexString(inBlockSeqLen, thePtr);
*--thePtr = ' ';
thePtr = IntToHexString(inBlockSeq.mLogSeq, thePtr);
*--thePtr = ' ';
thePtr = IntToHexString(inBlockSeq.mViewSeq, thePtr);
*--thePtr = ' ';
thePtr = IntToHexString(inBlockSeq.mEpochSeq, thePtr);
*--thePtr = ' ';
thePtr = IntToHexString(mFileSystemId, thePtr);
// Non empty block checksum includes leading '\n'
const int theChecksumFrontLen = 0 < inBlockLen ? 1 : 0;
theChecksum = ChecksumBlocksCombine(
ComputeBlockChecksum(
thePtr,
theSeqEndPtr - thePtr - theChecksumFrontLen),
theChecksum,
inBlockLen + theChecksumFrontLen
);
const char* const theSeqPtr = thePtr;
const int theBlockLen =
(int)(theSeqEndPtr - theSeqPtr) + max(0, (int)inBlockLen);
char* const theEndPtr = mTmpBuf + kTmpBufSize;
thePtr = theEndPtr;
*--thePtr = ' ';
thePtr = IntToHexString(theBlockLen, thePtr);
*--thePtr = ':';
*--thePtr = 'l';
inBuffer.CopyIn(thePtr, (int)(theEndPtr - thePtr));
thePtr = theEndPtr;
*--thePtr = '\n';
*--thePtr = '\r';
*--thePtr = '\n';
*--thePtr = '\r';
thePtr = IntToHexString(theChecksum, thePtr);
inBuffer.CopyIn(thePtr, (int)(theEndPtr - thePtr));
inBuffer.CopyIn(theSeqPtr, (int)(theSeqEndPtr - theSeqPtr));
inBuffer.CopyIn(inBlockPtr, (int)inBlockLen);
}
bool IsUp() const
{ return mUpFlag; }
const bool& GetUpFlag() const
{ return mUpFlag; }
void Update(
Transmitter& inTransmitter);
int GetAuthType() const
{ return mAuthType; }
void QueueVrRequest(
MetaVrRequest& inVrReq,
NodeId inNodeId);
int Update(
MetaVrSM& inMetaVrSM);
void GetStatus(
StatusReporter& inReporter);
MetaVrLogSeq GetLastLogSeq() const
{
return (mMetaVrSMPtr ? mMetaVrSMPtr->GetLastLogSeq() :
MetaVrLogSeq());
}
bool Init(
MetaVrHello& inHello,
const ServerLocation& inPeer)
{
return (mMetaVrSMPtr &&
mMetaVrSMPtr->Init(inHello, inPeer, mTransmitter));
}
NodeId GetNodeId() const
{ return mNodeId; }
void Deleted(
Transmitter& inTransmitter);
void Suspend(
bool inFlag);
void ScheduleHelloTransmit();
void ScheduleHeartbeatTransmit();
int GetPendingAckByteCount() const
{ return mPendingAckByteCount; }
virtual void Timeout();
private:
typedef Properties::String String;
enum { kTmpBufSize = 2 + 1 + sizeof(seq_t) * 2 + 4 };
enum { kSeqBufSize = 5 * kTmpBufSize };
LogTransmitter& mTransmitter;
NetManager& mNetManager;
int mRetryInterval;
int mMaxReadAhead;
int mHeartbeatInterval;
int mMinAckToCommit;
int mMaxPending;
int mCompactionInterval;
MetaVrLogSeq mCommitted;
int mPendingAckByteCount;
int mAuthType;
string mAuthTypeStr;
CommitObserver& mCommitObserver;
int mIdsCount;
NodeId mNodeId;
bool mSendingFlag;
bool mPendingUpdateFlag;
bool mUpFlag;
bool mSuspendedFlag;
int64_t mFileSystemId;
int64_t mNextTimerRunTimeUsec;
MetaVrSM* mMetaVrSMPtr;
string mTransmitterAuthParamsPrefix;
Properties mTransmitterAuthParams;
int mTransmittersCount;
Transmitter* mTransmittersPtr[1];
char mParseBuffer[MAX_RPC_HEADER_LEN];
char mTmpBuf[kTmpBufSize + 1];
char mSeqBuf[kSeqBufSize + 1];
void Insert(
Transmitter& inTransmitter);
void EndOfTransmit();
void Update();
int StartTransmitters(
ClientAuthContext* inAuthCtxPtr);
private:
Impl(
const Impl& inImpl);
Impl& operator=(
const Impl& inImpl);
};
class LogTransmitter::Impl::Transmitter :
public KfsCallbackObj,
public ITimeout
{
public:
typedef Impl::List List;
typedef Impl::NodeId NodeId;
typedef LogTransmitter::StatusReporter::Counters Counters;
Transmitter(
Impl& inImpl,
const ServerLocation& inServer,
NodeId inNodeId,
bool inActiveFlag,
const MetaVrLogSeq& inLastLogSeq)
: KfsCallbackObj(),
mImpl(inImpl),
mServer(inServer),
mPendingSend(),
mBlocksQueue(),
mConnectionPtr(),
mAuthenticateOpPtr(0),
mVrOpPtr(0),
mVrOpSeq(-1),
mNextSeq(mImpl.RandomSeq()),
mRecursionCount(0),
mCompactBlockCount(0),
mHeartbeatSendTimeoutCount(0),
mLastAckReceivedTime(0),
mAuthContext(),
mAuthRequestCtx(),
mLastSentBlockEndSeq(inLastLogSeq),
mAckBlockSeq(),
mAckBlockFlags(0),
mCtrs(),
mPrevResponseTimeUsec(0),
mPrevResponseSeqLength(0),
mReplyProps(),
mIstream(),
mOstream(),
mSleepingFlag(false),
mReceivedIdFlag(false),
mActiveFlag(inActiveFlag),
mSendHelloFlag(false),
mMetaVrHello(*(new MetaVrHello())),
mReceivedId(-1),
mPrimaryNodeId(-1),
mId(inNodeId),
mPeer()
{
SET_HANDLER(this, &Transmitter::HandleEvent);
List::Init(*this);
}
~Transmitter()
{
QCRTASSERT(mRecursionCount == 0);
Transmitter::Shutdown();
MetaRequest::Release(mAuthenticateOpPtr);
if (mSleepingFlag) {
mImpl.GetNetManager().UnRegisterTimeoutHandler(this);
}
VrDisconnect();
MetaRequest::Release(&mMetaVrHello);
mImpl.Deleted(*this);
}
int SetParameters(
ClientAuthContext* inAuthCtxPtr,
const char* inParamPrefixPtr,
const Properties& inParameters,
string& outErrMsg)
{
const bool kVerifyFlag = true;
return mAuthContext.SetParameters(
inParamPrefixPtr,
inParameters,
inAuthCtxPtr,
&outErrMsg,
kVerifyFlag
);
}
void QueueVrRequest(
MetaVrRequest& inReq)
{
if (! mVrOpPtr && ! mPendingSend.IsEmpty() &&
mConnectionPtr && ! mConnectionPtr->IsWriteReady()) {
ResetPending();
}
if (! mPendingSend.IsEmpty() || mVrOpPtr) {
KFS_LOG_STREAM_DEBUG <<
mServer <<
" queue VR request:"
" pending: " << mPendingSend.BytesConsumable() <<
" hello seq: " << mMetaVrHello.opSeqno <<
" cancel: " << MetaRequest::ShowReq(mVrOpPtr) <<
KFS_LOG_EOM;
Shutdown();
Reset("queue VR request");
}
if (mVrOpPtr) {
panic("log transmitter: invalid Vr op");
MetaRequest::Release(mVrOpPtr);
}
inReq.Ref();
mVrOpSeq = -1;
mVrOpPtr = &inReq;
if (mConnectionPtr) {
if (! mAuthenticateOpPtr) {
StartSend();
}
} else {
Start();
}
}
void Start()
{
if (! mConnectionPtr && ! mSleepingFlag) {
Connect();
SendHeartbeat();
}
}
int HandleEvent(
int inType,
void* inDataPtr)
{
mRecursionCount++;
QCASSERT(0 < mRecursionCount);
switch (inType) {
case EVENT_NET_READ:
QCASSERT(&mConnectionPtr->GetInBuffer() == inDataPtr);
HandleRead();
break;
case EVENT_NET_WROTE:
mHeartbeatSendTimeoutCount = 0;
break;
case EVENT_CMD_DONE:
if (! inDataPtr) {
panic("log transmitter: invalid null command completion");
break;
}
HandleCmdDone(*reinterpret_cast<MetaRequest*>(inDataPtr));
break;
case EVENT_NET_ERROR:
if (HandleSslShutdown()) {
break;
}
Error("network error");
break;
case EVENT_INACTIVITY_TIMEOUT:
if (SendHeartbeat()) {
break;
}
if (++mHeartbeatSendTimeoutCount <
Impl::kHeartbeatsPerTimeoutInterval) {
break;
}
Error("connection timed out");
break;
default:
panic("log transmitter: unexpected event");
break;
}
if (mRecursionCount <= 1) {
if (mConnectionPtr && mConnectionPtr->IsGood()) {
if (! mBlocksQueue.empty() && mLastAckReceivedTime +
4 * mImpl.GetHeartbeatInterval() <
mImpl.GetNetManager().Now()) {
Error("ACK timed out");
} else {
mConnectionPtr->StartFlush();
}
} else if (mConnectionPtr) {
Error();
}
if (mConnectionPtr && ! mAuthenticateOpPtr) {
mConnectionPtr->SetMaxReadAhead(mImpl.GetMaxReadAhead());
mConnectionPtr->SetInactivityTimeout(
mImpl.GetHeartbeatInterval());
}
}
mRecursionCount--;
QCASSERT(0 <= mRecursionCount);
return 0;
}
void CloseConnection()
{
if (mConnectionPtr) {
mConnectionPtr->Close();
mConnectionPtr.reset();
}
NodeId const thePrevPrimaryId = mPrimaryNodeId;
mPrimaryNodeId = -1;
MetaRequest::Release(mAuthenticateOpPtr);
mAuthenticateOpPtr = 0;
AdvancePendingQueue();
const MetaVrLogSeq thePrevAckSeq = mAckBlockSeq;
mAckBlockSeq = MetaVrLogSeq();
if (mSleepingFlag) {
mSleepingFlag = false;
mImpl.GetNetManager().UnRegisterTimeoutHandler(this);
}
mPeer.port = -1;
mPeer.hostname.clear();
mSendHelloFlag = true;
mMetaVrHello.opSeqno = -1;
mVrOpSeq = -1;
mReplyProps.clear();
UpdateAck(thePrevAckSeq, thePrevPrimaryId);
}
void Shutdown()
{
CloseConnection();
VrDisconnect();
mPeer.port = -1;
mPeer.hostname.clear();
mReplyProps.clear();
}
const ServerLocation& GetServerLocation() const
{ return mServer; }
virtual void Timeout()
{
if (mSleepingFlag) {
mSleepingFlag = false;
mImpl.GetNetManager().UnRegisterTimeoutHandler(this);
}
Connect();
}
bool SendBlock(
const MetaVrLogSeq& inBlockEndSeq,
int inBlockSeqLen,
IOBuffer& inBuffer,
int inLen)
{
if (inBlockEndSeq <= mAckBlockSeq ||
inLen <= 0 ||
inBlockEndSeq <= mLastSentBlockEndSeq ||
CanBypassSend(inBlockEndSeq, inBlockSeqLen)) {
return true;
}
if (mImpl.GetMaxPending() < inLen + mPendingSend.BytesConsumable()) {
ResetPending();
}
if (mConnectionPtr && ! mAuthenticateOpPtr) {
IOBuffer& theBuf = mConnectionPtr->GetOutBuffer();
if (mImpl.GetMaxPending() * 3 / 2 <
inLen + theBuf.BytesConsumable()) {
Error("exceeded max pending send");
} else {
theBuf.Copy(&inBuffer, inLen);
}
}
mPendingSend.Copy(&inBuffer, inLen);
CompactIfNeeded();
const bool kHeartbeatFlag = false;
return FlushBlock(inBlockEndSeq, inBlockSeqLen, inLen, kHeartbeatFlag);
}
bool SendBlock(
const MetaVrLogSeq& inBlockEndSeq,
int inBlockSeqLen,
const char* inBlockPtr,
size_t inBlockLen,
Checksum inChecksum,
size_t inChecksumStartPos)
{
if (inBlockEndSeq <= mAckBlockSeq || inBlockLen <= 0 ||
CanBypassSend(inBlockEndSeq, inBlockSeqLen)) {
return true;
}
const bool kHeartbeatFlag = false;
return SendBlockSelf(
inBlockEndSeq,
inBlockSeqLen,
inBlockPtr,
inBlockLen,
inChecksum,
inChecksumStartPos,
kHeartbeatFlag
);
}
void NotifyAck(
const MetaVrLogSeq& inAckSeq,
NodeId inPrimaryNodeId)
{
const MetaVrLogSeq thePrevAckSeq = mAckBlockSeq;
const NodeId thePrevPrimaryNodeId = mPrimaryNodeId;
mAckBlockSeq = inAckSeq;
mPrimaryNodeId = inPrimaryNodeId;
UpdateAck(thePrevAckSeq, thePrevPrimaryNodeId);
}
ClientAuthContext& GetAuthCtx()
{ return mAuthContext; }
NodeId GetId() const
{ return mId; }
NodeId GetReceivedId() const
{ return mReceivedId; }
MetaVrLogSeq GetAck() const
{ return mAckBlockSeq; }
const ServerLocation& GetLocation() const
{ return mServer; }
bool IsActive() const
{ return mActiveFlag; }
void SetActive(
bool inFlag)
{ mActiveFlag = inFlag; }
NodeId GetPrimaryNodeId() const
{ return mPrimaryNodeId; }
void ScheduleHelloTransmit()
{
if (mSendHelloFlag || ! mConnectionPtr) {
return;
}
mSendHelloFlag = true;
SendHello();
}
void ScheduleHeartbeatTransmit()
{
if (mConnectionPtr) {
SendHeartbeat();
return;
}
Connect();
}
int GetPendingSendByteCount() const
{ return mPendingSend.BytesConsumable(); }
void Timer(
int64_t inRunTimeUsec,
int64_t inNowUsec,
int64_t inIntervalUsec)
{
const int64_t theResponseTimeUsec =
mCtrs.mResponseTimeUsec - mPrevResponseTimeUsec;
const int64_t theOpsCount =
mCtrs.mResponseSeqLength - mPrevResponseSeqLength;
const int64_t theOpUsecs = 0 < theOpsCount ?
theResponseTimeUsec / theOpsCount : int64_t(0);
const int64_t theOpLogRate =
(theOpsCount << Counters::kRateFracBits) *
1000 * 1000 / (inIntervalUsec + inNowUsec - inRunTimeUsec);
mCtrs.mPendingBlockBytes = mPendingSend.BytesConsumable();
mPrevResponseTimeUsec = mCtrs.mResponseTimeUsec;
mPrevResponseSeqLength = mCtrs.mResponseSeqLength;
int64_t theRunTimeUsec = inRunTimeUsec;
while (theRunTimeUsec <= inNowUsec) {
mCtrs.mOp5SecAvgUsec = AverageFilter::Calculate(
mCtrs.mOp5SecAvgUsec,
theOpUsecs,
AverageFilter::kAvg5SecondsDecayExponent
);
mCtrs.mOp10SecAvgUsec = AverageFilter::Calculate(
mCtrs.mOp10SecAvgUsec,
theOpUsecs,
AverageFilter::kAvg10SecondsDecayExponent
);
mCtrs.mOp15SecAvgUsec = AverageFilter::Calculate(
mCtrs.mOp15SecAvgUsec,
theOpUsecs,
AverageFilter::kAvg15SecondsDecayExponent
);
mCtrs.mOp5SecAvgRate = AverageFilter::Calculate(
mCtrs.mOp5SecAvgRate,
theOpLogRate,
AverageFilter::kAvg5SecondsDecayExponent
);
mCtrs.mOp10SecAvgRate = AverageFilter::Calculate(
mCtrs.mOp10SecAvgRate,
theOpLogRate,
AverageFilter::kAvg10SecondsDecayExponent
);
mCtrs.mOp15SecAvgRate = AverageFilter::Calculate(
mCtrs.mOp15SecAvgRate,
theOpLogRate,
AverageFilter::kAvg15SecondsDecayExponent
);
mCtrs.m5SecAvgPendingOps = AverageFilter::Calculate(
mCtrs.m5SecAvgPendingOps,
mCtrs.mPendingBlockSeqLength,
AverageFilter::kAvg5SecondsDecayExponent
);
mCtrs.m10SecAvgPendingOps = AverageFilter::Calculate(
mCtrs.m10SecAvgPendingOps,
mCtrs.mPendingBlockSeqLength,
AverageFilter::kAvg10SecondsDecayExponent
);
mCtrs.m15SecAvgPendingOps = AverageFilter::Calculate(
mCtrs.m15SecAvgPendingOps,
mCtrs.mPendingBlockSeqLength,
AverageFilter::kAvg15SecondsDecayExponent
);
mCtrs.m5SecAvgPendingBytes = AverageFilter::Calculate(
mCtrs.m5SecAvgPendingBytes,
mCtrs.mPendingBlockBytes,
AverageFilter::kAvg5SecondsDecayExponent
);
mCtrs.m10SecAvgPendingBytes = AverageFilter::Calculate(
mCtrs.m10SecAvgPendingBytes,
mCtrs.mPendingBlockBytes,
AverageFilter::kAvg10SecondsDecayExponent
);
mCtrs.m15SecAvgPendingByes = AverageFilter::Calculate(
mCtrs.m15SecAvgPendingByes,
mCtrs.mPendingBlockBytes,
AverageFilter::kAvg15SecondsDecayExponent
);
theRunTimeUsec += inIntervalUsec;
}
}
void GetCounters(
Counters& outCounters)
{
outCounters = mCtrs;
outCounters.mOp5SecAvgUsec >>= AverageFilter::kAvgFracBits;
outCounters.mOp10SecAvgUsec >>= AverageFilter::kAvgFracBits;
outCounters.mOp15SecAvgUsec >>= AverageFilter::kAvgFracBits;
outCounters.mOp5SecAvgRate >>= AverageFilter::kAvgFracBits;
outCounters.mOp10SecAvgRate >>= AverageFilter::kAvgFracBits;
outCounters.mOp15SecAvgRate >>= AverageFilter::kAvgFracBits;
outCounters.m5SecAvgPendingOps >>= AverageFilter::kAvgFracBits;
outCounters.m10SecAvgPendingOps >>= AverageFilter::kAvgFracBits;
outCounters.m15SecAvgPendingOps >>= AverageFilter::kAvgFracBits;
outCounters.m5SecAvgPendingBytes >>= AverageFilter::kAvgFracBits;
outCounters.m10SecAvgPendingBytes >>= AverageFilter::kAvgFracBits;
outCounters.m15SecAvgPendingByes >>= AverageFilter::kAvgFracBits;
}
private:
class BlocksQueueEntry
{
public:
BlocksQueueEntry(
const MetaVrLogSeq& inSeq,
int inLength,
int inSeqLength,
int64_t inStartTime)
: mSeq(inSeq),
mLength(inLength),
mSeqLength(inSeqLength),
mStartTime(inStartTime)
{}
MetaVrLogSeq mSeq;
int mLength;
int mSeqLength;
int64_t mStartTime;
};
typedef ClientAuthContext::RequestCtx RequestCtx;
typedef deque<BlocksQueueEntry> BlocksQueue;
Impl& mImpl;
ServerLocation mServer;
IOBuffer mPendingSend;
BlocksQueue mBlocksQueue;
NetConnectionPtr mConnectionPtr;
MetaAuthenticate* mAuthenticateOpPtr;
MetaVrRequest* mVrOpPtr;
seq_t mVrOpSeq;
seq_t mNextSeq;
int mRecursionCount;
int mCompactBlockCount;
int mHeartbeatSendTimeoutCount;
time_t mLastAckReceivedTime;
ClientAuthContext mAuthContext;
RequestCtx mAuthRequestCtx;
MetaVrLogSeq mLastSentBlockEndSeq;
MetaVrLogSeq mAckBlockSeq;
uint64_t mAckBlockFlags;
Counters mCtrs;
int64_t mPrevResponseTimeUsec;
int64_t mPrevResponseSeqLength;
Properties mReplyProps;
IOBuffer::IStream mIstream;
IOBuffer::WOStream mOstream;
bool mSleepingFlag;
bool mReceivedIdFlag;
bool mActiveFlag;
bool mSendHelloFlag;
MetaVrHello& mMetaVrHello;
NodeId mReceivedId;
NodeId mPrimaryNodeId;
NodeId const mId;
ServerLocation mPeer;
Transmitter* mPrevPtr[1];
Transmitter* mNextPtr[1];
friend class QCDLListOp<Transmitter>;
void UpdateAck(
const MetaVrLogSeq& inPrevAck,
NodeId inPrevPrimaryNodeId)
{
if (mActiveFlag && (! mImpl.IsUp() ||
inPrevAck != mAckBlockSeq ||
inPrevPrimaryNodeId != mPrimaryNodeId)) {
mImpl.Acked(inPrevAck, inPrevPrimaryNodeId, *this);
}
}
bool CanBypassSend(
const MetaVrLogSeq& inBlockEndSeq,
int inBlockSeqLen)
{
if (inBlockSeqLen <= 0 || mImpl.GetNodeId() != mId) {
return false;
}
if (inBlockEndSeq <= mAckBlockSeq) {
return true;
}
mLastSentBlockEndSeq = inBlockEndSeq;
return true;
}
bool SendBlockSelf(
const MetaVrLogSeq& inBlockEndSeq,
int inBlockSeqLen,
const char* inBlockPtr,
size_t inBlockLen,
Checksum inChecksum,
size_t inChecksumStartPos,
bool inHeartbeatFlag)
{
if (inBlockSeqLen < 0) {
panic("log transmitter: invalid block sequence length");
return false;
}
if (mVrOpPtr) {
return false;
}
int thePos = mPendingSend.BytesConsumable();
if (mImpl.GetMaxPending() < thePos) {
ResetPending();
thePos = 0;
}
if (mPendingSend.IsEmpty() || ! mConnectionPtr || mAuthenticateOpPtr) {
WriteBlock(mPendingSend, inBlockEndSeq,
inBlockSeqLen, inBlockPtr, inBlockLen, inChecksum,
inChecksumStartPos);
} else {
IOBuffer theBuffer;
WriteBlock(theBuffer, inBlockEndSeq,
inBlockSeqLen, inBlockPtr, inBlockLen, inChecksum,
inChecksumStartPos);
mPendingSend.Move(&theBuffer);
CompactIfNeeded();
}
mCtrs.mPendingBlockBytes = mPendingSend.BytesConsumable();
return FlushBlock(
inBlockEndSeq,
inBlockSeqLen,
mPendingSend.BytesConsumable() - thePos,
inHeartbeatFlag
);
}
bool FlushBlock(
const MetaVrLogSeq& inBlockEndSeq,
int inBlockSeqLen,
int inLen,
bool inHeartbeatFlag)
{
if (inBlockEndSeq < mLastSentBlockEndSeq || inLen <= 0) {
panic(
"log transmitter: "
"block sequence is invalid: less than last sent, "
"or invalid length"
);
return false;
}
mLastSentBlockEndSeq = inBlockEndSeq;
// Allow to cleanup heartbeats by assigning negative / invalid sequence.
mBlocksQueue.push_back(BlocksQueueEntry(
inHeartbeatFlag ? MetaVrLogSeq() : mLastSentBlockEndSeq,
inLen,
inBlockSeqLen,
mImpl.GetNetManager().NowUsec()
));
mCtrs.mPendingBlockSeqLength += inBlockSeqLen;
if (mRecursionCount <= 0 && ! mAuthenticateOpPtr && mConnectionPtr) {
if (mConnectionPtr->GetOutBuffer().IsEmpty()) {
StartSend();
} else {
mConnectionPtr->StartFlush();
}
}
return (!! mConnectionPtr);
}
void ResetPending()
{
mPendingSend.Clear();
mBlocksQueue.clear();
mCompactBlockCount = 0;
mCtrs.mPendingBlockSeqLength = 0;
mCtrs.mPendingBlockBytes = 0;
}
void Reset(
const char* inErrMsgPtr,
MsgLogger::LogLevel inLogLevel = MsgLogger::kLogLevelERROR)
{
ResetPending();
mLastSentBlockEndSeq = mImpl.GetLastLogSeq();
Error(inErrMsgPtr, inLogLevel);
}
void CompactIfNeeded()
{
mCompactBlockCount++;
if (mImpl.GetCompactionInterval() < mCompactBlockCount) {
mPendingSend.MakeBuffersFull();
mCompactBlockCount = 0;
}
}
void WriteBlock(
IOBuffer& inBuffer,
const MetaVrLogSeq& inBlockSeq,
int inBlockSeqLen,
const char* inBlockPtr,
size_t inBlockLen,
Checksum inChecksum,
size_t inChecksumStartPos)
{
mImpl.WriteBlock(inBuffer, inBlockSeq,
inBlockSeqLen, inBlockPtr, inBlockLen, inChecksum,
inChecksumStartPos);
if (! mConnectionPtr || mAuthenticateOpPtr) {
return;
}
mConnectionPtr->GetOutBuffer().Copy(
&inBuffer, inBuffer.BytesConsumable());
}
void Connect()
{
CloseConnection();
if (! mImpl.GetNetManager().IsRunning()) {
return;
}
if (! mServer.IsValid()) {
return;
}
mLastAckReceivedTime = mImpl.GetNetManager().Now();
mReceivedIdFlag = false;
const bool theReadIfOverloadedFlag = true;
const NetConnectionPtr theConnPtr = NetConnection::Connect(
mImpl.GetNetManager(), mServer,
this, 0, theReadIfOverloadedFlag, mImpl.GetMaxReadAhead(),
mImpl.GetHeartbeatInterval() * 3 / 2, mConnectionPtr);
if (! theConnPtr || ! theConnPtr->IsGood()) {
return;
}
if (! Authenticate()) {
StartSend();
}
}
bool Authenticate()
{
if (! mConnectionPtr || ! mAuthContext.IsEnabled()) {
return false;
}
if (mAuthenticateOpPtr) {
panic("log transmitter: "
"invalid authenticate invocation: auth is in flight");
return true;
}
mConnectionPtr->SetMaxReadAhead(mImpl.GetMaxReadAhead());
mAuthenticateOpPtr = new MetaAuthenticate();
mAuthenticateOpPtr->opSeqno = GetNextSeq();
mAuthenticateOpPtr->shortRpcFormatFlag = true;
string theErrMsg;
const int theErr = mAuthContext.Request(
mImpl.GetAuthType(),
mAuthenticateOpPtr->sendAuthType,
mAuthenticateOpPtr->sendContentPtr,
mAuthenticateOpPtr->sendContentLen,
mAuthRequestCtx,
&theErrMsg
);
if (theErr) {
KFS_LOG_STREAM_ERROR <<
mServer << ": "
"authentication request failure: " <<
theErrMsg <<
KFS_LOG_EOM;
MetaRequest::Release(mAuthenticateOpPtr);
mAuthenticateOpPtr = 0;
Error(theErrMsg.c_str());
return true;
}
KFS_LOG_STREAM_DEBUG <<
mServer << ": "
"starting: " <<
mAuthenticateOpPtr->Show() <<
KFS_LOG_EOM;
Request(*mAuthenticateOpPtr);
return true;
}
void HandleRead()
{
IOBuffer& theBuf = mConnectionPtr->GetInBuffer();
if (mAuthenticateOpPtr && 0 < mAuthenticateOpPtr->contentLength) {
HandleAuthResponse(theBuf);
if (mAuthenticateOpPtr) {
return;
}
}
bool theMsgAvailableFlag;
int theMsgLen = 0;
while ((theMsgAvailableFlag = IsMsgAvail(&theBuf, &theMsgLen))) {
const int theRet = HandleMsg(theBuf, theMsgLen);
if (theRet < 0) {
theBuf.Clear();
Error(mAuthenticateOpPtr ?
(mAuthenticateOpPtr->statusMsg.empty() ?
"invalid authenticate message" :
mAuthenticateOpPtr->statusMsg.c_str()) :
"request parse error"
);
return;
}
if (0 < theRet || ! mConnectionPtr) {
return; // Need more data, or down
}
theMsgLen = 0;
}
if (! mAuthenticateOpPtr &&
MAX_RPC_HEADER_LEN < theBuf.BytesConsumable()) {
Error("header size exceeds max allowed");
}
}
void HandleAuthResponse(
IOBuffer& inBuffer)
{
if (! mAuthenticateOpPtr || ! mConnectionPtr) {
panic("log transmitter: "
"handle auth response: invalid invocation");
MetaRequest::Release(mAuthenticateOpPtr);
mAuthenticateOpPtr = 0;
Error();
return;
}
if (! mAuthenticateOpPtr->contentBuf &&
0 < mAuthenticateOpPtr->contentLength) {
mAuthenticateOpPtr->contentBuf =
new char [mAuthenticateOpPtr->contentLength];
}
const int theRem = mAuthenticateOpPtr->Read(inBuffer);
if (0 < theRem) {
// Request one byte more to detect extaneous data.
mConnectionPtr->SetMaxReadAhead(theRem + 1);
return;
}
if (! inBuffer.IsEmpty()) {
KFS_LOG_STREAM_ERROR <<
mServer << ": "
"authentication protocol failure:" <<
" " << inBuffer.BytesConsumable() <<
" bytes past authentication response" <<
" filter: " <<
reinterpret_cast<const void*>(mConnectionPtr->GetFilter()) <<
" cmd: " << mAuthenticateOpPtr->Show() <<
KFS_LOG_EOM;
if (! mAuthenticateOpPtr->statusMsg.empty()) {
mAuthenticateOpPtr->statusMsg += "; ";
}
mAuthenticateOpPtr->statusMsg += "invalid extraneous data received";
mAuthenticateOpPtr->status = -EINVAL;
} else if (mAuthenticateOpPtr->status == 0) {
if (mConnectionPtr->GetFilter()) {
// Shutdown the current filter.
mConnectionPtr->Shutdown();
return;
}
mAuthenticateOpPtr->status = mAuthContext.Response(
mAuthenticateOpPtr->authType,
mAuthenticateOpPtr->useSslFlag,
mAuthenticateOpPtr->contentBuf,
mAuthenticateOpPtr->contentLength,
*mConnectionPtr,
mAuthRequestCtx,
&mAuthenticateOpPtr->statusMsg
);
}
const string theErrMsg = mAuthenticateOpPtr->statusMsg;
const bool theOkFlag = mAuthenticateOpPtr->status == 0;
KFS_LOG_STREAM(theOkFlag ?
MsgLogger::kLogLevelDEBUG : MsgLogger::kLogLevelERROR) <<
mServer << ":"
" finished: " << mAuthenticateOpPtr->Show() <<
" filter: " <<
reinterpret_cast<const void*>(mConnectionPtr->GetFilter()) <<
KFS_LOG_EOM;
MetaRequest::Release(mAuthenticateOpPtr);
mAuthenticateOpPtr = 0;
if (! theOkFlag) {
Error(theErrMsg.c_str());
return;
}
StartSend();
}
void StartSend()
{
if (! mConnectionPtr) {
return;
}
if (mAuthenticateOpPtr) {
panic("log transmitter: "
"invalid start send invocation: "
"authentication is in progress");
return;
}
if (mVrOpPtr) {
mSendHelloFlag = false;
mVrOpSeq = GetNextSeq();
mVrOpPtr->opSeqno = mVrOpSeq;
Request(*mVrOpPtr);
return;
}
mRecursionCount++;
SendHello();
if (mPendingSend.IsEmpty()) {
SendHeartbeat();
} else {
mConnectionPtr->GetOutBuffer().Copy(
&mPendingSend, mPendingSend.BytesConsumable());
}
mRecursionCount--;
if (mRecursionCount <= 0) {
mConnectionPtr->StartFlush();
}
}
bool HandleSslShutdown()
{
if (mAuthenticateOpPtr &&
mConnectionPtr &&
mConnectionPtr->IsGood() &&
! mConnectionPtr->GetFilter()) {
HandleAuthResponse(mConnectionPtr->GetInBuffer());
return (!! mConnectionPtr);
}
return false;
}
void SendHello()
{
if (! mSendHelloFlag ||
0 <= mMetaVrHello.opSeqno ||
mVrOpPtr ||
mAuthenticateOpPtr) {
return;
}
mSendHelloFlag = false;
mMetaVrHello.shortRpcFormatFlag = true;
if (mImpl.Init(mMetaVrHello, GetPeerLocation())) {
mMetaVrHello.opSeqno = GetNextSeq();
Request(mMetaVrHello);
}
}
bool SendHeartbeat()
{
if ((mActiveFlag &&
mAckBlockSeq.IsValid() &&
mAckBlockSeq < mLastSentBlockEndSeq) ||
mVrOpPtr ||
mAuthenticateOpPtr) {
return false;
}
if (! mBlocksQueue.empty()) {
if (mHeartbeatSendTimeoutCount + 1 <
Impl::kHeartbeatsPerTimeoutInterval) {
return false;
}
ResetPending();
}
if (! mLastSentBlockEndSeq.IsValid()) {
mLastSentBlockEndSeq = mImpl.GetLastLogSeq();
}
const bool kHeartbeatFlag = true;
SendBlockSelf(
mLastSentBlockEndSeq.IsValid() ?
mLastSentBlockEndSeq : MetaVrLogSeq(0, 0, 0),
0, "", 0, kKfsNullChecksum, 0, kHeartbeatFlag);
return true;
}
int HandleMsg(
IOBuffer& inBuffer,
int inHeaderLen)
{
IOBuffer::BufPos theLen = inHeaderLen;
const char* const theHeaderPtr = inBuffer.CopyOutOrGetBufPtr(
mImpl.GetParseBufferPtr(), theLen);
if (theLen != inHeaderLen) {
panic("handle msg: invalid header length");
Error("internal error: invalid header length");
return -1;
}
if (2 <= inHeaderLen &&
(theHeaderPtr[0] & 0xFF) == 'A' &&
(theHeaderPtr[1] & 0xFF) <= ' ') {
return HandleAck(theHeaderPtr, inHeaderLen, inBuffer);
}
if (3 <= inHeaderLen &&
(theHeaderPtr[0] & 0xFF) == 'O' &&
(theHeaderPtr[1] & 0xFF) == 'K' &&
(theHeaderPtr[2] & 0xFF) <= ' ') {
return HandleReply(theHeaderPtr, inHeaderLen, inBuffer);
}
return HanldeRequest(theHeaderPtr, inHeaderLen, inBuffer);
}
void AdvancePendingQueue()
{
if (mLastSentBlockEndSeq <= mAckBlockSeq) {
if (! mBlocksQueue.empty()) {
const BlocksQueueEntry& theBack = mBlocksQueue.back();
if (theBack.mSeq.IsValid() &&
theBack.mSeq != mLastSentBlockEndSeq) {
panic("log transmitter: invalid pending send queue");
}
const int64_t theNow = mImpl.GetNetManager().NowUsec();
for (BlocksQueue::const_iterator theIt = mBlocksQueue.begin();
mBlocksQueue.end() != theIt;
++theIt) {
if (0 < theIt->mSeqLength) {
mCtrs.mResponseTimeUsec += theNow - theIt->mStartTime;
mCtrs.mResponseSeqLength += theIt->mSeqLength;
mCtrs.mPendingBlockSeqLength -= theIt->mSeqLength;
}
}
mBlocksQueue.clear();
mPendingSend.Clear();
mCompactBlockCount = 0;
mCtrs.mPendingBlockBytes = 0;
}
return;
}
const int64_t theNow = mImpl.GetNetManager().NowUsec();
while (! mBlocksQueue.empty()) {
const BlocksQueueEntry& theFront = mBlocksQueue.front();
if (mAckBlockSeq < theFront.mSeq) {
break;
}
if (mPendingSend.Consume(theFront.mLength) != theFront.mLength) {
panic("log transmitter: "
"invalid pending send buffer or queue");
}
if (0 < theFront.mSeqLength) {
mCtrs.mResponseTimeUsec += theNow - theFront.mStartTime;
mCtrs.mResponseSeqLength += theFront.mSeqLength;
mCtrs.mPendingBlockSeqLength -= theFront.mSeqLength;
}
mBlocksQueue.pop_front();
if (0 < mCompactBlockCount) {
mCompactBlockCount--;
}
}
if (mBlocksQueue.empty() != mPendingSend.IsEmpty()) {
panic("log transmitter: invalid pending send queue");
}
mCtrs.mPendingBlockBytes = mPendingSend.BytesConsumable();
}
int HandleAck(
const char* inHeaderPtr,
int inHeaderLen,
IOBuffer& inBuffer)
{
const NodeId thePrevPrimaryId = mPrimaryNodeId;
const MetaVrLogSeq thePrevAckSeq = mAckBlockSeq;
const char* thePtr = inHeaderPtr + 2;
const char* const theEndPtr = thePtr + inHeaderLen;
if (! mAckBlockSeq.Parse<HexIntParser>(
thePtr, theEndPtr - thePtr) ||
! HexIntParser::Parse(
thePtr, theEndPtr - thePtr, mAckBlockFlags) ||
! HexIntParser::Parse(
thePtr, theEndPtr - thePtr, mPrimaryNodeId)) {
MsgLogLines(MsgLogger::kLogLevelERROR,
"malformed ack: ", inBuffer, inHeaderLen);
Error("malformed ack");
return -1;
}
if (! mAckBlockSeq.IsValid()) {
KFS_LOG_STREAM_ERROR <<
mServer << ": "
"invalid ack block sequence: " << mAckBlockSeq <<
" last sent: " << mLastSentBlockEndSeq <<
" pending: " <<
mPendingSend.BytesConsumable() <<
" / " << mBlocksQueue.size() <<
KFS_LOG_EOM;
Error("invalid ack sequence");
return -1;
}
const bool theHasIdFlag = mAckBlockFlags &
(uint64_t(1) << kLogBlockAckHasServerIdBit);
NodeId theId = -1;
if (theHasIdFlag &&
(! HexIntParser::Parse(thePtr, theEndPtr - thePtr, theId) ||
theId < 0)) {
KFS_LOG_STREAM_ERROR <<
mServer << ": "
"missing or invalid server id: " << theId <<
" last sent: " << mLastSentBlockEndSeq <<
KFS_LOG_EOM;
Error("missing or invalid server id");
return -1;
}
while (thePtr < theEndPtr && (*thePtr & 0xFF) <= ' ') {
thePtr++;
}
const char* const theChksumEndPtr = thePtr;
Checksum theChecksum = 0;
if (! HexIntParser::Parse(
thePtr, theEndPtr - thePtr, theChecksum)) {
KFS_LOG_STREAM_ERROR <<
mServer << ": "
"invalid ack checksum: " << theChecksum <<
" last sent: " << mLastSentBlockEndSeq <<
KFS_LOG_EOM;
Error("missing or invalid server id");
return -1;
}
const Checksum theComputedChksum = ComputeBlockChecksum(
inHeaderPtr, theChksumEndPtr - inHeaderPtr);
if (theComputedChksum != theChecksum) {
KFS_LOG_STREAM_ERROR <<
mServer << ": "
"ack checksum mismatch:"
" expected: " << theChecksum <<
" computed: " << theComputedChksum <<
KFS_LOG_EOM;
Error("ack checksum mismatch");
return -1;
}
if (! mReceivedIdFlag) {
mReceivedId = theId;
if (theHasIdFlag) {
mReceivedIdFlag = true;
if (! mActiveFlag && mId != theId) {
KFS_LOG_STREAM_NOTICE <<
mServer << ": inactive node ack id mismatch:" <<
" expected: " << mId <<
" actual:: " << theId <<
KFS_LOG_EOM;
}
} else {
const char* const theMsgPtr = "first ack wihout node id";
KFS_LOG_STREAM_ERROR <<
mServer << ": " << theMsgPtr <<
KFS_LOG_EOM;
Error(theMsgPtr);
return -1;
}
}
if (theHasIdFlag && mId != theId) {
KFS_LOG_STREAM_ERROR <<
mServer << ": "
"ack node id mismatch:"
" expected: " << mId <<
" actual:: " << theId <<
KFS_LOG_EOM;
Error("ack node id mismatch");
return -1;
}
KFS_LOG_STREAM_DEBUG <<
mServer << ":"
" log recv id: " << theId <<
" / " << mId <<
" primary: " << mPrimaryNodeId <<
" ack: " << thePrevAckSeq <<
" => " << mAckBlockSeq <<
" sent: " << mLastSentBlockEndSeq <<
" pending:"
" blocks: " << mBlocksQueue.size() <<
" bytes: " << mPendingSend.BytesConsumable() <<
KFS_LOG_EOM;
mLastAckReceivedTime = mImpl.GetNetManager().Now();
AdvancePendingQueue();
inBuffer.Consume(inHeaderLen);
UpdateAck(thePrevAckSeq, thePrevPrimaryId);
if (mConnectionPtr) {
if (! mAuthenticateOpPtr &&
(mAckBlockFlags &
(uint64_t(1) << kLogBlockAckReAuthFlagBit)) != 0) {
KFS_LOG_STREAM_DEBUG <<
mServer << ": "
"re-authentication requested" <<
KFS_LOG_EOM;
Authenticate();
} else if (mSendHelloFlag && mBlocksQueue.empty()) {
SendHello();
}
}
return (mConnectionPtr ? 0 : -1);
}
const ServerLocation& GetPeerLocation()
{
if (! mPeer.IsValid() && mConnectionPtr &&
0 != mConnectionPtr->GetPeerLocation(mPeer)) {
mPeer.port = -1;
mPeer.hostname.clear();
}
return mPeer;
}
int HandleReply(
const char* inHeaderPtr,
int inHeaderLen,
IOBuffer& inBuffer)
{
mReplyProps.clear();
mReplyProps.setIntBase(16);
if (mReplyProps.loadProperties(
inHeaderPtr, inHeaderLen, (char)':') != 0) {
MsgLogLines(MsgLogger::kLogLevelERROR,
"malformed reply: ", inBuffer, inHeaderLen);
Error("malformed reply");
return -1;
}
seq_t const theSeq = mReplyProps.getValue("c", seq_t(-1));
if (mAuthenticateOpPtr && theSeq == mAuthenticateOpPtr->opSeqno) {
inBuffer.Consume(inHeaderLen);
mAuthenticateOpPtr->contentLength =
mReplyProps.getValue("l", 0);
mAuthenticateOpPtr->authType =
mReplyProps.getValue("A", int(kAuthenticationTypeUndef));
mAuthenticateOpPtr->useSslFlag =
mReplyProps.getValue("US", 0) != 0;
int64_t theCurrentTime =
mReplyProps.getValue("CT", int64_t(-1));
mAuthenticateOpPtr->sessionExpirationTime =
mReplyProps.getValue("ET", int64_t(-1));
KFS_LOG_STREAM_DEBUG <<
mServer << ": "
"authentication reply:"
" cur time: " << theCurrentTime <<
" delta: " << (TimeNow() - theCurrentTime) <<
" expires in: " <<
(mAuthenticateOpPtr->sessionExpirationTime -
theCurrentTime) <<
KFS_LOG_EOM;
HandleAuthResponse(inBuffer);
} else if (0 <= mMetaVrHello.opSeqno &&
theSeq == mMetaVrHello.opSeqno) {
inBuffer.Consume(inHeaderLen);
KFS_LOG_STREAM_DEBUG <<
mServer << ": "
"-seq: " << theSeq <<
" status: " << mMetaVrHello.status <<
" " << mMetaVrHello.statusMsg <<
" " << mMetaVrHello.Show() <<
KFS_LOG_EOM;
mMetaVrHello.opSeqno = -1;
mMetaVrHello.HandleResponse(theSeq, mReplyProps, mId,
GetPeerLocation());
if (0 != mMetaVrHello.status) {
Error(mMetaVrHello.statusMsg.empty() ?
"VR hello error" : mMetaVrHello.statusMsg.c_str());
mReplyProps.clear();
return -1;
}
} else if (mVrOpPtr && 0 <= mVrOpSeq && theSeq == mVrOpSeq) {
inBuffer.Consume(inHeaderLen);
VrUpdate(theSeq);
} else {
KFS_LOG_STREAM_ERROR <<
mServer << ": "
"unexpected reply" <<
" auth : " << MetaRequest::ShowReq(mAuthenticateOpPtr) <<
"vr:"
" seq: " << mVrOpSeq <<
" " << MetaRequest::ShowReq(mVrOpPtr) <<
" hello: " << MetaRequest::ShowReq(
mMetaVrHello.opSeqno < 0 ? 0 : &mMetaVrHello) <<
KFS_LOG_EOM;
MsgLogLines(MsgLogger::kLogLevelERROR,
"unexpected reply: ", inBuffer, inHeaderLen);
Error("unexpected reply");
return -1;
}
mReplyProps.clear();
return (mConnectionPtr ? 0 : -1);
}
int HanldeRequest(
const char* inHeaderPtr,
int inHeaderLen,
IOBuffer& inBuffer)
{
// No request handling for now.
MsgLogLines(MsgLogger::kLogLevelERROR,
"invalid response: ", inBuffer, inHeaderLen);
Error("invalid response");
return -1;
}
void HandleCmdDone(
MetaRequest& inReq)
{
KFS_LOG_STREAM_FATAL <<
mServer << ": "
"unexpected invocation: " << inReq.Show() <<
KFS_LOG_EOM;
panic("LogTransmitter::Impl::Transmitter::HandleCmdDone "
"unexpected invocation");
}
seq_t GetNextSeq()
{ return ++mNextSeq; }
void Request(
MetaRequest& inReq)
{
// For now authentication or Vr ops.
if (&inReq != mAuthenticateOpPtr && &inReq != mVrOpPtr &&
&inReq != &mMetaVrHello) {
panic("LogTransmitter::Impl::Transmitter: invalid request");
return;
}
if (! mConnectionPtr) {
return;
}
KFS_LOG_STREAM_DEBUG <<
mServer << ":"
" id: " << mId <<
" +seq: " << inReq.opSeqno <<
" " << inReq.Show() <<
KFS_LOG_EOM;
IOBuffer& theBuf = mConnectionPtr->GetOutBuffer();
ReqOstream theStream(mOstream.Set(theBuf));
if (&inReq == mVrOpPtr) {
mVrOpPtr->Request(theStream);
} else if (&inReq == &mMetaVrHello) {
mMetaVrHello.Request(theStream);
} else {
mAuthenticateOpPtr->Request(theStream);
}
mOstream.Reset();
if (mRecursionCount <= 0) {
mConnectionPtr->StartFlush();
}
}
void Error(
const char* inMsgPtr = 0,
MsgLogger::LogLevel inLogLevel = MsgLogger::kLogLevelERROR)
{
if (! mConnectionPtr) {
return;
}
KFS_LOG_STREAM(inLogLevel) <<
mServer << ": " <<
(inMsgPtr ? inMsgPtr : "network error") <<
" socket error: " << mConnectionPtr->GetErrorMsg() <<
" vr:"
" seq: " << mVrOpSeq <<
" op: " << MetaRequest::ShowReq(mVrOpPtr) <<
" hello seq: " << mMetaVrHello.opSeqno <<
" pending: "
" blocks: " << mBlocksQueue.size() <<
" bytes: " << mPendingSend.BytesConsumable() <<
KFS_LOG_EOM;
mMetaVrHello.opSeqno = -1;
const NodeId thePrevPrimaryId = mPrimaryNodeId;
mPrimaryNodeId = -1;
mConnectionPtr->Close();
mConnectionPtr.reset();
MetaRequest::Release(mAuthenticateOpPtr);
mAuthenticateOpPtr = 0;
AdvancePendingQueue();
const MetaVrLogSeq thePrevAck = mAckBlockSeq;
mAckBlockSeq = MetaVrLogSeq();
VrDisconnect();
UpdateAck(thePrevAck, thePrevPrimaryId);
if (mSleepingFlag) {
return;
}
mSleepingFlag = true;
SetTimeoutInterval(mImpl.GetRetryInterval());
mImpl.GetNetManager().RegisterTimeoutHandler(this);
}
void VrUpdate(
seq_t inSeq)
{
if (! mVrOpPtr) {
return;
}
MetaVrRequest& theReq = *mVrOpPtr;
if (inSeq != mVrOpSeq) {
mReplyProps.clear();
}
mVrOpSeq = -1;
mVrOpPtr = 0;
theReq.HandleResponse(inSeq, mReplyProps, mId, GetPeerLocation());
MetaRequest::Release(&theReq);
}
void VrDisconnect()
{
if (0 <= mMetaVrHello.opSeqno) {
mMetaVrHello.opSeqno = -1;
mReplyProps.clear();
mMetaVrHello.HandleResponse(mMetaVrHello.opSeqno, mReplyProps, mId,
GetPeerLocation());
}
VrUpdate(-1);
}
void MsgLogLines(
MsgLogger::LogLevel inLogLevel,
const char* inPrefixPtr,
IOBuffer& inBuffer,
int inBufLen,
int inMaxLines = 64)
{
const char* const thePrefixPtr = inPrefixPtr ? inPrefixPtr : "";
istream& theStream = mIstream.Set(inBuffer, inBufLen);
int theRemCnt = inMaxLines;
string theLine;
while (--theRemCnt >= 0 && getline(theStream, theLine)) {
string::iterator theIt = theLine.end();
if (theIt != theLine.begin() && *--theIt <= ' ') {
theLine.erase(theIt);
}
KFS_LOG_STREAM(inLogLevel) <<
thePrefixPtr << theLine <<
KFS_LOG_EOM;
}
mIstream.Reset();
}
time_t TimeNow()
{ return mImpl.GetNetManager().Now(); }
private:
Transmitter(
const Transmitter& inTransmitter);
Transmitter& operator=(
const Transmitter& inTransmitter);
};
int
LogTransmitter::Impl::SetParameters(
const char* inParamPrefixPtr,
const Properties& inParameters)
{
Properties::String theParamName;
if (inParamPrefixPtr) {
theParamName.Append(inParamPrefixPtr);
}
const size_t thePrefixLen = theParamName.GetSize();
mRetryInterval = inParameters.getValue(
theParamName.Truncate(thePrefixLen).Append(
"retryInterval"), mRetryInterval);
mMaxReadAhead = max(512, min(64 << 20, inParameters.getValue(
theParamName.Truncate(thePrefixLen).Append(
"maxReadAhead"), mMaxReadAhead)));
mMaxPending = inParameters.getValue(
theParamName.Truncate(thePrefixLen).Append(
"maxPending"), mMaxPending);
mCompactionInterval = inParameters.getValue(
theParamName.Truncate(thePrefixLen).Append(
"compactionInterval"), mCompactionInterval);
mAuthTypeStr = inParameters.getValue(
theParamName.Truncate(thePrefixLen).Append(
"authType"), mAuthTypeStr);
const char* thePtr = mAuthTypeStr.c_str();
mAuthType = 0;
while (*thePtr != 0) {
while (*thePtr != 0 && (*thePtr & 0xFF) <= ' ') {
thePtr++;
}
const char* theStartPtr = thePtr;
while (' ' < (*thePtr & 0xFF)) {
thePtr++;
}
const size_t theLen = thePtr - theStartPtr;
if (theLen == 3) {
if (memcmp("Krb5", theStartPtr, theLen) == 0) {
mAuthType |= kAuthenticationTypeKrb5;
} else if (memcmp("PSK", theStartPtr, theLen) == 0) {
mAuthType |= kAuthenticationTypeKrb5;
}
} else if (theLen == 4 && memcmp("X509", theStartPtr, theLen) == 0) {
mAuthType |= kAuthenticationTypeX509;
}
}
mTransmitterAuthParamsPrefix =
theParamName.Truncate(thePrefixLen).Append("auth.").GetStr();
inParameters.copyWithPrefix(
mTransmitterAuthParamsPrefix, mTransmitterAuthParams);
return StartTransmitters(0);
}
int
LogTransmitter::Impl::StartTransmitters(
ClientAuthContext* inAuthCtxPtr)
{
if (List::IsEmpty(mTransmittersPtr)) {
return 0;
}
const bool theStartFlag = ! mSuspendedFlag &&
mMetaVrSMPtr && mMetaVrSMPtr->IsPrimary();
const char* const theAuthPrefixPtr = mTransmitterAuthParamsPrefix.c_str();
ClientAuthContext* theAuthCtxPtr = inAuthCtxPtr ? inAuthCtxPtr :
&(List::Front(mTransmittersPtr)->GetAuthCtx());
int theRet = 0;
List::Iterator theIt(mTransmittersPtr);
Transmitter* theTPtr;
while ((theTPtr = theIt.Next())) {
string theErrMsg;
const int theErr = theTPtr->SetParameters(
theAuthCtxPtr, theAuthPrefixPtr, mTransmitterAuthParams, theErrMsg);
if (0 != theErr) {
if (theErrMsg.empty()) {
theErrMsg = QCUtils::SysError(theErr,
"setting authentication parameters error");
}
KFS_LOG_STREAM_ERROR <<
theTPtr->GetServerLocation() << ": " <<
theErrMsg <<
KFS_LOG_EOM;
if (0 == theRet) {
theRet = theErr;
}
} else if (theStartFlag) {
theTPtr->Start();
}
if (! theAuthCtxPtr) {
theAuthCtxPtr = &theTPtr->GetAuthCtx();
}
}
return theRet;
}
void
LogTransmitter::Impl::Shutdown()
{
Transmitter* thePtr;
while ((thePtr = List::PopBack(mTransmittersPtr))) {
delete thePtr;
}
}
void
LogTransmitter::Impl::Deleted(
Transmitter& inTransmitter)
{
if (List::IsInList(mTransmittersPtr, inTransmitter)) {
panic("log transmitter: invalid transmitter delete attempt");
}
}
void
LogTransmitter::Impl::Insert(
LogTransmitter::Impl::Transmitter& inTransmitter)
{
Transmitter* const theHeadPtr = List::Front(mTransmittersPtr);
if (! theHeadPtr) {
List::PushFront(mTransmittersPtr, inTransmitter);
return;
}
// Insertion sort.
const NodeId theId = inTransmitter.GetId();
Transmitter* thePtr = theHeadPtr;
while (theId < thePtr->GetId()) {
if (theHeadPtr == (thePtr = &List::GetNext(*thePtr))) {
List::PushBack(mTransmittersPtr, inTransmitter);
return;
}
}
if (thePtr == theHeadPtr) {
List::PushFront(mTransmittersPtr, inTransmitter);
} else {
QCDLListOp<Transmitter>::Insert(inTransmitter, List::GetPrev(*thePtr));
}
}
void
LogTransmitter::Impl::Acked(
const MetaVrLogSeq& inPrevAck,
LogTransmitter::Impl::NodeId inPrimaryNodeId,
LogTransmitter::Impl::Transmitter& inTransmitter)
{
if (! inTransmitter.IsActive() || List::IsEmpty(mTransmittersPtr)) {
return;
}
const NodeId thePrimaryId = inTransmitter.GetPrimaryNodeId();
if (inPrimaryNodeId != thePrimaryId &&
0 <= thePrimaryId &&
mMetaVrSMPtr &&
! mMetaVrSMPtr->ValidateAckPrimaryId(
inTransmitter.GetId(), thePrimaryId)) {
return;
}
const MetaVrLogSeq theAck = inTransmitter.GetAck();
const NodeId theCurPrimaryId = mMetaVrSMPtr ?
mMetaVrSMPtr->GetPrimaryNodeId(theAck) : NodeId(-1);
if (mCommitted < theAck && 0 <= theCurPrimaryId) {
NodeId thePrevId = -1;
int thePending = 0;
int theCurPending = 0;
int theAckAdvCnt = 0;
MetaVrLogSeq theCommitted = theAck;
MetaVrLogSeq theCurMax = mCommitted;
List::Iterator theIt(mTransmittersPtr);
const Transmitter* thePtr;
while ((thePtr = theIt.Next())) {
if (! thePtr->IsActive()) {
continue;
}
const MetaVrLogSeq theCurAck = thePtr->GetAck();
if (! theCurAck.IsValid()) {
continue;
}
const NodeId theId = thePtr->GetId();
if (theCurPrimaryId != thePtr->GetPrimaryNodeId()) {
continue;
}
if (theId == thePrevId) {
theCurMax = max(theCurMax, theCurAck);
theCurPending = min(
theCurPending, thePtr->GetPendingSendByteCount());
} else {
if (mCommitted < theCurMax) {
theCommitted = min(theCommitted, theCurMax);
thePending = max(thePending, theCurPending);
theAckAdvCnt++;
}
theCurPending = thePtr->GetPendingSendByteCount();
theCurMax = theCurAck;
thePrevId = theId;
}
}
if (mCommitted < theCurMax) {
theCommitted = min(theCommitted, theCurMax);
thePending = max(thePending, theCurPending);
theAckAdvCnt++;
}
if (mMinAckToCommit <= theAckAdvCnt) {
mCommitted = theCommitted;
mPendingAckByteCount = thePending;
mCommitObserver.Notify(mCommitted, mPendingAckByteCount);
}
}
if (inPrevAck.IsValid() != theAck.IsValid() ||
theCurPrimaryId < 0 ||
inPrimaryNodeId != thePrimaryId ||
(! IsUp() && 0 <= theCurPrimaryId)) {
Update(inTransmitter);
}
}
int
LogTransmitter::Impl::TransmitBlock(
const MetaVrLogSeq& inBlockEndSeq,
int inBlockSeqLen,
const char* inBlockPtr,
size_t inBlockLen,
LogTransmitter::Impl::Checksum inChecksum,
size_t inChecksumStartPos)
{
if (inBlockSeqLen < 0 || (inBlockLen <= 0 && 0 < inBlockSeqLen)) {
return -EINVAL;
}
if (inBlockLen <= 0 || List::IsEmpty(mTransmittersPtr)) {
return 0;
}
mSendingFlag = true;
int theCnt = 0;
Transmitter* thePtr;
if (List::Front(mTransmittersPtr) == List::Back(mTransmittersPtr)) {
thePtr = List::Front(mTransmittersPtr);
const NodeId theId = thePtr->GetId();
if (thePtr->SendBlock(
inBlockEndSeq, inBlockSeqLen,
inBlockPtr, inBlockLen, inChecksum, inChecksumStartPos) &&
0 <= theId && thePtr->IsActive()) {
theCnt++;
}
} else {
IOBuffer theBuffer;
WriteBlock(theBuffer, inBlockEndSeq, inBlockSeqLen,
inBlockPtr, inBlockLen, inChecksum, inChecksumStartPos);
NodeId thePrevId = -1;
List::Iterator theIt(mTransmittersPtr);
while ((thePtr = theIt.Next())) {
const NodeId theId = thePtr->GetId();
if (thePtr->SendBlock(
inBlockEndSeq, inBlockSeqLen,
theBuffer, theBuffer.BytesConsumable())) {
if (0 <= theId && theId != thePrevId && thePtr->IsActive()) {
theCnt++;
}
thePrevId = theId;
}
}
}
EndOfTransmit();
return (theCnt < mMinAckToCommit ? -EIO : 0);
}
void
LogTransmitter::Impl::NotifyAck(
LogTransmitter::NodeId inNodeId,
const MetaVrLogSeq& inAckSeq,
NodeId inPrimaryNodeId)
{
List::Iterator theIt(mTransmittersPtr);
Transmitter* thePtr;
while ((thePtr = theIt.Next())) {
if (thePtr->GetId() == inNodeId) {
thePtr->NotifyAck(inAckSeq, inPrimaryNodeId);
}
}
if (mMinAckToCommit <= 0 && (inNodeId < 0 ||
inNodeId == inPrimaryNodeId) && mCommitted < inAckSeq) {
mCommitted = inAckSeq;
mPendingAckByteCount = 0;
mCommitObserver.Notify(mCommitted, mPendingAckByteCount);
}
}
void
LogTransmitter::Impl::EndOfTransmit()
{
if (! mSendingFlag) {
panic("log transmitter: invalid end of transmit invocation");
}
mSendingFlag = false;
if (mPendingUpdateFlag) {
Update();
}
}
void
LogTransmitter::Impl::Update(
LogTransmitter::Impl::Transmitter& /* inTransmitter */)
{
Update();
}
void
LogTransmitter::Impl::Update()
{
if (mSendingFlag) {
mPendingUpdateFlag = true;
return;
}
mPendingUpdateFlag = false;
int theIdCnt = 0;
int theUpCnt = 0;
int theIdUpCnt = 0;
int theTotalCnt = 0;
int thePrevAllId = -1;
NodeId thePrevId = -1;
MetaVrLogSeq theMinAck;
MetaVrLogSeq theMaxAck;
List::Iterator theIt(mTransmittersPtr);
Transmitter* thePtr;
const NodeId theCurPrimaryId = mMetaVrSMPtr ?
mMetaVrSMPtr->GetPrimaryNodeId(mCommitted) : NodeId(-1);
if (0 <= theCurPrimaryId) {
while ((thePtr = theIt.Next())) {
const NodeId theId = thePtr->GetId();
const MetaVrLogSeq theAck = thePtr->GetAck();
if (0 <= theId && theId != thePrevAllId) {
theIdCnt++;
thePrevAllId = theId;
}
if (thePtr->IsActive() && theAck.IsValid() &&
theCurPrimaryId == thePtr->GetPrimaryNodeId()) {
theUpCnt++;
if (theId != thePrevId) {
theIdUpCnt++;
}
if (theMinAck.IsValid()) {
theMinAck = min(theMinAck, theAck);
theMaxAck = max(theMaxAck, theAck);
} else {
theMinAck = theAck;
theMaxAck = theAck;
}
thePrevId = theId;
}
theTotalCnt++;
}
}
const bool theUpFlag = mMinAckToCommit <= theIdUpCnt;
const bool theNotifyFlag = theUpFlag != mUpFlag;
KFS_LOG_STREAM(theNotifyFlag ?
MsgLogger::kLogLevelINFO : MsgLogger::kLogLevelDEBUG) <<
"update:"
" primary: " << theCurPrimaryId <<
" tranmitters: " << theTotalCnt <<
" up: " << theUpCnt <<
" ids up: " << theIdUpCnt <<
" quorum: " << mMinAckToCommit <<
" committed: " << mCommitted <<
" ack: [" << theMinAck <<
"," << theMaxAck << "]"
" ids: " << mIdsCount <<
" => " << theIdCnt <<
" up: " << mUpFlag <<
" => " << theUpFlag <<
KFS_LOG_EOM;
mIdsCount = theIdCnt;
mUpFlag = theUpFlag;
if (theNotifyFlag) {
mCommitObserver.Notify(mCommitted, mPendingAckByteCount);
}
}
void
LogTransmitter::Impl::GetStatus(
LogTransmitter::StatusReporter& inReporter)
{
List::Iterator theIt(mTransmittersPtr);
Transmitter* thePtr;
LogTransmitter::StatusReporter::Counters theCtrs;
while ((thePtr = theIt.Next())) {
thePtr->GetCounters(theCtrs);
if (! inReporter.Report(
thePtr->GetLocation(),
thePtr->GetId(),
thePtr->IsActive(),
thePtr->GetReceivedId(),
thePtr->GetPrimaryNodeId(),
thePtr->GetAck(),
mCommitted,
theCtrs)) {
break;
}
}
}
void
LogTransmitter::Impl::QueueVrRequest(
MetaVrRequest& inVrReq,
LogTransmitter::Impl::NodeId inNodeId)
{
inVrReq.shortRpcFormatFlag = true;
List::Iterator theIt(mTransmittersPtr);
Transmitter* thePtr;
while ((thePtr = theIt.Next())) {
if (inNodeId < 0 || thePtr->GetId() == inNodeId) {
thePtr->QueueVrRequest(inVrReq);
if (0 <= inNodeId) {
break;
}
}
}
}
int
LogTransmitter::Impl::Update(
MetaVrSM& inMetaVrSM)
{
mMetaVrSMPtr = &inMetaVrSM;
const MetaVrLogSeq theLastLogSeq = inMetaVrSM.GetLastLogSeq();
const Config& theConfig = inMetaVrSM.GetConfig();
const Config::Nodes& theNodes = theConfig.GetNodes();
ClientAuthContext* const theAuthCtxPtr = List::IsEmpty(mTransmittersPtr) ?
0 : &(List::Front(mTransmittersPtr)->GetAuthCtx());
Transmitter* theTransmittersPtr[1];
theTransmittersPtr[0] = mTransmittersPtr[0];
mTransmittersPtr[0] = 0;
int theTransmittersCount = 0;
SetHeartbeatInterval(theConfig.GetPrimaryTimeout());
for (Config::Nodes::const_iterator theIt = theNodes.begin();
theNodes.end() != theIt;
++theIt) {
const Config::NodeId theId = theIt->first;
const Config::Node& theNode = theIt->second;
const Config::Locations& theLocations = theNode.GetLocations();
for (Config::Locations::const_iterator theIt = theLocations.begin();
theLocations.end() != theIt;
++theIt) {
const ServerLocation& theLocation = *theIt;
if (! theLocation.IsValid()) {
continue;
}
List::Iterator theTIt(theTransmittersPtr);
Transmitter* theTPtr;
while ((theTPtr = theTIt.Next())) {
if (theTPtr->GetId() == theId &&
theTPtr->GetLocation() == theLocation) {
List::Remove(theTransmittersPtr, *theTPtr);
break;
}
}
if (theTPtr) {
theTPtr->SetActive(
0 != (theNode.GetFlags() & Config::kFlagActive));
} else {
theTPtr = new Transmitter(*this, theLocation, theId,
0 != (theNode.GetFlags() & Config::kFlagActive),
theLastLogSeq);
}
theTransmittersCount++;
Insert(*theTPtr);
}
}
Transmitter* theTPtr;
while ((theTPtr = List::PopFront(theTransmittersPtr))) {
delete theTPtr;
}
mTransmittersCount = theTransmittersCount;
mNodeId = inMetaVrSM.GetNodeId();
mMinAckToCommit = inMetaVrSM.GetQuorum();
StartTransmitters(theAuthCtxPtr);
Update();
return mTransmittersCount;
}
void
LogTransmitter::Impl::Suspend(
bool inFlag)
{
if (inFlag == mSuspendedFlag) {
return;
}
mSuspendedFlag = inFlag;
const bool theStartFlag = ! mSuspendedFlag &&
mMetaVrSMPtr && mMetaVrSMPtr->IsPrimary();
List::Iterator theIt(mTransmittersPtr);
Transmitter* thePtr;
while ((thePtr = theIt.Next())) {
if (mSuspendedFlag) {
thePtr->Shutdown();
} else if (theStartFlag) {
thePtr->Start();
}
}
Update();
}
void
LogTransmitter::Impl::ScheduleHelloTransmit()
{
List::Iterator theIt(mTransmittersPtr);
Transmitter* thePtr;
while ((thePtr = theIt.Next())) {
thePtr->ScheduleHelloTransmit();
}
}
void
LogTransmitter::Impl::ScheduleHeartbeatTransmit()
{
List::Iterator theIt(mTransmittersPtr);
Transmitter* thePtr;
while ((thePtr = theIt.Next())) {
thePtr->ScheduleHeartbeatTransmit();
}
}
void
LogTransmitter::Impl::Timeout()
{
const int64_t theNowUsec = mNetManager.NowUsec();
if (theNowUsec < mNextTimerRunTimeUsec) {
return;
}
const int64_t kIntervalUsec = 1000 * 1000;
List::Iterator theIt(mTransmittersPtr);
Transmitter* thePtr;
while ((thePtr = theIt.Next())) {
thePtr->Timer(mNextTimerRunTimeUsec, theNowUsec, kIntervalUsec);
}
while (mNextTimerRunTimeUsec <= theNowUsec) {
mNextTimerRunTimeUsec += kIntervalUsec;
}
}
LogTransmitter::LogTransmitter(
NetManager& inNetManager,
LogTransmitter::CommitObserver& inCommitObserver)
: mImpl(*(new Impl(*this, inNetManager, inCommitObserver))),
mUpFlag(mImpl.GetUpFlag())
{}
LogTransmitter::~LogTransmitter()
{
delete &mImpl;
}
void
LogTransmitter::SetFileSystemId(
int64_t inFsId)
{
mImpl.SetFileSystemId(inFsId);
}
int
LogTransmitter::SetParameters(
const char* inParamPrefixPtr,
const Properties& inParameters)
{
return mImpl.SetParameters(inParamPrefixPtr, inParameters);
}
int
LogTransmitter::TransmitBlock(
const MetaVrLogSeq& inBlockEndSeq,
int inBlockSeqLen,
const char* inBlockPtr,
size_t inBlockLen,
uint32_t inChecksum,
size_t inChecksumStartPos)
{
return mImpl.TransmitBlock(inBlockEndSeq, inBlockSeqLen,
inBlockPtr, inBlockLen, inChecksum, inChecksumStartPos);
}
void
LogTransmitter::NotifyAck(
LogTransmitter::NodeId inNodeId,
const MetaVrLogSeq& inAckSeq,
NodeId inPrimaryNodeId)
{
mImpl.NotifyAck(inNodeId, inAckSeq, inPrimaryNodeId);
}
void
LogTransmitter::Suspend(
bool inFlag)
{
return mImpl.Suspend(inFlag);
}
void
LogTransmitter::QueueVrRequest(
MetaVrRequest& inVrReq,
LogTransmitter::NodeId inNodeId)
{
mImpl.QueueVrRequest(inVrReq, inNodeId);
}
int
LogTransmitter::Update(
MetaVrSM& inMetaVrSM)
{
return mImpl.Update(inMetaVrSM);
}
void
LogTransmitter::GetStatus(
LogTransmitter::StatusReporter& inReporter)
{
return mImpl.GetStatus(inReporter);
}
void
LogTransmitter::SetHeartbeatInterval(
int inPrimaryTimeoutSec)
{
mImpl.SetHeartbeatInterval(inPrimaryTimeoutSec);
mImpl.ScheduleHeartbeatTransmit();
}
int
LogTransmitter::GetChannelsCount() const
{
return mImpl.GetChannelsCount();
}
void
LogTransmitter::ScheduleHelloTransmit()
{
mImpl.ScheduleHelloTransmit();
}
void
LogTransmitter::Shutdown()
{
mImpl.Shutdown();
}
} // namespace KFS
| [
"movsiannikov@quantcast.com"
] | movsiannikov@quantcast.com |
d0b936be124bc6086383e57ff23b2c33290c7b4b | 908469f5311041a4831eb2f172633cad46c32224 | /cppPrimer/15/QueryText/main.cpp | 2a147175ab25af6c0a2b03aa6d700f76d51a54f5 | [] | no_license | SmileyJs/Learning | f90dc4ff2a7f5280b6a6c11ddd4aaf05ad9021d2 | 4cacee5e372e71ec2245d4701ea34e07b6d3daa2 | refs/heads/master | 2021-10-22T11:43:35.004887 | 2019-03-10T14:24:58 | 2019-03-10T14:24:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cpp | #include <fstream>
#include "TextQuery.h"
#include "QueryBase.h"
#include "Query.h"
#include "NotQuery.h"
#include "AndQuery.h"
#include "QueryHistory.h"
int
main(int argc, char const *argv[])
{
ifstream input("./text.txt");
if (!input) {
cout << "file input error!" << endl;
return -1;
}
TextQuery text(input);
Query q0 = Query("daddy"), q1 = Query("the"), q2 = Query("Daddy");
QueryHistory history;
history.addQuery(q0);
history.addQuery(q1);
history.addQuery(q2);
Query q = history[0] & history[1] | ~history[2];
cout << q << endl;
print(cout, q.eval(text));
print(cout, q.eval(text), 3, 7);
return 0;
} | [
"wangjieshuai1990@gmail.com"
] | wangjieshuai1990@gmail.com |
e87290b4e3d4e7d5bfcd892bef11823c76260e8a | 17a084ce7308487077f9b34ac494407ee500240e | /test/g2o_test.cpp | 706bea956b0c33cc5a22d79dfde0ca3ce4b39d26 | [] | no_license | wystephen/ArSLAMPlus | 2a93491f83c2e0d2cde72944de7d16ade0866cbd | 7f870002f0f9872e68673889cd1b5496263ecebf | refs/heads/master | 2021-01-09T05:42:57.058599 | 2017-02-12T05:37:59 | 2017-02-12T05:37:59 | 80,818,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,035 | cpp | //
// Created by steve on 17-2-3.
//
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*/
#include <iostream>
#include "g2o/core/sparse_optimizer.h"
#include "g2o/core/block_solver.h"
#include "g2o/core/optimization_algorithm_gauss_newton.h"
#include "g2o/core/optimization_algorithm_levenberg.h"
#include "g2o/solvers/csparse/linear_solver_csparse.h"
#include "g2o/core/factory.h"
//#include "g2o/types/slam3d/types_slam3d.h"
//#include "g2o/types/slam2d/types_slam2d.h"
#include "g2o/stuff/command_args.h"
using namespace std;
using namespace g2o;
// we use the 2D and 3D SLAM types here
G2O_USE_TYPE_GROUP(slam2d);
G2O_USE_TYPE_GROUP(slam3d);
int main(int argc, char** argv)
{
// Command line parsing
int maxIterations;
string outputFilename;
string inputFilename;
CommandArgs arg;
arg.param("i", maxIterations, 10, "perform n iterations, if negative consider the gain");
arg.param("o", outputFilename, "", "output final version of the graph");
arg.paramLeftOver("graph-input", inputFilename, "", "graph file which will be processed");
arg.parseArgs(argc, argv);
// create the linear solver
BlockSolverX::LinearSolverType * linearSolver = new LinearSolverCSparse<BlockSolverX::PoseMatrixType>();
// create the block solver on top of the linear solver
BlockSolverX* blockSolver = new BlockSolverX(linearSolver);
// create the algorithm to carry out the optimization
//OptimizationAlgorithmGaussNewton* optimizationAlgorithm = new OptimizationAlgorithmGaussNewton(blockSolver);
OptimizationAlgorithmLevenberg* optimizationAlgorithm = new OptimizationAlgorithmLevenberg(blockSolver);
// NOTE: We skip to fix a variable here, either this is stored in the file
// itself or Levenberg will handle it.
// create the optimizer to load the data and carry out the optimization
SparseOptimizer optimizer;
optimizer.setVerbose(true);
optimizer.setAlgorithm(optimizationAlgorithm);
ifstream ifs(inputFilename.c_str());
if (! ifs) {
cerr << "unable to open " << inputFilename << endl;
return 1;
}
optimizer.load(ifs);
optimizer.initializeOptimization();
optimizer.optimize(maxIterations);
if (outputFilename.size() > 0) {
if (outputFilename == "-") {
cerr << "saving to stdout";
optimizer.save(cout);
} else {
cerr << "saving " << outputFilename << " ... ";
optimizer.save(outputFilename.c_str());
}
cerr << "done." << endl;
}
return 0;
}
| [
"551619855@qq.com"
] | 551619855@qq.com |
e0033109277bd4f1ff67c7d4ee84ac411c19951d | 66f718c293a58c4990969c943985456765c3be91 | /src/testApp.cpp | 618dcb15e4dd07c5a978a959d508b0bf2d092335 | [] | no_license | miguelespada/arduino_paris | bbed7d79ef6b0ab95ff55f50c0bf1b0ecf775477 | 22e624e59099785860040d22ca128041325c863b | refs/heads/master | 2021-01-15T23:02:03.771442 | 2015-04-10T09:04:48 | 2015-04-10T09:04:48 | 32,094,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
ofSetVerticalSync(true);
ofSetFrameRate(60);
}
//--------------------------------------------------------------
void testApp::update(){
};
//--------------------------------------------------------------
void testApp::draw(){
info.draw();
}
//--------------------------------------------------------------
void testApp::keyPressed (int key){
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
} | [
"miguel.valero.espada@gmail.com"
] | miguel.valero.espada@gmail.com |
3f35158a3a86368de79daf6d3a6c2c59e948eb89 | 46dce717512fd5fce3964b5d0dc19fbc3c80562d | /arduino/AnalogInOutSerial.ino | 3727f0a8cb9e8d3476a5165d31b141596a0c7886 | [
"MIT"
] | permissive | hjgode/py1090_2 | eae02d0a46bbbd324671e4940e23d33cc39b0527 | ceb9e0810c394754fbf8ed18cf379d65ac31d885 | refs/heads/master | 2021-01-18T18:31:07.120654 | 2016-08-05T17:29:08 | 2016-08-05T17:29:08 | 62,028,041 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62 | ino | /home/hgode/SketchBook/AnalogInOutSerial/AnalogInOutSerial.ino | [
"hjgode@gmail.com"
] | hjgode@gmail.com |
971802a3c74a8e34f0ba0678d4ea2b8e91d240b1 | 41a305a708a46206e54f25d1b6aba04d792b0546 | /src/camera.cpp | 07b930b1c71ee26c56c16fc1742df29045ba6540 | [
"MIT"
] | permissive | SignalImageCV/loam_tools | 6afa241824aa45cc21cd33129df08b9f0f3d85be | f46294bae45104276a32f5a509fa568aed5295ef | refs/heads/master | 2020-04-24T21:38:38.647387 | 2017-09-11T19:45:43 | 2017-09-11T19:45:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | cpp | /* -*-c++-*--------------------------------------------------------------------
* 2017 Bernd Pfrommer bernd.pfrommer@gmail.com
*/
#include "loam_tools/camera.h"
namespace loam_tools {
std::ostream &operator<<(std::ostream &os, const Camera &c) {
os << "K: " << std::endl << c.K << std::endl << " dist: " << std::endl << c.dist << std::endl << " res: " << std::endl << c.res[0] << "x" << c.res[1];
return (os);
}
}
| [
"bernd.pfrommer@gmail.com"
] | bernd.pfrommer@gmail.com |
a8d96a32e21db8f2100cf4859c04733499192441 | 2c148e207664a55a5809a3436cbbd23b447bf7fb | /src/chrome/browser/resource_coordinator/tab_activity_watcher_browsertest.cc | d3fca266a8b15b7dbaa2160d3bb2181376bf251c | [
"BSD-3-Clause"
] | permissive | nuzumglobal/Elastos.Trinity.Alpha.Android | 2bae061d281ba764d544990f2e1b2419b8e1e6b2 | 4c6dad6b1f24d43cadb162fb1dbec4798a8c05f3 | refs/heads/master | 2020-05-21T17:30:46.563321 | 2018-09-03T05:16:16 | 2018-09-03T05:16:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,242 | cc | // Copyright 2018 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 <memory>
#include "base/macros.h"
#include "chrome/browser/resource_coordinator/tab_metrics_event.pb.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tabs/tab_ukm_test_helper.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/test/web_contents_tester.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/mojom/ukm_interface.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
using metrics::TabMetricsEvent;
using ukm::builders::TabManager_TabMetrics;
using ukm::builders::TabManager_Background_ForegroundedOrClosed;
namespace resource_coordinator {
namespace {
const char* kEntryName = TabManager_TabMetrics::kEntryName;
const char* kFOCEntryName =
TabManager_Background_ForegroundedOrClosed::kEntryName;
// The default metric values for a tab.
const UkmMetricMap kBasicMetricValues({
{TabManager_TabMetrics::kContentTypeName,
TabMetricsEvent::CONTENT_TYPE_TEXT_HTML},
{TabManager_TabMetrics::kDefaultProtocolHandlerName, base::nullopt},
{TabManager_TabMetrics::kHasBeforeUnloadHandlerName, 0},
{TabManager_TabMetrics::kHasFormEntryName, 0},
{TabManager_TabMetrics::kIsExtensionProtectedName, 0},
{TabManager_TabMetrics::kIsPinnedName, 0},
{TabManager_TabMetrics::kKeyEventCountName, 0},
{TabManager_TabMetrics::kNavigationEntryCountName, 1},
{TabManager_TabMetrics::kSiteEngagementScoreName, 0},
{TabManager_TabMetrics::kTouchEventCountName, 0},
{TabManager_TabMetrics::kWasRecentlyAudibleName, 0},
// TODO(michaelpg): Test TabManager_TabMetrics::kMouseEventCountName.
// Depending on the test environment, the browser may receive mouse events
// from the mouse cursor during tests, so we currently don't check this
// metric.
});
// These parameters don't affect logging.
const bool kIsUserGesture = true;
const bool kCheckNavigationSuccess = true;
} // namespace
// Tests UKM entries generated by TabActivityWatcher/TabMetricsLogger as tabs
// are backgrounded and foregrounded.
// Modeled after the TabActivityWatcherTest unit tests, these browser tests
// focus on end-to-end testing from the first browser launch onwards, verifying
// that window and browser commands are really triggering the paths that lead
// to UKM logs.
class TabActivityWatcherTest : public InProcessBrowserTest {
protected:
TabActivityWatcherTest() = default;
// InProcessBrowserTest:
void PreRunTestOnMainThread() override {
InProcessBrowserTest::PreRunTestOnMainThread();
ukm_entry_checker_ = std::make_unique<UkmEntryChecker>();
}
void SetUpOnMainThread() override {
// Browser created in BrowserMain() shouldn't result in a background tab
// being logged.
EXPECT_EQ(0u, ukm_entry_checker_->NumEntries(kEntryName));
ASSERT_TRUE(embedded_test_server()->Start());
test_urls_ = {embedded_test_server()->GetURL("/title1.html"),
embedded_test_server()->GetURL("/title2.html"),
embedded_test_server()->GetURL("/title3.html")};
}
void TearDown() override {
EXPECT_EQ(0, ukm_entry_checker_->NumNewEntriesRecorded(kEntryName));
InProcessBrowserTest::TearDown();
}
protected:
void ExpectNewForegroundedEntry(const GURL& url) {
// TODO(michaelpg): Add an interactive_ui_test to test MRU metrics since
// they can be affected by window activation.
UkmMetricMap expected_metrics = {
{TabManager_Background_ForegroundedOrClosed::kIsForegroundedName, 1},
};
ukm_entry_checker_->ExpectNewEntry(kFOCEntryName, url, expected_metrics);
}
void ExpectNewClosedEntry(const GURL& url) {
UkmMetricMap expected_metrics = {
{TabManager_Background_ForegroundedOrClosed::kIsForegroundedName, 0},
};
ukm_entry_checker_->ExpectNewEntry(kFOCEntryName, url, expected_metrics);
}
std::vector<GURL> test_urls_;
std::unique_ptr<UkmEntryChecker> ukm_entry_checker_;
private:
DISALLOW_COPY_AND_ASSIGN(TabActivityWatcherTest);
};
// Tests TabMetrics UKMs logged by creating and switching between tabs.
IN_PROC_BROWSER_TEST_F(TabActivityWatcherTest, SwitchTabs) {
const GURL kTabUrls[] = {
GURL(), // "about:blank" tab doesn't have a UKM source.
test_urls_[0], test_urls_[1],
};
EXPECT_EQ(0u, ukm_entry_checker_->NumEntries(kEntryName));
UkmMetricMap expected_metrics = kBasicMetricValues;
expected_metrics[TabManager_TabMetrics::kWindowIdName] =
browser()->session_id().id();
// Adding a new foreground tab logs the previously active tab.
AddTabAtIndex(1, kTabUrls[1], ui::PAGE_TRANSITION_LINK);
{
SCOPED_TRACE("");
ukm_entry_checker_->ExpectNewEntry(kEntryName, kTabUrls[0],
expected_metrics);
}
AddTabAtIndex(2, kTabUrls[2], ui::PAGE_TRANSITION_LINK);
{
SCOPED_TRACE("");
ukm_entry_checker_->ExpectNewEntry(kEntryName, kTabUrls[1],
expected_metrics);
}
// Switching to another tab logs the previously active tab.
browser()->tab_strip_model()->ActivateTabAt(0, kIsUserGesture);
{
SCOPED_TRACE("");
ukm_entry_checker_->ExpectNewEntry(kEntryName, kTabUrls[2],
expected_metrics);
ExpectNewForegroundedEntry(kTabUrls[0]);
}
browser()->tab_strip_model()->ActivateTabAt(1, kIsUserGesture);
{
SCOPED_TRACE("");
ukm_entry_checker_->ExpectNewEntry(kEntryName, kTabUrls[0],
expected_metrics);
ExpectNewForegroundedEntry(kTabUrls[1]);
}
// Closing the window doesn't log more TabMetrics UKMs (tested in TearDown()).
CloseBrowserSynchronously(browser());
{
SCOPED_TRACE("");
ExpectNewClosedEntry(kTabUrls[2]);
ExpectNewClosedEntry(kTabUrls[0]);
}
}
// Tests that switching between multiple windows doesn't affect TabMetrics UKMs.
// This is a sanity check; window activation shouldn't make any difference to
// what we log. If we needed to actually test different behavior based on window
// focus, we would run these tests in interactive_ui_tests.
IN_PROC_BROWSER_TEST_F(TabActivityWatcherTest, SwitchWindows) {
Browser* browser_2 = CreateBrowser(browser()->profile());
EXPECT_EQ(0, ukm_entry_checker_->NumNewEntriesRecorded(kEntryName));
AddTabAtIndexToBrowser(browser(), 1, test_urls_[0], ui::PAGE_TRANSITION_LINK,
kCheckNavigationSuccess);
{
SCOPED_TRACE("");
UkmMetricMap expected_metrics = kBasicMetricValues;
expected_metrics[TabManager_TabMetrics::kWindowIdName] =
browser()->session_id().id();
ukm_entry_checker_->ExpectNewEntry(kEntryName, GURL(), kBasicMetricValues);
}
AddTabAtIndexToBrowser(browser_2, 1, test_urls_[1], ui::PAGE_TRANSITION_LINK,
kCheckNavigationSuccess);
{
SCOPED_TRACE("");
UkmMetricMap expected_metrics = kBasicMetricValues;
expected_metrics[TabManager_TabMetrics::kWindowIdName] =
browser_2->session_id().id();
ukm_entry_checker_->ExpectNewEntry(kEntryName, GURL(), kBasicMetricValues);
}
browser()->window()->Activate();
browser_2->window()->Activate();
EXPECT_EQ(0, ukm_entry_checker_->NumNewEntriesRecorded(kEntryName));
// Closing each window doesn't log more TabMetrics UKMs.
CloseBrowserSynchronously(browser_2);
CloseBrowserSynchronously(browser());
}
// Tests page with a beforeunload handler.
IN_PROC_BROWSER_TEST_F(TabActivityWatcherTest, BeforeUnloadHandler) {
// Navigate to a page with a beforeunload handler.
GURL url(embedded_test_server()->GetURL("/beforeunload.html"));
ui_test_utils::NavigateToURL(browser(), url);
// Log metrics for the first tab by switching to a new tab.
AddTabAtIndex(1, test_urls_[0], ui::PAGE_TRANSITION_LINK);
UkmMetricMap expected_metrics = kBasicMetricValues;
expected_metrics[TabManager_TabMetrics::kHasBeforeUnloadHandlerName] = 1;
expected_metrics[TabManager_TabMetrics::kNavigationEntryCountName] = 2;
{
SCOPED_TRACE("");
ukm_entry_checker_->ExpectNewEntry(kEntryName, url, expected_metrics);
}
// Sanity check: the new tab doesn't have a beforeunload handler.
browser()->tab_strip_model()->ActivateTabAt(0, kIsUserGesture);
{
SCOPED_TRACE("");
ukm_entry_checker_->ExpectNewEntry(kEntryName, test_urls_[0],
kBasicMetricValues);
}
}
// Tests events logged when dragging a tab between browsers.
IN_PROC_BROWSER_TEST_F(TabActivityWatcherTest, TabDrag) {
// This test will navigate 3 tabs.
const GURL kBrowserStartUrl = test_urls_[0];
const GURL kBrowser2StartUrl = test_urls_[1];
const GURL kDraggedTabUrl = test_urls_[2];
Browser* browser_2 = CreateBrowser(browser()->profile());
ui_test_utils::NavigateToURL(browser(), kBrowserStartUrl);
ui_test_utils::NavigateToURL(browser_2, kBrowser2StartUrl);
// Adding a tab backgrounds the original tab in the window.
AddTabAtIndexToBrowser(browser(), 1, kDraggedTabUrl, ui::PAGE_TRANSITION_LINK,
kCheckNavigationSuccess);
{
SCOPED_TRACE("");
ukm_entry_checker_->ExpectNewEntry(
kEntryName, kBrowserStartUrl,
{{TabManager_TabMetrics::kWindowIdName, browser()->session_id().id()}});
}
// "Drag" the new tab out of its browser.
content::WebContents* dragged_contents =
browser()->tab_strip_model()->GetWebContentsAt(1);
std::unique_ptr<content::WebContents> owned_dragged_contents =
browser()->tab_strip_model()->DetachWebContentsAt(1);
dragged_contents->WasHidden();
// The other tab in the browser is now foregrounded.
ExpectNewForegroundedEntry(kBrowserStartUrl);
// "Drop" the tab into the other browser. This requires showing and
// reactivating the tab, but to the user, it never leaves the foreground, so
// we don't log a foregrounded event for it.
browser_2->tab_strip_model()->InsertWebContentsAt(
1, std::move(owned_dragged_contents), TabStripModel::ADD_NONE);
dragged_contents->WasShown();
browser_2->tab_strip_model()->ActivateTabAt(1, kIsUserGesture);
EXPECT_EQ(0, ukm_entry_checker_->NumNewEntriesRecorded(kFOCEntryName));
// The first tab in this window was backgrounded when the new one was
// inserted.
{
SCOPED_TRACE("");
ukm_entry_checker_->ExpectNewEntry(
kEntryName, kBrowser2StartUrl,
{{TabManager_TabMetrics::kWindowIdName, browser_2->session_id().id()}});
}
// Closing the window with 2 tabs means we log the backgrounded tab as closed.
CloseBrowserSynchronously(browser_2);
ExpectNewClosedEntry(kBrowser2StartUrl);
CloseBrowserSynchronously(browser());
EXPECT_EQ(0, ukm_entry_checker_->NumNewEntriesRecorded(kEntryName));
EXPECT_EQ(0, ukm_entry_checker_->NumNewEntriesRecorded(kFOCEntryName));
}
} // namespace resource_coordinator
| [
"jiawang.yu@spreadtrum.com"
] | jiawang.yu@spreadtrum.com |
e91afc70759caae8cd5f20e896c9fb9f1951910f | a6334a20b6fb6cfe8cb422dab980c09bd69eff50 | /katis/simpleaddition.cpp | 4124be3de628cb41a26dbff41354038324cd291e | [] | no_license | anhoangphuc/CP | d0fcc3f4c25f3216f02d1dfdd68cf817a336a0f3 | 609f18852bd76dbc7b2ed52e44f3b58095e8c3b9 | refs/heads/master | 2022-07-19T11:42:36.017438 | 2022-07-02T04:11:24 | 2022-07-02T04:11:24 | 208,000,598 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,543 | cpp | #include <bits/stdc++.h>
using namespace std;
const int BASE = 1e9;
const int scs = 9;
typedef vector<int> BigInt;
//----------------------------------------
BigInt stringToBigInt(string s) {
BigInt res;
res.clear();
int i = s.length() - 1;
while (i >= 0) {
int j = max(i - scs + 1, 0);
res.push_back(stoi(s.substr(j, i - j + 1)));
i = j - 1;
}
return res;
}
//----------------------------------------
void printBigInt(BigInt a) {
for (auto x = a.rbegin(); x != a.rend(); x++) {
if (x == a.rbegin()) cout << *x;
else {
string temp = to_string(*x);
while (temp.length() < scs) temp = '0' + temp;
cout << temp;
}
}
cout << endl;
}
//----------------------------------------
BigInt addBigInt(BigInt firstNumber, BigInt secondNumber) {
BigInt res;
res.clear();
int carry = 0;
for (auto i = 0; i < max(firstNumber.size(), secondNumber.size()); i++) {
auto val1 = i < firstNumber.size() ? firstNumber[i]:0;
auto val2 = i < secondNumber.size() ? secondNumber[i]:0;
auto tmp = (val1 + val2 + carry);
res.push_back(tmp % BASE);
carry = tmp / BASE;
}
return res;
}
//----------------------------------------
int main() {
string s;
cin >> s;
auto firstNumber = stringToBigInt(s);
cin >> s;
auto secondNumber = stringToBigInt(s);
printBigInt(addBigInt(firstNumber, secondNumber));
} | [
"hoangphucnb97@gmail.com"
] | hoangphucnb97@gmail.com |
c5e72db749010bd31e64a5e0359457b30aa6d6ac | e62fe3e24d00711e5e5666a99b17dcd7bd727d00 | /em_test_3/em_test_3/Common/Trace.hpp | ea8e96dd33fc08cd0af6c13b3647c81bace0329a | [] | no_license | Scouser87/em_test_3 | a0212b30adc2070064ddcd3058113b65877e0be3 | 3a3497c9f5d4554696d224e0bce841ff93352252 | refs/heads/master | 2020-05-22T18:12:10.241416 | 2017-03-12T20:59:37 | 2017-03-12T20:59:37 | 84,712,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,281 | hpp | //
// Trace.hpp
// em_test_3
//
// Created by Sergei Makarov on 09.03.17.
// Copyright © 2017 Sergei Makarov. All rights reserved.
//
#ifndef Trace_hpp
#define Trace_hpp
#include <stdio.h>
#include <string>
void G_CustomLog(int _lvl, int _extraFlags, const char* type, const char* s_function, int s_line, const char * sFmt,...);
#define LOG(...) {G_CustomLog(0, 0, "ALL",__func__,__LINE__,__VA_ARGS__);}
#define LOGeX(_lvl, _extraFlags, ...) {G_CustomLog(_lvl, _extraFlags, "ALL",__func__,__LINE__,__VA_ARGS__);}
#define ALOG(...) {G_CustomLog(0, 0, "FRAMEWORK",__func__,__LINE__,__VA_ARGS__);}
#define ALOGeX(_lvl, _extraFlags, ...) {G_CustomLog(_lvl, _extraFlags, "FRAMEWORK",__func__,__LINE__,__VA_ARGS__);}
#define GLOG(...) {G_CustomLog(0, 0, "GAME",__func__,__LINE__,__VA_ARGS__);}
#define GLOGeX(_lvl, _extraFlags, ...) {G_CustomLog(_lvl, _extraFlags, "GAME",__func__,__LINE__,__VA_ARGS__);}
#define NLOG(...) {G_CustomLog(0, 0, "NETWORK",__func__,__LINE__,__VA_ARGS__);}
#define NLOGeX(_lvl, _extraFlags, ...) {G_CustomLog(_lvl, _extraFlags, "NETWORK",__func__,__LINE__,__VA_ARGS__);}
#define SLOG(...) {G_CustomLog(0, 0, "SERVER",__func__,__LINE__,__VA_ARGS__);}
#define SLOGeX(_lvl, _extraFlags, ...) {G_CustomLog(_lvl, _extraFlags, "SERVER",__func__,__LINE__,__VA_ARGS__);}
#define OS_LOG(...) {G_CustomLog(0, 0, "SYSTEM",__func__,__LINE__,__VA_ARGS__);}
#define OS_LOGeX(_lvl, _extraFlags, ...) {G_CustomLog(_lvl, _extraFlags, "SYSTEM",__func__,__LINE__,__VA_ARGS__);}
#define TLOG(...) {G_CustomLog(0, 0, "TRACE",__func__,__LINE__,__VA_ARGS__);}
#define TLOGeX(_lvl, _extraFlags, ...) {G_CustomLog(_lvl, _extraFlags, "TRACE",__func__,__LINE__,__VA_ARGS__);}
#define C_LOG(type,...) {G_CustomLog(0, 0, type,__func__,__LINE__,__VA_ARGS__);}
#define TRACE(x) { tracefunctions::stringwithnameofvarible=#x; tracefunctions::print(x);}
namespace tracefunctions
{
extern std::string stringwithnameofvarible;
void print(int x);
void print(unsigned int x);
void print(long x);
void print(unsigned long x);
void print(long long x);
void print(unsigned long long x);
void print(bool x);
void print(double x);
void print(const char* x);
void print(char* x);
void print(std::string x);
};
#endif /* Trace_hpp */
| [
"scouser987@gmail.com"
] | scouser987@gmail.com |
9936e31d4114d54fa7e4731c067359cc7b8058d2 | cf4c0dadd6701fec73fa48ee396c180e51f1c272 | /OcclusionTest/Experimental/OSGExactOccupancyMap.h | eac1b486b8c994be1d3a21d9a4901a68607d4125 | [] | no_license | BackupTheBerlios/opensgplus | df8afe4211eb2210647eeec4f93ceb4216958f26 | 45d2e5e30ab8448c25faeb4a5c882a7ffc5c9812 | refs/heads/master | 2020-04-17T18:31:32.481331 | 2006-06-13T22:40:43 | 2006-06-13T22:40:43 | 40,039,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,530 | h | /*---------------------------------------------------------------------------*\
* OpenSG PLUS Occlusion Test *
* *
* *
* Copyright (C) 2002 by the WSI/GRIS Uni Tuebingen *
* *
* www.opensg.org *
* *
* contact: staneker@gris.uni-tuebingen.de *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
#ifndef _OSGEXACTOCCUPANCYMAP_H_
#define _OSGEXACTOCCUPANCYMAP_H_ 1
#ifdef __sgi
#pragma once
#endif
#include <GL/gl.h>
#include <OSGBaseTypes.h>
#include <OSGSystemDef.h>
#include <OSGDrawAction.h>
#include <OSGDynamicVolume.h>
#include <OSGRasterizer.h>
OSG_BEGIN_NAMESPACE
//! ExactOccupancyMap
//! \ingroup RenderingBackendLib
template<typename buffertype, UInt16 scaleshift=4>
class OSG_SYSTEMLIB_DLLMAPPING ExactOccupancyMap
{
/*========================== PUBLIC =================================*/
public:
/*---------------------------------------------------------------------*/
/*! \name Statistic */
/*! \{ */
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Constructors */
/*! \{ */
ExactOccupancyMap(void);
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Destructor */
/*! \{ */
virtual ~ExactOccupancyMap(void);
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Access */
/*! \{ */
void setup(const Int32&, const UInt16&, const UInt16&);
void setup(const Int32&, Viewport*);
void frameInit(void);
void frameExit(void);
void init(void);
void perform(const Int32&, const Int16* bb_x, const Int16* bb_y, const Real32* bb_z, const char bb_minidx);
void insertBox(const Int16* bb_x, const Int16* bb_y, const Real32* bb_z, const char bb_minidx);
Int32 result(const Int32&);
void exit(void);
/*! \} */
/*========================= PROTECTED ===============================*/
protected:
/*---------------------------------------------------------------------*/
/*! \name Member */
/*! \{ */
/*! \} */
/*========================== PRIVATE ================================*/
private:
class testPoint{
private:
ExactOccupancyMap<buffertype, scaleshift>* _t;
public:
testPoint(ExactOccupancyMap<buffertype, scaleshift>* t):_t(t){ };
inline bool visitPoint(const Int16& x, const Int16& y, const Real32&){
return(_t->visitPoint(x,y,0));
};
};
class renderPoint{
private:
ExactOccupancyMap<buffertype, scaleshift>* _t;
public:
renderPoint(ExactOccupancyMap<buffertype, scaleshift>* t):_t(t){ };
inline bool visitPoint(const Int16& x, const Int16& y, const Real32&){
return(_t->setPoint(x,y,1));
};
};
testPoint _testPoint;
renderPoint _renderPoint;
UInt32 _maxtests;
GLuint* _results;
Int32 _pixcount;
Int32 _maxpix;
UInt32 _w, _h; // Width and height of viewport
UInt32 _bufferw; // Width and height of buffer
/**************************************************
* Fragmented Z-Buffer for Occlusion Culling Test *
**************************************************/
buffertype* _buffer;
void clearBuffer(void);
bool getPoint(const Int32& x, const Int32& y);
bool boxIsVisible(void);
bool boxIsHidden(void);
bool testBox(const Int16* bb_x, const Int16* bb_y, const Real32* bb_z, const char bb_minidx);
bool setPoint(const Int32& x, const Int32& y, const bool&);
bool visitPoint(const Int32& x, const Int32& y, const bool&);
void visualize(void);
/*! \brief prohibit default function (move to 'public' if needed) */
ExactOccupancyMap(const ExactOccupancyMap &source);
/*! \brief prohibit default function (move to 'public' if needed) */
void operator =(const ExactOccupancyMap &source);
};
OSG_END_NAMESPACE
#include "OSGExactOccupancyMap.inl"
#endif /* _OSGEXACTOCCUPANCYMAP_H_ */
| [
"jsux"
] | jsux |
44788abfea6b485679ebdfc462c68dd38a18941c | 0c8ef462f89c184e3f86b2d9ac97f572c373c1aa | /Collisions/Collider.h | 8499373a52338bdfb9ded97fcb0020776c76adba | [] | no_license | SonyaHon/opengl2d | 7aec023fb1edbedb874159a0d96aa81c714456a9 | ccd697f0d9e60f179135b8d2981f763a85b1d156 | refs/heads/master | 2021-01-11T14:49:43.459262 | 2017-03-27T13:46:48 | 2017-03-27T13:46:48 | 80,225,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | h | #ifndef INC_2DS_COLLIDER_H
#define INC_2DS_COLLIDER_H
#include <GL/glew.h>
#include <glm/glm.hpp>
#include "../Utils/Enums.h"
class Collider {
private:
ColliderType type;
glm::vec2 position;
GLfloat width;
GLfloat height;
GLfloat radius1;
public:
Collider();
Collider(ColliderType type, GLfloat x, GLfloat y, GLfloat size1, GLfloat size2);
Collider(ColliderType type, GLfloat x, GLfloat y, GLfloat size1);
const glm::vec2 &getPosition() const;
void setColliderSize(GLfloat size1, GLfloat size2);
bool collisionSimple(GLfloat myX, GLfloat myY, Collider &target, GLfloat targetX, GLfloat targetY);
};
#endif //INC_2DS_COLLIDER_H
| [
"volkov030@gmail.com"
] | volkov030@gmail.com |
ae293b8f3769d3521a5c5b69a469047068bf03c8 | 527739ed800e3234136b3284838c81334b751b44 | /include/RED4ext/Types/generated/anim/IAnimNodeSourceChannel_Float.hpp | c59ebe31d776650f2d1dccb14ca5c310b5e1fafb | [
"MIT"
] | permissive | 0xSombra/RED4ext.SDK | 79ed912e5b628ef28efbf92d5bb257b195bfc821 | 218b411991ed0b7cb7acd5efdddd784f31c66f20 | refs/heads/master | 2023-07-02T11:03:45.732337 | 2021-04-15T16:38:19 | 2021-04-15T16:38:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | hpp | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/ISerializable.hpp>
namespace RED4ext
{
namespace anim {
struct IAnimNodeSourceChannel_Float : ISerializable
{
static constexpr const char* NAME = "animIAnimNodeSourceChannel_Float";
static constexpr const char* ALIAS = NAME;
};
RED4EXT_ASSERT_SIZE(IAnimNodeSourceChannel_Float, 0x30);
} // namespace anim
} // namespace RED4ext
| [
"expired6978@gmail.com"
] | expired6978@gmail.com |
6429b2d7eb85eda0cd17e33027e05b5d07ecf4a8 | 4e02637ff36bdae1357b3196d3b94108f2245511 | /glm-0.9.2.7/glm/gtx/multiple.inl | 6ccf1adbf9df61d12ab1251552230e19dd5f6724 | [
"MIT"
] | permissive | lokeshh/checkers | 6ebf5b6fa413f41daa0346621b74ab3d3e3ab91f | fd79acbfc3a9f53e853bf35356272f83c8909684 | refs/heads/master | 2021-01-10T08:14:53.824994 | 2020-10-11T15:49:03 | 2020-10-11T15:49:03 | 43,547,155 | 1 | 1 | MIT | 2020-10-11T15:49:05 | 2015-10-02T10:26:38 | C++ | UTF-8 | C++ | false | false | 4,935 | inl | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2009-10-26
// Updated : 2009-10-26
// Licence : This source is under MIT License
// File : glm/gtx/multiple.inl
///////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency:
// - GLM core
///////////////////////////////////////////////////////////////////////////////////////////////////
namespace glm{
namespace gtx{
namespace multiple
{
//////////////////////
// higherMultiple
template <typename genType>
GLM_FUNC_QUALIFIER genType higherMultiple
(
genType const & Source,
genType const & Multiple
)
{
genType Tmp = Source % Multiple;
return Tmp ? Source + Multiple - Tmp : Source;
}
template <>
GLM_FUNC_QUALIFIER detail::thalf higherMultiple
(
detail::thalf const & Source,
detail::thalf const & Multiple
)
{
int Tmp = int(float(Source)) % int(float(Multiple));
return Tmp ? Source + Multiple - detail::thalf(float(Tmp)) : Source;
}
template <>
GLM_FUNC_QUALIFIER float higherMultiple
(
float const & Source,
float const & Multiple
)
{
int Tmp = int(Source) % int(Multiple);
return Tmp ? Source + Multiple - float(Tmp) : Source;
}
template <>
GLM_FUNC_QUALIFIER double higherMultiple
(
double const & Source,
double const & Multiple
)
{
long Tmp = long(Source) % long(Multiple);
return Tmp ? Source + Multiple - double(Tmp) : Source;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tvec2<T> higherMultiple
(
detail::tvec2<T> const & Source,
detail::tvec2<T> const & Multiple
)
{
detail::tvec2<T> Result;
for(typename detail::tvec2<T>::size_type i = 0; i < detail::tvec2<T>::value_size(); ++i)
Result[i] = higherMultiple(Source[i], Multiple[i]);
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tvec3<T> higherMultiple
(
detail::tvec3<T> const & Source,
detail::tvec3<T> const & Multiple
)
{
detail::tvec3<T> Result;
for(typename detail::tvec3<T>::size_type i = 0; i < detail::tvec3<T>::value_size(); ++i)
Result[i] = higherMultiple(Source[i], Multiple[i]);
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tvec4<T> higherMultiple
(
detail::tvec4<T> const & Source,
detail::tvec4<T> const & Multiple
)
{
detail::tvec4<T> Result;
for(typename detail::tvec4<T>::size_type i = 0; i < detail::tvec4<T>::value_size(); ++i)
Result[i] = higherMultiple(Source[i], Multiple[i]);
return Result;
}
//////////////////////
// lowerMultiple
template <typename genType>
GLM_FUNC_QUALIFIER genType lowerMultiple
(
genType const & Source,
genType const & Multiple
)
{
genType Tmp = Source % Multiple;
return Tmp ? Source - Tmp : Source;
}
template <>
GLM_FUNC_QUALIFIER detail::thalf lowerMultiple
(
detail::thalf const & Source,
detail::thalf const & Multiple
)
{
int Tmp = int(float(Source)) % int(float(Multiple));
return Tmp ? Source - detail::thalf(float(Tmp)) : Source;
}
template <>
GLM_FUNC_QUALIFIER float lowerMultiple
(
float const & Source,
float const & Multiple
)
{
int Tmp = int(Source) % int(Multiple);
return Tmp ? Source - float(Tmp) : Source;
}
template <>
GLM_FUNC_QUALIFIER double lowerMultiple
(
double const & Source,
double const & Multiple
)
{
long Tmp = long(Source) % long(Multiple);
return Tmp ? Source - double(Tmp) : Source;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tvec2<T> lowerMultiple
(
detail::tvec2<T> const & Source,
detail::tvec2<T> const & Multiple
)
{
detail::tvec2<T> Result;
for(typename detail::tvec2<T>::size_type i = 0; i < detail::tvec2<T>::value_size(); ++i)
Result[i] = lowerMultiple(Source[i], Multiple[i]);
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tvec3<T> lowerMultiple
(
detail::tvec3<T> const & Source,
detail::tvec3<T> const & Multiple
)
{
detail::tvec3<T> Result;
for(typename detail::tvec3<T>::size_type i = 0; i < detail::tvec3<T>::value_size(); ++i)
Result[i] = lowerMultiple(Source[i], Multiple[i]);
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tvec4<T> lowerMultiple
(
detail::tvec4<T> const & Source,
detail::tvec4<T> const & Multiple
)
{
detail::tvec4<T> Result;
for(typename detail::tvec4<T>::size_type i = 0; i < detail::tvec4<T>::value_size(); ++i)
Result[i] = lowerMultiple(Source[i], Multiple[i]);
return Result;
}
}//namespace multiple
}//namespace gtx
}//namespace glm
| [
"lokeshhsharma@gmail.com"
] | lokeshhsharma@gmail.com |
d453173e78999f5a7b0dabd24b1821f1042120ea | 1097ed333a4000634e68a590ee6ffc6129ae61e3 | /CppScripts/torch-x/tinynet.cpp | 1196b267c6cb59c9c4e92b72a802cb71ebd6a982 | [
"MIT"
] | permissive | AutuanLiu/Code-Storm2019 | 1bbe890c7ca0d033c32348173bfebba612623a90 | 8efc7c5475fd888f7d86c3b08a3c1c9e55c1ac30 | refs/heads/master | 2020-04-23T07:03:08.975232 | 2019-10-24T08:56:26 | 2019-10-24T08:56:26 | 170,995,032 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 144 | cpp | #include <torch/torch.h>
#include <iostream>
int main() {
torch::Tensor tensor = torch::rand({2, 3});
std::cout << tensor << std::endl;
}
| [
"autuanliu@163.com"
] | autuanliu@163.com |
98178a59b12ef9e945c54d003159377689493b8a | 8fcf034037208ccb83e8de56467d2efe8b13d9b0 | /src/codecs/field_codecs.h | 5fb74c583d1b4d77a17de73481c749b90329bb96 | [] | no_license | callmepurple/TimeBaseClientPython | b268bd4faf78035830925a6f72808e95e71d09f9 | ef0a982e6e098752f887765855da304e91fd1227 | refs/heads/main | 2023-04-30T19:10:02.534248 | 2021-05-17T12:02:41 | 2021-05-17T12:02:41 | 368,222,884 | 0 | 0 | null | 2021-05-17T14:50:46 | 2021-05-17T14:50:45 | null | UTF-8 | C++ | false | false | 30,552 | h | #ifndef DELTIX_API_DECODERS_FIELD_DECODERS_H_
#define DELTIX_API_DECODERS_FIELD_DECODERS_H_
#include "Python.h"
#include "python_common.h"
#include "schema.h"
#include "message_codec.h"
#include <algorithm>
#include <memory>
extern "C" double decimal_native_toFloat64(uint64_t value);
extern "C" uint64_t decimal_native_fromFloat64(double value);
double dfp_toDouble(uint64_t value) {
return decimal_native_toFloat64(value);
}
uint64_t dfp_fromDouble(double value) {
return decimal_native_fromFloat64(value);
}
namespace DxApiImpl {
namespace Python {
class FieldCodec {
protected:
FieldCodec(const char *field_name) : field_name_(field_name) {
key_ = PyUnicode_FromString(field_name);
};
virtual ~FieldCodec() {
Py_XDECREF(key_);
Py_XDECREF(TYPE_NAME_PROPERTY1);
}
public:
virtual PyObject * decode(DxApi::DataReader &reader) = 0;
virtual void encode(PyObject *field_value, DxApi::DataWriter &writer) = 0;
const char * getFieldName() {
return field_name_.c_str();
}
PyObject * getKey() {
return key_;
}
protected:
PyObject * key_;
std::string field_name_;
PyObject * TYPE_NAME_PROPERTY1 = PyUnicode_FromString("typeName");
private:
DISALLOW_COPY_AND_ASSIGN(FieldCodec);
};
template <typename T>
class FieldValueCodec : public FieldCodec {
protected:
FieldValueCodec(const char *field_name, FieldValueCodec<T> *relative_to)
: FieldCodec(field_name), relative_to_(relative_to)
{ };
public:
virtual void appendRelative(T &value) {
if (relative_to_ != NULL && !relative_to_->isNull())
value = relative_to_->getValue() + value;
}
virtual void substractRelative(T &value) {
if (relative_to_ != NULL && !relative_to_->isNull())
value = value - relative_to_->getValue();
}
virtual T & getValue() {
return value_;
}
virtual bool isNull() {
return is_null_;
}
protected:
T value_;
bool is_null_;
FieldValueCodec<T> *relative_to_;
};
class AlphanumericFieldCodec : public FieldCodec {
public:
AlphanumericFieldCodec(const char* field_name, int field_size) : FieldCodec(field_name), field_size_(field_size) { };
inline PyObject * decode(DxApi::DataReader &reader) {
bool hasField = reader.readAlphanumeric(buffer_, field_size_);
if (!hasField)
Py_RETURN_NONE;
else
return PyUnicode_FromString(buffer_.c_str());
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
bool type_mismatch = false;
bool exists = getStringValue(field_value, buffer_, type_mismatch);
if (type_mismatch)
THROW_EXCEPTION("Wrong type of field '%s'. Required: STRING.", field_name_.c_str());
if (exists) {
writer.writeAlphanumeric(field_size_, buffer_);
} else {
writer.writeAlphanumericNull(field_size_);
}
}
protected:
int field_size_;
std::string buffer_;
};
class TimestampFieldCodec : public FieldCodec {
public:
TimestampFieldCodec(const char* field_name) : FieldCodec(field_name) { };
inline PyObject * decode(DxApi::DataReader &reader) {
int64_t value = reader.readTimestamp();
if (value != DxApi::TIMESTAMP_NULL)
return PyLong_FromLongLong(value);
else
Py_RETURN_NONE;
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
int64_t value;
bool type_mismatch;
bool exists = getInt64Value(field_value, value, type_mismatch);
if (type_mismatch)
THROW_EXCEPTION("Wrong type of field '%s'. Required: INTEGER.", field_name_.c_str());
if (exists) {
writer.writeTimestamp(value);
} else {
writer.writeTimestamp(DxApi::TIMESTAMP_NULL);
}
}
};
class IntegerFieldCodec : public FieldValueCodec<int64_t> {
public:
IntegerFieldCodec(const char* field_name, FieldValueCodec<int64_t> *relative_to, int field_size)
: FieldValueCodec(field_name, relative_to), field_size_(field_size) { };
inline PyObject * decode(DxApi::DataReader &reader) {
switch (field_size_) {
case 8: {
int8_t result = reader.readInt8();
if (result != DxApi::Constants::INT8_NULL) {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyLong_FromLongLong(value_);
} else {
Py_RETURN_NONE;
}
}
break;
case 16: {
int16_t result = reader.readInt16();
if (result != DxApi::Constants::INT16_NULL) {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyLong_FromLongLong(value_);
} else {
Py_RETURN_NONE;
}
}
break;
case 30: {
uint32_t result = reader.readPUInt30();
if (result != DxApi::UINT61_NULL) {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyLong_FromLongLong(value_);
} else {
Py_RETURN_NONE;
}
}
break;
case 32: {
int32_t result = reader.readInt32();
if (result != DxApi::Constants::INT32_NULL) {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyLong_FromLongLong(value_);
} else {
Py_RETURN_NONE;
}
}
break;
case 48: {
int64_t result = reader.readInt48();
if (result != DxApi::INT48_NULL) {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyLong_FromLongLong(value_);
} else {
Py_RETURN_NONE;
}
}
break;
case 61: {
uint64_t result = reader.readPUInt61();
if (result != DxApi::UINT61_NULL) {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyLong_FromLongLong(value_);
} else {
Py_RETURN_NONE;
}
}
break;
case 64: {
int64_t result = reader.readInt64();
if (result != DxApi::INT64_NULL) {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyLong_FromLongLong(value_);
} else {
Py_RETURN_NONE;
}
}
break;
default:
THROW_EXCEPTION("Unknow size of integer: %d.", field_size_);
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
bool type_mismatch;
bool exists = getInt64Value(field_value, value_, type_mismatch);
if (type_mismatch)
THROW_EXCEPTION("Wrong type of field '%s'. Required: INTEGER.", field_name_.c_str());
if (!exists) {
is_null_ = true;
switch (field_size_) {
case 8: {
writer.writeInt8(DxApi::Constants::INT8_NULL);
}
break;
case 16: {
writer.writeInt16(DxApi::Constants::INT16_NULL);
}
break;
case 30: {
writer.writePUInt30(DxApi::UINT30_NULL);
}
break;
case 32: {
writer.writeInt32(DxApi::Constants::INT32_NULL);
}
break;
case 48: {
writer.writeInt48(DxApi::INT48_NULL);
}
break;
case 61: {
writer.writePUInt61(DxApi::UINT61_NULL);
}
break;
case 64: {
writer.writeInt64(DxApi::INT64_NULL);
}
break;
default:
THROW_EXCEPTION("Unknow size of integer: %d.", field_size_);
}
} else {
substractRelative(value_);
is_null_ = false;
switch (field_size_)
{
case 8: {
writer.writeInt8((int8_t)value_);
}
break;
case 16: {
writer.writeInt16((int16_t)value_);
}
break;
case 30: {
writer.writePUInt30((uint32_t)value_);
}
break;
case 32: {
writer.writeInt32((int32_t)value_);
}
break;
case 48: {
writer.writeInt48(value_);
}
break;
case 61: {
writer.writePUInt61((uint64_t)value_);
}
break;
case 64: {
writer.writeInt64(value_);
}
break;
default:
THROW_EXCEPTION("Unknow size of integer: %d.", field_size_);
}
}
}
private:
int field_size_;
};
class Decimal64FieldCodec : public FieldCodec {
public:
Decimal64FieldCodec(const char* field_name) : FieldCodec(field_name) { };
inline PyObject * decode(DxApi::DataReader &reader) {
int64_t result = reader.readInt64();
if (result != DxApi::INT64_NULL) {
return PyFloat_FromDouble(decodeDecimal64(result));
} else {
Py_RETURN_NONE;
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
double value;
bool type_mismatch;
bool exists = getDoubleValue(field_value, value, type_mismatch);
if (type_mismatch)
THROW_EXCEPTION("Wrong type of field '%s'. Required: DOUBLE.", field_name_.c_str());
if (exists) {
writer.writeInt64(encodeDecimal64(value));
} else {
writer.writeInt64(DxApi::INT64_NULL);
}
}
inline double decodeDecimal64(int64_t value) {
return dfp_toDouble(value);
}
inline int64_t encodeDecimal64(double value) {
return dfp_fromDouble(value);
}
};
class FloatFieldCodec : public FieldValueCodec<double> {
public:
FloatFieldCodec(const char* field_name, FieldValueCodec *relative_to, int field_size)
: FieldValueCodec(field_name, relative_to), field_size_(field_size) {
};
inline PyObject * decode(DxApi::DataReader &reader) {
switch (field_size_) {
case 32: {
float result = reader.readFloat32();
if (result != result) {
Py_RETURN_NONE;
} else {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyFloat_FromDouble(value_);
}
}
break;
case 63: {
double result = reader.readDecimal();
value_ = result;
if (result != result) {
Py_RETURN_NONE;
} else {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyFloat_FromDouble(value_);
}
}
break;
case 64: {
double result = reader.readFloat64();
value_ = result;
if (result != result) {
Py_RETURN_NONE;
} else {
value_ = result;
is_null_ = false;
appendRelative(value_);
return PyFloat_FromDouble(value_);
}
}
break;
default:
THROW_EXCEPTION("Unknow size of float: %d.", field_size_);
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
bool type_mismatch;
bool exists = getDoubleValue(field_value, value_, type_mismatch);
if (type_mismatch)
THROW_EXCEPTION("Wrong type of field '%s'. Required: FLOAT.", field_name_.c_str());
if (!exists) {
is_null_ = true;
switch (field_size_) {
case 32: {
writer.writeFloat32(DxApi::FLOAT32_NULL);
}
break;
case 63: {
writer.writeDecimal(DxApi::DECIMAL_NULL);
}
break;
case 64: {
writer.writeFloat64(DxApi::FLOAT64_NULL);
}
break;
default:
THROW_EXCEPTION("Unknow size of float: %d.", field_size_);
}
} else {
substractRelative(value_);
is_null_ = false;
switch (field_size_)
{
case 32: {
writer.writeFloat32((float)value_);
}
break;
case 63: {
writer.writeDecimal(value_);
}
break;
case 64: {
writer.writeFloat64(value_);
}
break;
default:
THROW_EXCEPTION("Unknow size of float: %d.", field_size_);
}
}
}
protected:
int field_size_;
};
class IntervalFieldCodec : public FieldCodec {
public:
IntervalFieldCodec(const char* field_name) : FieldCodec(field_name) {};
inline PyObject * decode(DxApi::DataReader &reader) {
int32_t result = reader.readInterval();
if (result != DxApi::Constants::INTERVAL_NULL)
return PyLong_FromLong(result);
else
Py_RETURN_NONE;
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
int32_t value;
bool type_mismatch;
bool exists = getInt32Value(field_value, value, type_mismatch);
if (type_mismatch)
THROW_EXCEPTION("Wrong type of field '%s'. Required: INTEGER.", field_name_.c_str());
if (exists) {
writer.writeInterval(value);
} else {
writer.writeInterval(DxApi::Constants::INTERVAL_NULL);
}
}
};
class TimeOfDayFieldCodec : public FieldCodec {
public:
TimeOfDayFieldCodec(const char* field_name) : FieldCodec(field_name) {};
inline PyObject * decode(DxApi::DataReader &reader) {
int32_t result = reader.readTimeOfDay();
if (result != DxApi::Constants::TIMEOFDAY_NULL) {
return PyLong_FromLong(result);
} else {
Py_RETURN_NONE;
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
int32_t value;
bool type_mismatch;
bool exists = getInt32Value(field_value, value, type_mismatch);
if (type_mismatch)
THROW_EXCEPTION("Wrong type of field '%s'. Required: INTEGER.", field_name_.c_str());
if (exists) {
writer.writeInterval(value);
} else {
writer.writeInterval(DxApi::Constants::TIMEOFDAY_NULL);
}
}
};
class BinaryFieldCodec : public FieldCodec {
public:
BinaryFieldCodec(const char* field_name) : FieldCodec(field_name) {};
inline PyObject * decode(DxApi::DataReader &reader) {
bool not_null = reader.readBinary(buffer_);
if (not_null) {
return PyBytes_FromStringAndSize(reinterpret_cast<char*>(buffer_.data()), buffer_.size());
}
else {
Py_RETURN_NONE;
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
if (field_value == Py_None || field_value == NULL) {
writer.writeBinaryArrayNull();
return;
}
if (PyBytes_Check(field_value)) {
uint8_t *bytes = (uint8_t *) PyBytes_AsString(field_value);
size_t size = PyBytes_Size(field_value);
if (bytes == NULL)
writer.writeBinaryArrayNull();
else
writer.writeBinaryArray(bytes, size);
}
else if (PyByteArray_Check(field_value)) {
uint8_t *bytes = (uint8_t *) PyByteArray_AsString(field_value);
if (bytes == NULL)
writer.writeBinaryArrayNull();
else
writer.writeBinaryArray(bytes, PyByteArray_Size(field_value));
}
else {
THROW_EXCEPTION("Wrong type of '%s' field. Required: BYTES.", field_name_.c_str());
}
}
private:
std::vector<uint8_t> buffer_;
};
class BooleanFieldCodec : public FieldCodec {
public:
BooleanFieldCodec(const char* field_name, bool nullable) : FieldCodec(field_name), nullable(nullable) {};
inline PyObject * decode(DxApi::DataReader &reader) {
if (nullable) {
uint8_t result = reader.readNullableBooleanInt8();
if (result == DxApi::Constants::BOOL_TRUE) {
Py_RETURN_TRUE;
} else if (result == DxApi::Constants::BOOL_FALSE) {
Py_RETURN_FALSE;
} else {
Py_RETURN_NONE;
}
} else {
if (reader.readBoolean())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
bool ret_value;
bool exists = getBooleanValue(field_value, ret_value);
if (exists) {
writer.writeBoolean(ret_value);
} else {
writer.writeNullableBoolean(false, true);
}
}
protected:
bool nullable;
};
class CharFieldCodec : public FieldCodec {
public:
CharFieldCodec(const char* field_name) : FieldCodec(field_name) { };
inline PyObject * decode(DxApi::DataReader &reader) {
const wchar_t ch = reader.readWChar();
if (ch != DxApi::Constants::CHAR_NULL) {
return PyUnicode_FromOrdinal(ch); /*PyUnicode_FromWideChar(&ch, 1)*/
} else {
Py_RETURN_NONE;
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
if (field_value == NULL || Py_None == field_value) {
writer.writeWChar(DxApi::Constants::CHAR_NULL);
} else {
if (PyUnicode_Check(field_value)) {
std::wstring str;
str.resize(PyUnicode_GetSize(field_value) + 1, 0);
int len = (int)PyUnicode_AsWideChar(
#if PY_VERSION_HEX < 0x03020000
(PyUnicodeObject *)
#endif
field_value, &str[0], (Py_ssize_t)str.size());
if (len > -1)
{
assert(len < (int)str.size());
str[len] = 0;
}
else str[str.size() - 1] = 0;
writer.writeWChar(str[0]);
} else {
writer.writeWChar(DxApi::Constants::CHAR_NULL);
}
}
}
};
class Utf8FieldCodec : public FieldCodec {
public:
Utf8FieldCodec(const char* field_name) : FieldCodec(field_name) { };
inline PyObject * decode(DxApi::DataReader &reader) {
bool hasField = reader.readUTF8(buffer);
if (hasField) {
return PyUnicode_FromString(buffer.c_str());
} else {
Py_RETURN_NONE;
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
if (Py_None == field_value || field_value == NULL) {
writer.writeUTF8((const char *) NULL, 0);
} else {
if (PyUnicode_Check(field_value)) {
std::wstring str;
str.resize(PyUnicode_GetSize(field_value) + 1, 0);
int len = (int)PyUnicode_AsWideChar(
#if PY_VERSION_HEX < 0x03020000
(PyUnicodeObject *)
#endif
field_value, &str[0], (Py_ssize_t)str.size());
if (len > -1)
{
assert(len < (int)str.size());
str[len] = 0;
} else
str[str.size() - 1] = 0;
writer.writeUTF8(str);
} else {
writer.writeUTF8((const char *)NULL, 0);
}
}
}
private:
std::string buffer;
};
class AsciiFieldCodec : public FieldCodec {
public:
AsciiFieldCodec(const char* field_name) : FieldCodec(field_name) { };
inline PyObject * decode(DxApi::DataReader &reader) {
bool hasField = reader.readAscii(buffer);
if (hasField) {
return PyUnicode_FromString(buffer.c_str());
}
else {
Py_RETURN_NONE;
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
if (Py_None == field_value || field_value == NULL) {
writer.writeAscii((const char *)NULL, 0);
}
else {
if (PyUnicode_Check(field_value)) {
std::wstring str;
str.resize(PyUnicode_GetSize(field_value) + 1, 0);
int len = (int)PyUnicode_AsWideChar(
#if PY_VERSION_HEX < 0x03020000
(PyUnicodeObject *)
#endif
field_value, &str[0], (Py_ssize_t)str.size());
if (len > -1)
{
assert(len < (int)str.size());
str[len] = 0;
}
else
str[str.size() - 1] = 0;
writer.writeAscii(str);
}
else {
writer.writeAscii((const char *)NULL, 0);
}
}
}
private:
std::string buffer;
};
class EnumFieldCodec : public FieldCodec {
public:
EnumFieldCodec(const char* field_name, const Schema::TickDbClassDescriptor &descriptor)
: FieldCodec(field_name), descriptor_(descriptor) {
};
inline PyObject * decode(DxApi::DataReader &reader) {
switch (descriptor_.enumType) {
case Schema::FieldTypeEnum::ENUM8: {
int8_t result = reader.readEnum8();
if (result != DxApi::Constants::ENUM_NULL) {
if (result < 0 || result >= descriptor_.enumSymbols.size())
THROW_EXCEPTION("Enum value out of bound for '%s' field.", field_name_.c_str());
return PyUnicode_FromString(descriptor_.enumSymbols[result].c_str());
} else {
Py_RETURN_NONE;
}
}
break;
case Schema::FieldTypeEnum::ENUM16: {
int16_t result = reader.readEnum16();
if (result != DxApi::ENUM_NULL) {
if (result < 0 || result >= descriptor_.enumSymbols.size())
THROW_EXCEPTION("Enum value out of bound for '%s' field.", field_name_.c_str());
return PyUnicode_FromString(descriptor_.enumSymbols[result].c_str());
} else {
Py_RETURN_NONE;
}
}
break;
case Schema::FieldTypeEnum::ENUM32: {
int32_t result = reader.readEnum32();
if (result != DxApi::Constants::ENUM_NULL) {
if (result < 0 || result >= descriptor_.enumSymbols.size())
THROW_EXCEPTION("Enum value out of bound for '%s' field.", field_name_.c_str());
return PyUnicode_FromString(descriptor_.enumSymbols[result].c_str());
} else {
Py_RETURN_NONE;
}
}
case Schema::FieldTypeEnum::ENUM64: {
int64_t result = reader.readEnum64();
if (result != DxApi::Constants::ENUM_NULL) {
if (result < 0 || result >= (int64_t) descriptor_.enumSymbols.size())
THROW_EXCEPTION("Enum value out of bound for '%s' field.", field_name_.c_str());
return PyUnicode_FromString(descriptor_.enumSymbols[result].c_str());
} else {
Py_RETURN_NONE;
}
}
default:
THROW_EXCEPTION("Unknow type of enum for '%s' field.", field_name_.c_str());
}
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
bool type_mismatch;
bool exists = getStringValue(field_value, buffer_, type_mismatch);
if (type_mismatch)
THROW_EXCEPTION("Wrong type of field '%s'. Required: STRING.", field_name_.c_str());
if (exists) {
auto it = descriptor_.symbolToEnumValue.find(buffer_);
if (it == descriptor_.symbolToEnumValue.end())
THROW_EXCEPTION("Unknown enum value '%s' of field '%s'", buffer_.c_str(), field_name_.c_str());
switch (descriptor_.enumType) {
case Schema::FieldTypeEnum::ENUM8:
writer.writeEnum8(descriptor_.symbolToEnumValue[buffer_]);
break;
case Schema::FieldTypeEnum::ENUM16:
writer.writeEnum16(descriptor_.symbolToEnumValue[buffer_]);
break;
case Schema::FieldTypeEnum::ENUM32:
writer.writeEnum32(descriptor_.symbolToEnumValue[buffer_]);
break;
case Schema::FieldTypeEnum::ENUM64:
writer.writeEnum64(descriptor_.symbolToEnumValue[buffer_]);
break;
default:
THROW_EXCEPTION("Unknow type of enum for '%s' field.", field_name_.c_str());
}
} else {
switch (descriptor_.enumType) {
case Schema::FieldTypeEnum::ENUM8:
writer.writeEnum8(DxApi::Constants::ENUM_NULL);
break;
case Schema::FieldTypeEnum::ENUM16:
writer.writeEnum16(DxApi::Constants::ENUM_NULL);
break;
case Schema::FieldTypeEnum::ENUM32:
writer.writeEnum32(DxApi::Constants::ENUM_NULL);
break;
case Schema::FieldTypeEnum::ENUM64:
writer.writeEnum64(DxApi::Constants::ENUM_NULL);
break;
default:
THROW_EXCEPTION("Unknow type of enum for '%s' field.", field_name_.c_str());
}
}
}
protected:
std::string buffer_;
Schema::TickDbClassDescriptor descriptor_;
};
class ArrayFieldCodec : public FieldCodec {
public:
ArrayFieldCodec(const char* field_name, FieldCodecPtr element_codec)
: FieldCodec(field_name), element_codec_(element_codec) {
};
inline PyObject * decode(DxApi::DataReader &reader) {
int32_t len = reader.readArrayStart();
if (len == DxApi::Constants::INT32_NULL)
Py_RETURN_NONE;
PyObject *list = PyList_New(len);
for (int i = 0; i < len; ++i) {
PyObject *element = element_codec_->decode(reader);
PyList_SetItem(list, i, element);
}
reader.readArrayEnd();
return list;
}
inline void encode(PyObject *field_value, DxApi::DataWriter &writer) {
if (field_value == NULL) {
writer.writeArrayNull();
return;
}
if (PyList_Check(field_value)) {
Py_ssize_t size = PyList_Size(field_value);
writer.writeArrayStart(size);
for (int i = 0; i < size; i++) {
element_codec_->encode(PyList_GetItem(field_value, i), writer);
}
writer.writeArrayEnd();
} else {
if (field_value == Py_None) {
writer.writeArrayNull();
} else {
THROW_EXCEPTION("Wrong type of field '%s'. Required: ARRAY.", field_name_.c_str());
}
}
}
private:
FieldCodecPtr element_codec_;
};
class ObjectFieldCodec : public FieldCodec {
public:
ObjectFieldCodec(
const char* field_name, PythonDxApiModule *dxapi_module,
std::vector<std::string> types, std::vector<MessageCodecPtr> codecs)
: FieldCodec(field_name), dxapi_module_(dxapi_module), types_(types), codecs_(codecs)
{
for (int i = 0; i < types.size(); ++i) {
type_name_to_id_[types[i]] = i;
}
};
inline PyObject * decode(DxApi::DataReader &reader) {
int32_t type_id = reader.readObjectStart();
if (type_id == DxApi::Constants::INT32_NULL)
Py_RETURN_NONE;
if (type_id < 0 || type_id >= codecs_.size())
THROW_EXCEPTION("Can't find codec of type id '%d' for field: %s.", type_id, field_name_.c_str());
if (dxapi_module_ == NULL)
THROW("DxApi module is not initialized for object codec.");
PyObject *object = dxapi_module_->newInstrumentMessageObject();
codecs_[type_id]->decode(object, reader);
reader.readObjectEnd();
PythonRefHolder type_name_obj(PyUnicode_FromString(types_[type_id].c_str()));
PyObject_SetAttrString(object, TYPE_NAME_PROPERTY.c_str(), type_name_obj.getReference());
return object;
}
inline void encode(PyObject *message, DxApi::DataWriter &writer) {
if (message == NULL || message == Py_None) {
writer.writeObjectNull();
return;
}
int32_t type_id = getTypeId(message);
writer.writeObjectStart(type_id);
codecs_[type_id]->encode(message, writer);
writer.writeObjectEnd();
}
int32_t getTypeId(PyObject *message) {
if (types_.size() == 1)
return 0;
std::string type_name;
bool exists = getStringValue(message, TYPE_NAME_PROPERTY, TYPE_NAME_PROPERTY1, type_name);
if (!exists)
THROW_EXCEPTION("Unkown type of object. Specify '%s' attribute for field '%s'.",
TYPE_NAME_PROPERTY.c_str(), field_name_.c_str());
auto type_id_it = type_name_to_id_.find(type_name);
if (type_id_it == type_name_to_id_.end())
THROW_EXCEPTION("Unknown type '%s' of field '%s'.",
type_name.c_str(), field_name_.c_str());
int32_t type_id = type_id_it->second;
if (type_id < 0 || type_id >= codecs_.size())
THROW_EXCEPTION("Can't find codec for type '%s' of field '%s'",
type_name.c_str(), field_name_.c_str());
return type_id;
}
private:
PythonDxApiModule *dxapi_module_;
std::vector<std::string> types_;
std::vector<MessageCodecPtr> codecs_;
std::unordered_map<std::string, int32_t> type_name_to_id_;
};
}
}
#endif //DELTIX_API_DECODERS_FIELD_DECODERS_H_ | [
"rkisel@deltixlab.com"
] | rkisel@deltixlab.com |
f4b431813604b1d8b42932a25442cae6d7b100ef | 6782fa623e13377e3dfdc26efb8c5cc12ea1d273 | /MyLearnCPP01/_06_02_PassingArgumentsByAdress.cpp | 6db6f56696249bd1a0fa2b4aa23b2fb7a4378a42 | [] | no_license | HHHHHHHHHHHHHHHHHHHHHCS/MyLearnCPP01 | a73e6b5f354493fe9b541eb3c9cab844462e06e0 | 2536bb91d40e7ce252f71d261ba87ca0acbe1a3a | refs/heads/master | 2020-05-25T04:32:48.564949 | 2020-05-11T01:55:35 | 2020-05-11T01:55:35 | 187,627,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49 | cpp | #include "_06_02_PassingArgumentsByAddress.h"
| [
"464962683@qq.com"
] | 464962683@qq.com |
1a47e00bc5fc4fbe708edf32e5cbb3000f8b69b6 | 777a75e6ed0934c193aece9de4421f8d8db01aac | /src/Providers/UNIXProviders/tests/UNIXProviders.Tests/UNIX_BGPClustersInASFixture.h | 7bf0195fd6ccaa02fe310116358fd293230e869e | [
"MIT"
] | permissive | brunolauze/openpegasus-providers-old | 20fc13958016e35dc4d87f93d1999db0eae9010a | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | refs/heads/master | 2021-01-01T20:05:44.559362 | 2014-04-30T17:50:06 | 2014-04-30T17:50:06 | 19,132,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,878 | h | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include "CIMFixtureBase.h"
class UNIX_BGPClustersInASFixture :
public CIMFixtureBase
{
public:
UNIX_BGPClustersInASFixture();
~UNIX_BGPClustersInASFixture();
virtual void Run();
};
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
7ff0f739eaeb2b2d7c0d683644cd2a011525bfb7 | 049baa7029a6b614066d61064a74d05324c2e614 | /adevs/adevs-2.8.1/examples/smart_grid/main_2bus.cpp | 940c6b1d6b3a8cb15c1ec18093e88bfc88ccc2b9 | [
"BSD-2-Clause-Views"
] | permissive | nicolascofrer/inter-sector-model | 79a3ab24d0294a3a8aa6daaa4ff71f5b1db21f55 | 0c92d297636259d729fcd406f2785a5d3ce18550 | refs/heads/master | 2021-02-05T09:03:59.203210 | 2020-02-28T13:02:36 | 2020-02-28T13:02:36 | 243,762,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,671 | cpp | /**
* This model is based on the power system example in Chapter 6
* of "Building Software for Simulation" by J. Nutaro.
*/
#include "adevs.h"
#include <iostream>
#include <fstream>
#include <list>
#define OMC_ADEVS_IO_TYPE adevs::PortValue<double>
#include "twobus.h"
using namespace std;
using namespace adevs;
/**
* Adds the ability to make step adjustments of the base
* load P0 in the two bus model.
*/
class twoBusAdjustableLoad:
public twobus
{
public:
static const int load_event;
static const int control_event;
static const int sensor_event;
twoBusAdjustableLoad():
twobus(),
load_adj_fraction(0.0),
control_adj_fraction(0.0)
{
}
void init(double* q)
{
twobus::init(q);
r0 = get_Load_imp_R();
n = get_Genr_n();
output_event = false;
}
double time_event_func(const double* q)
{
if (output_event) return 0.0;
else return twobus::time_event_func(q);
}
void internal_event(double* q, const bool* state_event)
{
twobus::internal_event(q,state_event);
output_event = n != get_Genr_n();
n = get_Genr_n();
}
void confluent_event(double* q, const bool* state_event,
Bag<OMC_ADEVS_IO_TYPE>& xb)
{
internal_event(q,state_event);
external_event(q,0.0,xb);
}
void external_event(double* q, double e,
const Bag<OMC_ADEVS_IO_TYPE>& xb)
{
Bag<OMC_ADEVS_IO_TYPE>::const_iterator iter;
for (iter = xb.begin(); iter != xb.end(); iter++)
{
if ((*iter).port == load_event)
load_adj_fraction = (*iter).value;
else
control_adj_fraction = (*iter).value;
}
set_Load_imp_R(
(1.0+load_adj_fraction+control_adj_fraction)*r0);
update_vars(q,true);
}
void output_func(const double* q, const bool* state_event,
Bag<OMC_ADEVS_IO_TYPE>& yb)
{
if (output_event)
{
yb.insert(OMC_ADEVS_IO_TYPE(sensor_event,
n*get_Genr_freqInterval()/get_Genr_nomFreq()));
}
}
private:
double r0;
double load_adj_fraction, control_adj_fraction;
int n;
bool output_event;
};
const int twoBusAdjustableLoad::load_event = 0;
const int twoBusAdjustableLoad::control_event = 1;
const int twoBusAdjustableLoad::sensor_event = 2;
/**
* Instigate a step change in load.
*/
class StepLoad:
public Atomic<OMC_ADEVS_IO_TYPE>
{
public:
const static int load_event;
StepLoad():
Atomic<OMC_ADEVS_IO_TYPE>(),
when(1.0),
stepsize(0.01)
{
}
void delta_int() { when = DBL_MAX; }
void delta_ext(double,const Bag<OMC_ADEVS_IO_TYPE>&){}
void delta_conf(const Bag<OMC_ADEVS_IO_TYPE>&){}
void output_func(Bag<OMC_ADEVS_IO_TYPE>& yb)
{
yb.insert(OMC_ADEVS_IO_TYPE(load_event,stepsize));
}
double ta() { return when; }
void gc_output(Bag<OMC_ADEVS_IO_TYPE>&){}
private:
double when;
const double stepsize;
};
const int StepLoad::load_event = 0;
/**
* Communication channel that carries the sensor
* signal to the actuator at the load. This model
* passes on unchanged the port value pairs that
* it receives.
*/
class Comm:
public Atomic<OMC_ADEVS_IO_TYPE>
{
public:
Comm():
Atomic<OMC_ADEVS_IO_TYPE>(),
msg_rate(100.0),
ttg(DBL_MAX)
{
}
void delta_int()
{
q.pop_front();
if (!q.empty())
ttg = 1.0/msg_rate;
else
ttg = DBL_MAX;
}
void delta_ext(double e, const Bag<OMC_ADEVS_IO_TYPE>& xb)
{
Bag<OMC_ADEVS_IO_TYPE>::const_iterator iter;
for (iter = xb.begin(); iter != xb.end(); iter++)
q.push_back(*iter);
if (ttg < DBL_MAX) ttg -= e;
else ttg = 1.0/msg_rate;
}
void delta_conf(const Bag<OMC_ADEVS_IO_TYPE>& xb)
{
delta_int();
delta_ext(0.0,xb);
}
void output_func(Bag<OMC_ADEVS_IO_TYPE>& yb)
{
yb.insert(q.front());
}
double ta() { return ttg; }
void gc_output(Bag<OMC_ADEVS_IO_TYPE>&){}
private:
const double msg_rate;
double ttg;
list<OMC_ADEVS_IO_TYPE> q;
};
/**
* Calculate the control signal from a sensor
* event.
*/
class Control:
public Atomic<OMC_ADEVS_IO_TYPE>
{
public:
const static int control_event;
const static int sensor_event;
Control():
Atomic<OMC_ADEVS_IO_TYPE>(),
sig(0.0),
act(false),
gain(10.0)
{
}
void delta_int() { act = false; }
void delta_ext(double,const Bag<OMC_ADEVS_IO_TYPE>& xb)
{
sig = (*(xb.begin())).value;
act = true;
}
void delta_conf(const Bag<OMC_ADEVS_IO_TYPE>& xb)
{
delta_int();
delta_ext(0.0,xb);
}
void output_func(Bag<OMC_ADEVS_IO_TYPE>& yb)
{
yb.insert(OMC_ADEVS_IO_TYPE(control_event,-sig*gain));
}
double ta()
{
if (act) return 0.0;
else return DBL_MAX;
}
void gc_output(Bag<OMC_ADEVS_IO_TYPE>&){}
private:
double sig;
bool act;
const double gain;
};
const int Control::control_event = 0;
const int Control::sensor_event = 1;
/**
* Model that connects the above two.
*/
class SmartGrid:
public Digraph<double>
{
public:
SmartGrid():
Digraph<double>(),
fout("soln")
{
pwr_sys = new twoBusAdjustableLoad();
Hybrid<OMC_ADEVS_IO_TYPE>* hybrid_model =
new Hybrid<OMC_ADEVS_IO_TYPE>(
pwr_sys,
new rk_45<OMC_ADEVS_IO_TYPE>(pwr_sys,1E-4,0.01),
new linear_event_locator<OMC_ADEVS_IO_TYPE>(pwr_sys,1E-5));
StepLoad* step_load = new StepLoad();
Control* control = new Control();
Comm* comm = new Comm();
add(hybrid_model);
add(step_load);
add(control);
add(comm);
couple(step_load,step_load->load_event,
hybrid_model,pwr_sys->load_event);
couple(control,control->control_event,
hybrid_model,pwr_sys->control_event);
couple(hybrid_model,pwr_sys->sensor_event,
comm,pwr_sys->sensor_event);
couple(comm,pwr_sys->sensor_event,
control,control->sensor_event);
}
void print_vars(double t);
~SmartGrid() { fout.close(); }
private:
twoBusAdjustableLoad* pwr_sys;
ofstream fout;
};
void SmartGrid::print_vars(double t)
{
if (t == 0)
{
fout << "# t,w,Pm,Pe,Ef,theta,,T1.va,T1.vb,V,V0" << endl;
}
fout << t << " "
<< pwr_sys->get_Genr_w()*pwr_sys->get_Genr_nomFreq() << " "
<< pwr_sys->get_Genr_n()*pwr_sys->get_Genr_freqInterval() << " "
<< pwr_sys->get_Genr_Pm() << " "
<< pwr_sys->get_Genr_Pe() << " "
<< pwr_sys->get_Genr_Ef() << " "
<< pwr_sys->get_Genr_theta() << " "
<< pwr_sys->get_L12_T1_va() << " "
<< pwr_sys->get_L12_T1_vb() << " "
<< pwr_sys->get_Genr_V() << " "
<< pwr_sys->get_Genr_V0() << " "
<< endl;
}
int main()
{
SmartGrid* model = new SmartGrid();
// Create the simulator
Simulator<OMC_ADEVS_IO_TYPE>* sim =
new Simulator<OMC_ADEVS_IO_TYPE>(model);
model->print_vars(0);
while (sim->nextEventTime() <= 20.0)
{
double t = sim->nextEventTime();
sim->execNextEvent();
model->print_vars(t);
}
delete sim;
delete model;
return 0;
}
| [
"nicolas.cofre@gatech.edu"
] | nicolas.cofre@gatech.edu |
c63fd37cb116cf97c8c95e1fc9a8d1b81ee7bcb3 | 9620c8e0ca242f056af639a6501a3729e03fc13d | /VaporPlus/DXSampleHelper.h | edd967f7775ee206215dac79c6e5a865ae632277 | [
"MIT"
] | permissive | clandrew/vapor | 2c405bf063e24bb6346b6b6eed94020ff9cbc680 | 500ef1ac43f7b72499914ccad2306037fc7d96b9 | refs/heads/master | 2021-06-20T23:54:32.338340 | 2021-02-02T06:14:41 | 2021-02-02T06:14:41 | 179,010,582 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,716 | h | #pragma once
#include <stdexcept>
// Note that while ComPtr is used to manage the lifetime of resources on the CPU,
// it has no understanding of the lifetime of resources on the GPU. Apps must account
// for the GPU lifetime of resources to avoid destroying objects that may still be
// referenced by the GPU.
using Microsoft::WRL::ComPtr;
class HrException : public std::runtime_error
{
inline std::string HrToString(HRESULT hr)
{
char s_str[64] = {};
sprintf_s(s_str, "HRESULT of 0x%08X", static_cast<UINT>(hr));
return std::string(s_str);
}
public:
HrException(HRESULT hr) : std::runtime_error(HrToString(hr)), m_hr(hr) {}
HRESULT Error() const { return m_hr; }
private:
const HRESULT m_hr;
};
#define SAFE_RELEASE(p) if (p) (p)->Release()
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
throw HrException(hr);
}
}
inline void ThrowIfFailed(HRESULT hr, const wchar_t* msg)
{
if (FAILED(hr))
{
OutputDebugString(msg);
throw HrException(hr);
}
}
inline void ThrowIfFalse(bool value)
{
ThrowIfFailed(value ? S_OK : E_FAIL);
}
inline void ThrowIfFalse(bool value, const wchar_t* msg)
{
ThrowIfFailed(value ? S_OK : E_FAIL, msg);
}
inline void GetAssetsPath(_Out_writes_(pathSize) WCHAR* path, UINT pathSize)
{
if (path == nullptr)
{
throw std::exception();
}
DWORD size = GetModuleFileName(nullptr, path, pathSize);
if (size == 0 || size == pathSize)
{
// Method failed or path was truncated.
throw std::exception();
}
WCHAR* lastSlash = wcsrchr(path, L'\\');
if (lastSlash)
{
*(lastSlash + 1) = L'\0';
}
}
inline HRESULT ReadDataFromFile(LPCWSTR filename, byte** data, UINT* size)
{
using namespace Microsoft::WRL;
CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {};
extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
extendedParams.lpSecurityAttributes = nullptr;
extendedParams.hTemplateFile = nullptr;
Wrappers::FileHandle file(CreateFile2(filename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &extendedParams));
if (file.Get() == INVALID_HANDLE_VALUE)
{
throw std::exception();
}
FILE_STANDARD_INFO fileInfo = {};
if (!GetFileInformationByHandleEx(file.Get(), FileStandardInfo, &fileInfo, sizeof(fileInfo)))
{
throw std::exception();
}
if (fileInfo.EndOfFile.HighPart != 0)
{
throw std::exception();
}
*data = reinterpret_cast<byte*>(malloc(fileInfo.EndOfFile.LowPart));
*size = fileInfo.EndOfFile.LowPart;
if (!ReadFile(file.Get(), *data, fileInfo.EndOfFile.LowPart, nullptr, nullptr))
{
throw std::exception();
}
return S_OK;
}
// Assign a name to the object to aid with debugging.
#if defined(_DEBUG) || defined(DBG)
inline void SetName(ID3D12Object* pObject, LPCWSTR name)
{
pObject->SetName(name);
}
inline void SetNameIndexed(ID3D12Object* pObject, LPCWSTR name, UINT index)
{
WCHAR fullName[50];
if (swprintf_s(fullName, L"%s[%u]", name, index) > 0)
{
pObject->SetName(fullName);
}
}
#else
inline void SetName(ID3D12Object*, LPCWSTR)
{
}
inline void SetNameIndexed(ID3D12Object*, LPCWSTR, UINT)
{
}
#endif
// Naming helper for ComPtr<T>.
// Assigns the name of the variable as the name of the object.
// The indexed variant will include the index in the name of the object.
#define NAME_D3D12_OBJECT(x) SetName((x).Get(), L#x)
#define NAME_D3D12_OBJECT_INDEXED(x, n) SetNameIndexed((x)[n].Get(), L#x, n)
inline UINT Align(UINT size, UINT alignment)
{
return (size + (alignment - 1)) & ~(alignment - 1);
}
inline UINT CalculateConstantBufferByteSize(UINT byteSize)
{
// Constant buffer size is required to be aligned.
return Align(byteSize, D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT);
}
#ifdef D3D_COMPILE_STANDARD_FILE_INCLUDE
inline Microsoft::WRL::ComPtr<ID3DBlob> CompileShader(
const std::wstring& filename,
const D3D_SHADER_MACRO* defines,
const std::string& entrypoint,
const std::string& target)
{
UINT compileFlags = 0;
#if defined(_DEBUG) || defined(DBG)
compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
HRESULT hr;
Microsoft::WRL::ComPtr<ID3DBlob> byteCode = nullptr;
Microsoft::WRL::ComPtr<ID3DBlob> errors;
hr = D3DCompileFromFile(filename.c_str(), defines, D3D_COMPILE_STANDARD_FILE_INCLUDE,
entrypoint.c_str(), target.c_str(), compileFlags, 0, &byteCode, &errors);
if (errors != nullptr)
{
OutputDebugStringA((char*)errors->GetBufferPointer());
}
ThrowIfFailed(hr);
return byteCode;
}
#endif
// Resets all elements in a ComPtr array.
template<class T>
void ResetComPtrArray(T* comPtrArray)
{
for (auto &i : *comPtrArray)
{
i.Reset();
}
}
// Resets all elements in a unique_ptr array.
template<class T>
void ResetUniquePtrArray(T* uniquePtrArray)
{
for (auto &i : *uniquePtrArray)
{
i.reset();
}
}
class GpuUploadBuffer
{
public:
ComPtr<ID3D12Resource> GetResource() { return m_resource; }
protected:
ComPtr<ID3D12Resource> m_resource;
GpuUploadBuffer() {}
~GpuUploadBuffer()
{
if (m_resource.Get())
{
m_resource->Unmap(0, nullptr);
}
}
void Allocate(ID3D12Device* device, UINT bufferSize, LPCWSTR resourceName = nullptr)
{
auto uploadHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
auto bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(bufferSize);
ThrowIfFailed(device->CreateCommittedResource(
&uploadHeapProperties,
D3D12_HEAP_FLAG_NONE,
&bufferDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&m_resource)));
m_resource->SetName(resourceName);
}
uint8_t* MapCpuWriteOnly()
{
uint8_t* mappedData;
// We don't unmap this until the app closes. Keeping buffer mapped for the lifetime of the resource is okay.
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU.
ThrowIfFailed(m_resource->Map(0, &readRange, reinterpret_cast<void**>(&mappedData)));
return mappedData;
}
};
struct D3DBuffer
{
ComPtr<ID3D12Resource> resource;
D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorHandle;
D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorHandle;
};
// Helper class to create and update a constant buffer with proper constant buffer alignments.
// Usage: ToDo
// ConstantBuffer<...> cb;
// cb.Create(...);
// cb.staging.var = ...; | cb->var = ... ;
// cb.CopyStagingToGPU(...);
template <class T>
class ConstantBuffer : public GpuUploadBuffer
{
uint8_t* m_mappedConstantData;
UINT m_alignedInstanceSize;
UINT m_numInstances;
public:
ConstantBuffer() : m_alignedInstanceSize(0), m_numInstances(0), m_mappedConstantData(nullptr) {}
void Create(ID3D12Device* device, UINT numInstances = 1, LPCWSTR resourceName = nullptr)
{
m_numInstances = numInstances;
UINT alignedSize = Align(sizeof(T), D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT);
UINT bufferSize = numInstances * alignedSize;
Allocate(device, bufferSize, resourceName);
m_mappedConstantData = MapCpuWriteOnly();
}
void CopyStagingToGpu(UINT instanceIndex = 0)
{
memcpy(m_mappedConstantData + instanceIndex * m_alignedInstanceSize, &staging, sizeof(T));
}
// Accessors
T staging;
T* operator->() { return &staging; }
UINT NumInstances() { return m_numInstances; }
D3D12_GPU_VIRTUAL_ADDRESS GpuVirtualAddress(UINT instanceIndex = 0)
{
return m_resource->GetGPUVirtualAddress() + instanceIndex * m_alignedInstanceSize;
}
};
// Helper class to create and update a structured buffer.
// Usage: ToDo
// ConstantBuffer<...> cb;
// cb.Create(...);
// cb.staging.var = ...; | cb->var = ... ;
// cb.CopyStagingToGPU(...);
template <class T>
class StructuredBuffer : public GpuUploadBuffer
{
T* m_mappedBuffers;
std::vector<T> m_staging;
UINT m_numInstances;
public:
// Performance tip: Align structures on sizeof(float4) boundary.
// Ref: https://developer.nvidia.com/content/understanding-structured-buffer-performance
static_assert(sizeof(T) % 16 == 0, L"Align structure buffers on 16 byte boundary for performance reasons.");
StructuredBuffer() : m_mappedBuffers(nullptr), m_numInstances(0) {}
void Create(ID3D12Device* device, UINT numElements, UINT numInstances = 1, LPCWSTR resourceName = nullptr)
{
m_staging.resize(numElements);
UINT bufferSize = numInstances * numElements * sizeof(T);
Allocate(device, bufferSize, resourceName);
m_mappedBuffers = reinterpret_cast<T*>(MapCpuWriteOnly());
}
void CopyStagingToGpu(UINT instanceIndex = 0)
{
memcpy(m_mappedBuffers + instanceIndex, &m_staging[0], InstanceSize());
}
// Accessors
T& operator[](UINT elementIndex) { return m_staging[elementIndex]; }
size_t NumElementsPerInstance() { return m_staging.size(); }
UINT NumInstances() { return m_staging.size(); }
size_t InstanceSize() { return NumElementsPerInstance() * sizeof(T); }
D3D12_GPU_VIRTUAL_ADDRESS GpuVirtualAddress(UINT instanceIndex = 0)
{
return m_resource->GetGPUVirtualAddress() + instanceIndex * InstanceSize();
}
}; | [
"cmlandrews@gmail.com"
] | cmlandrews@gmail.com |
bded0d489776c8620b3128ae66531f0aa711b452 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/mutt/gumtree/mutt_old_hunk_173.cpp | 47a305caf909d3d1413a3285887b9be397a4b08d | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | mutt_forward_trailer (out);
return 0;
}
void mutt_make_attribution (CONTEXT *ctx, HEADER *cur, FILE *out)
{
char buffer[STRING];
if (Attribution)
{
mutt_make_string (buffer, sizeof (buffer), Attribution, ctx, cur);
fputs (buffer, out);
fputc ('\n', out);
}
| [
"993273596@qq.com"
] | 993273596@qq.com |
9d89252c39c2e45a2d035872d685fb6bb63a70c7 | 1ec178dc08d90bbbe606faf5416e985430d24b40 | /MyAladdin/Civilian3.h | 3b310983361e944c9885728c5d3d3d31394fa0d9 | [] | no_license | huynhthanhnhan/ProjectGameMegaman | 6307bc09b30fdef3e636f7c0ff276775e4bb64fb | 0cf51773f1bbc247faddbb95d53069a8ab55015f | refs/heads/master | 2020-04-09T19:45:28.962919 | 2018-12-18T17:55:26 | 2018-12-18T17:55:26 | 160,552,369 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | h | #pragma once
#ifndef __CIVILIAN3_H__
#define __CIVILIAN3_H__
#include"Enemy.h"
#define V_CIVILIAN3 3
#define W_CIVILIAN3_NORMAL 80
#define H_CIVILIAN3_NORMAL 130
#define D_ATTACK_CIVILIAN3 80
class Civilian3
:public Enemy
{
private:
int _maxStand;
public:
Civilian3(int xRegion, int yRegion, int widthRegion, int heightRegion, Global::EDirection direct);
~Civilian3();
// Inherited via Enemy
virtual bool isAttack() override;
virtual void update(float deltaTime) override;
virtual void Refresh() override;
private:
virtual void LoadResource() override;
virtual void UpdateRender(Global::EState currentState) override;
virtual void DetermineDirection(Global::EState state, Global::EDirection direct);
};
#endif __CIVILIAN3_H__ | [
"15520564@gm.uit.edu.vn"
] | 15520564@gm.uit.edu.vn |
590e5629cc0f983ecf8a702a3224094e120f9f8e | c0257c61d3ed7169e31d1108a81042909a50ddf4 | /src/init.cpp | afb9d2a8d78d4e5cd588faf5eacf9312451e8a72 | [
"MIT"
] | permissive | Piratesdev/Piratescoin | 8c3f787286c73ece544ab96482f5af1101917684 | 95626f84e456023f2b57f1fe4723e7472b481b75 | refs/heads/master | 2016-09-05T13:40:27.920924 | 2014-11-20T04:30:02 | 2014-11-20T04:30:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,891 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
// Used to pass flags to the Bind() function
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1)
};
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
static CCoinsViewDB *pcoinsdbview;
void Shutdown()
{
printf("Shutdown : In progress...\n");
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) return;
RenameThread("piratescoin-shutoff");
nTransactionsUpdated++;
StopRPCThreads();
bitdb.Flush(false);
StopNode();
{
LOCK(cs_main);
if (pwalletMain)
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
if (pblocktree)
pblocktree->Flush();
if (pcoinsTip)
pcoinsTip->Flush();
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pblocktree; pblocktree = NULL;
}
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
delete pwalletMain;
printf("Shutdown : done\n");
}
//
// Signal handlers are very limited in what they are allowed to do, so:
//
void DetectShutdownThread(boost::thread_group* threadGroup)
{
// Tell the main threads to shutdown.
while (!fRequestShutdown)
{
MilliSleep(200);
if (fRequestShutdown)
threadGroup->interrupt_all();
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/piratescoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to piratescoind / RPC client
std::string strUsage = _("Piratescoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" piratescoind [options] " + "\n" +
" piratescoind [options] <command> [params] " + _("Send command to -server or piratescoind") + "\n" +
" piratescoind [options] help " + _("List commands") + "\n" +
" piratescoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "piratescoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !defined(WIN32)
fDaemon = GetBoolArg("-daemon");
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect piratescoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: piratescoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: piratescoind.pid)") + "\n" +
" -gen " + _("Generate coins (default: 0)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 14857)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 14856)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
#ifndef QT_GUI
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
#endif
" -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" +
" -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" +
" -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" +
" -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Piratescoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("piratescoin-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
FILE *file = OpenBlockFile(pos, true);
if (!file)
break;
printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
printf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
printf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
printf("Importing %s...\n", path.string().c_str());
LoadExternalBlockFile(file);
}
}
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
{
return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
}
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
fTestNet = false;
SetGenesisHash();
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
fBenchmark = GetBoolArg("-benchmark");
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", 0);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps", true);
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-mintxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
}
if (mapArgs.count("-minrelaytxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Piratescoin is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("Piratescoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Using data directory %s\n", strDataDir.c_str());
printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "Piratescoin server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
int64 nStart;
// ********************************************************* Step 5: verify wallet database integrity
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
return false;
}
if (filesystem::exists(GetDataDir() / "wallet.dat"))
{
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
bool fBound = false;
if (!fNoListen) {
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
#endif
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load block chain
fReindex = GetBoolArg("-reindex");
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = GetArg("-dbcache", 25) << 20;
if (nTotalCache < (1 << 22))
nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex)
pblocktree->WriteReindexing(true);
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (!VerifyDB()) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
return false;
}
} else {
return InitError(strLoadError);
}
}
}
if (mapArgs.count("-txindex") && fTxIndex != GetBoolArg("-txindex", false))
return InitError(_("You need to rebuild the databases using -reindex to change -txindex"));
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Step 8: load wallet
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet("wallet.dat");
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Piratescoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart Piratescoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ConnectBestBlock(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
StartNode(threadGroup);
if (fServer)
StartRPCThreads();
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
return !fRequestShutdown;
}
| [
"root@kepler1.(none)"
] | root@kepler1.(none) |
9d55d90ed33939acd9b1b66370673237d025ed8f | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/built-in/audio/Wenet_Conformer_for_Pytorch/runtime/core/kaldi/fstext/fstext-utils.h | b0aed022be814dbe88dd8f4ec572b7695e0e5874 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | C++ | false | false | 18,143 | h | // fstext/fstext-utils.h
// Copyright 2009-2011 Microsoft Corporation
// 2012-2013 Johns Hopkins University (Author: Daniel Povey)
// 2013 Guoguo Chen
// 2014 Telepoint Global Hosting Service, LLC. (Author: David
// Snyder)
// See ../../COPYING for clarification regarding multiple 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#ifndef KALDI_FSTEXT_FSTEXT_UTILS_H_
#define KALDI_FSTEXT_FSTEXT_UTILS_H_
#include <fst/fst-decl.h>
#include <fst/fstlib.h>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include "fstext/determinize-star.h"
#include "fstext/remove-eps-local.h"
#include "base/kaldi-common.h" // for error reporting macros.
#include "util/text-utils.h" // for SplitStringToVector
#include "fst/script/print-impl.h"
namespace fst {
/// Returns the highest numbered output symbol id of the FST (or zero
/// for an empty FST.
template <class Arc>
typename Arc::Label HighestNumberedOutputSymbol(const Fst<Arc> &fst);
/// Returns the highest numbered input symbol id of the FST (or zero
/// for an empty FST.
template <class Arc>
typename Arc::Label HighestNumberedInputSymbol(const Fst<Arc> &fst);
/// Returns the total number of arcs in an FST.
template <class Arc>
typename Arc::StateId NumArcs(const ExpandedFst<Arc> &fst);
/// GetInputSymbols gets the list of symbols on the input of fst
/// (including epsilon, if include_eps == true), as a sorted, unique
/// list.
template <class Arc, class I>
void GetInputSymbols(const Fst<Arc> &fst, bool include_eps,
std::vector<I> *symbols);
/// GetOutputSymbols gets the list of symbols on the output of fst
/// (including epsilon, if include_eps == true)
template <class Arc, class I>
void GetOutputSymbols(const Fst<Arc> &fst, bool include_eps,
std::vector<I> *symbols);
/// ClearSymbols sets all the symbols on the input and/or
/// output side of the FST to zero, as specified.
/// It does not alter the symbol tables.
template <class Arc>
void ClearSymbols(bool clear_input, bool clear_output, MutableFst<Arc> *fst);
template <class I>
void GetSymbols(const SymbolTable &symtab, bool include_eps,
std::vector<I> *syms_out);
inline void DeterminizeStarInLog(VectorFst<StdArc> *fst, float delta = kDelta,
bool *debug_ptr = NULL, int max_states = -1);
// e.g. of using this function: PushInLog<REWEIGHT_TO_INITIAL>(fst,
// kPushWeights|kPushLabels);
template <ReweightType rtype> // == REWEIGHT_TO_{INITIAL, FINAL}
void PushInLog(VectorFst<StdArc> *fst, uint32 ptype, float delta = kDelta) {
// PushInLog pushes the FST
// and returns a new pushed FST (labels and weights pushed to the left).
VectorFst<LogArc> *fst_log =
new VectorFst<LogArc>; // Want to determinize in log semiring.
Cast(*fst, fst_log);
VectorFst<StdArc> tmp;
*fst = tmp; // free up memory.
VectorFst<LogArc> *fst_pushed_log = new VectorFst<LogArc>;
Push<LogArc, rtype>(*fst_log, fst_pushed_log, ptype, delta);
Cast(*fst_pushed_log, fst);
delete fst_log;
delete fst_pushed_log;
}
// Minimizes after encoding; applicable to all FSTs. It is like what you get
// from the Minimize() function, except it will not push the weights, or the
// symbols. This is better for our recipes, as we avoid ever pushing the
// weights. However, it will only minimize optimally if your graphs are such
// that the symbols are as far to the left as they can go, and the weights
// in combinable paths are the same... hard to formalize this, but it's
// something that is satisified by our normal FSTs.
template <class Arc>
void MinimizeEncoded(VectorFst<Arc> *fst, float delta = kDelta) {
Map(fst, QuantizeMapper<Arc>(delta));
EncodeMapper<Arc> encoder(kEncodeLabels | kEncodeWeights, ENCODE);
Encode(fst, &encoder);
internal::AcceptorMinimize(fst);
Decode(fst, encoder);
}
/// GetLinearSymbolSequence gets the symbol sequence from a linear FST.
/// If the FST is not just a linear sequence, it returns false. If it is
/// a linear sequence (including the empty FST), it returns true. In this
/// case it outputs the symbol
/// sequences as "isymbols_out" and "osymbols_out" (removing epsilons), and
/// the total weight as "tot_weight". The total weight will be Weight::Zero()
/// if the FST is empty. If any of the output pointers are NULL, it does not
/// create that output.
template <class Arc, class I>
bool GetLinearSymbolSequence(const Fst<Arc> &fst, std::vector<I> *isymbols_out,
std::vector<I> *osymbols_out,
typename Arc::Weight *tot_weight_out);
/// This function converts an FST with a special structure, which is
/// output by the OpenFst functions ShortestPath and RandGen, and converts
/// them into a std::vector of separate FSTs. This special structure is that
/// the only state that has more than one (arcs-out or final-prob) is the
/// start state. fsts_out is resized to the appropriate size.
template <class Arc>
void ConvertNbestToVector(const Fst<Arc> &fst,
std::vector<VectorFst<Arc> > *fsts_out);
/// Takes the n-shortest-paths (using ShortestPath), but outputs
/// the result as a vector of up to n fsts. This function will
/// size the "fsts_out" vector to however many paths it got
/// (which will not exceed n). n must be >= 1.
template <class Arc>
void NbestAsFsts(const Fst<Arc> &fst, size_t n,
std::vector<VectorFst<Arc> > *fsts_out);
/// Creates unweighted linear acceptor from symbol sequence.
template <class Arc, class I>
void MakeLinearAcceptor(const std::vector<I> &labels, MutableFst<Arc> *ofst);
/// Creates an unweighted acceptor with a linear structure, with alternatives
/// at each position. Epsilon is treated like a normal symbol here.
/// Each position in "labels" must have at least one alternative.
template <class Arc, class I>
void MakeLinearAcceptorWithAlternatives(
const std::vector<std::vector<I> > &labels, MutableFst<Arc> *ofst);
/// Does PreDeterminize and DeterminizeStar and then removes the disambiguation
/// symbols. This is a form of determinization that will never blow up. Note
/// that ifst is non-const and can be considered to be destroyed by this
/// operation.
/// Does not do epsilon removal (RemoveEpsLocal)-- this is so it's safe to cast
/// to log and do this, and maintain equivalence in tropical.
template <class Arc>
void SafeDeterminizeWrapper(MutableFst<Arc> *ifst, MutableFst<Arc> *ofst,
float delta = kDelta);
/// SafeDeterminizeMinimizeWapper is as SafeDeterminizeWrapper except that it
/// also minimizes (encoded minimization, which is safe). This algorithm will
/// destroy "ifst".
template <class Arc>
void SafeDeterminizeMinimizeWrapper(MutableFst<Arc> *ifst, VectorFst<Arc> *ofst,
float delta = kDelta);
/// SafeDeterminizeMinimizeWapperInLog is as SafeDeterminizeMinimizeWrapper
/// except it first casts tothe log semiring.
void SafeDeterminizeMinimizeWrapperInLog(VectorFst<StdArc> *ifst,
VectorFst<StdArc> *ofst,
float delta = kDelta);
/// RemoveSomeInputSymbols removes any symbol that appears in "to_remove", from
/// the input side of the FST, replacing them with epsilon.
template <class Arc, class I>
void RemoveSomeInputSymbols(const std::vector<I> &to_remove,
MutableFst<Arc> *fst);
// MapInputSymbols will replace any input symbol i that is between 0 and
// symbol_map.size()-1, with symbol_map[i]. It removes the input symbol
// table of the FST.
template <class Arc, class I>
void MapInputSymbols(const std::vector<I> &symbol_map, MutableFst<Arc> *fst);
template <class Arc>
void RemoveWeights(MutableFst<Arc> *fst);
/// Returns true if and only if the FST is such that the input symbols
/// on arcs entering any given state all have the same value.
/// if "start_is_epsilon", treat start-state as an epsilon input arc
/// [i.e. ensure only epsilon can enter start-state].
template <class Arc>
bool PrecedingInputSymbolsAreSame(bool start_is_epsilon, const Fst<Arc> &fst);
/// This is as PrecedingInputSymbolsAreSame, but with a functor f that maps
/// labels to classes. The function tests whether the symbols preceding any
/// given state are in the same class. Formally, f is of a type F that has an
/// operator of type F::Result F::operator() (F::Arg a) const; where F::Result
/// is an integer type and F::Arc can be constructed from Arc::Label. this must
/// apply to valid labels and also to kNoLabel (so we can have a marker for the
/// invalid labels.
template <class Arc, class F>
bool PrecedingInputSymbolsAreSameClass(bool start_is_epsilon,
const Fst<Arc> &fst, const F &f);
/// Returns true if and only if the FST is such that the input symbols
/// on arcs exiting any given state all have the same value.
/// If end_is_epsilon, treat end-state as an epsilon output arc [i.e. ensure
/// end-states cannot have non-epsilon output transitions.]
template <class Arc>
bool FollowingInputSymbolsAreSame(bool end_is_epsilon, const Fst<Arc> &fst);
template <class Arc, class F>
bool FollowingInputSymbolsAreSameClass(bool end_is_epsilon, const Fst<Arc> &fst,
const F &f);
/// MakePrecedingInputSymbolsSame ensures that all arcs entering any given fst
/// state have the same input symbol. It does this by detecting states
/// that have differing input symbols going in, and inserting, for each of
/// the preceding arcs with non-epsilon input symbol, a new dummy state that
/// has an epsilon link to the fst state.
/// If "start_is_epsilon", ensure that start-state can have only epsilon-links
/// into it.
template <class Arc>
void MakePrecedingInputSymbolsSame(bool start_is_epsilon, MutableFst<Arc> *fst);
/// As MakePrecedingInputSymbolsSame, but takes a functor object that maps
/// labels to classes.
template <class Arc, class F>
void MakePrecedingInputSymbolsSameClass(bool start_is_epsilon,
MutableFst<Arc> *fst, const F &f);
/// MakeFollowingInputSymbolsSame ensures that all arcs exiting any given fst
/// state have the same input symbol. It does this by detecting states that
/// have differing input symbols on arcs that exit it, and inserting, for each
/// of the following arcs with non-epsilon input symbol, a new dummy state that
/// has an input-epsilon link from the fst state. The output symbol and weight
/// stay on the link to the dummy state (in order to keep the FST
/// output-deterministic and stochastic, if it already was). If end_is_epsilon,
/// treat "being a final-state" like having an epsilon output link.
template <class Arc>
void MakeFollowingInputSymbolsSame(bool end_is_epsilon, MutableFst<Arc> *fst);
/// As MakeFollowingInputSymbolsSame, but takes a functor object that maps
/// labels to classes.
template <class Arc, class F>
void MakeFollowingInputSymbolsSameClass(bool end_is_epsilon,
MutableFst<Arc> *fst, const F &f);
/// MakeLoopFst creates an FST that has a state that is both initial and
/// final (weight == Weight::One()), and for each non-NULL pointer fsts[i],
/// it has an arc out whose output-symbol is i and which goes to a
/// sub-graph whose input language is equivalent to fsts[i], where the
/// final-state becomes a transition to the loop-state. Each fst in "fsts"
/// should be an acceptor. The fst MakeLoopFst returns is output-deterministic,
/// but not output-epsilon free necessarily, and arcs are sorted on output
/// label. Note: if some of the pointers in the input vector "fsts" have the
/// same value, "MakeLoopFst" uses this to speed up the computation.
/// Formally: suppose I is the set of indexes i such that fsts[i] != NULL.
/// Let L[i] be the language that the acceptor fsts[i] accepts.
/// Let the language K be the set of input-output pairs i:l such
/// that i in I and l in L[i]. Then the FST returned by MakeLoopFst
/// accepts the language K*, where * is the Kleene closure (CLOSURE_STAR)
/// of K.
/// We could have implemented this via a combination of "project",
/// "concat", "union" and "closure". But that FST would have been
/// less well optimized and would have a lot of final-states.
template <class Arc>
VectorFst<Arc> *MakeLoopFst(const std::vector<const ExpandedFst<Arc> *> &fsts);
/// ApplyProbabilityScale is applicable to FSTs in the log or tropical semiring.
/// It multiplies the arc and final weights by "scale" [this is not the Mul
/// operation of the semiring, it's actual multiplication, which is equivalent
/// to taking a power in the semiring].
template <class Arc>
void ApplyProbabilityScale(float scale, MutableFst<Arc> *fst);
/// EqualAlign is similar to RandGen, but it generates a sequence with exactly
/// "length" input symbols. It returns true on success, false on failure
/// (failure is partly random but should never happen in practice for normal
/// speech models.) It generates a random path through the input FST, finds out
/// which subset of the states it visits along the way have self-loops with
/// inupt symbols on them, and outputs a path with exactly enough self-loops to
/// have the requested number of input symbols. Note that EqualAlign does not
/// use the probabilities on the FST. It just uses equal probabilities in the
/// first stage of selection (since the output will anyway not be a truly random
/// sample from the FST). The input fst "ifst" must be connected or this may
/// enter an infinite loop.
template <class Arc>
bool EqualAlign(const Fst<Arc> &ifst, typename Arc::StateId length,
int rand_seed, MutableFst<Arc> *ofst, int num_retries = 10);
// RemoveUselessArcs removes arcs such that there is no input symbol
// sequence for which the best path through the FST would contain
// those arcs [for these purposes, epsilon is not treated as a real symbol].
// This is mainly geared towards decoding-graph FSTs which may contain
// transitions that have less likely words on them that would never be
// taken. We do not claim that this algorithm removes all such arcs;
// it just does the best job it can.
// Only works for tropical (not log) semiring as it uses
// NaturalLess.
template <class Arc>
void RemoveUselessArcs(MutableFst<Arc> *fst);
// PhiCompose is a version of composition where
// the right hand FST (fst2) is treated as a backoff
// LM, with the phi symbol (e.g. #0) treated as a
// "failure transition", only taken when we don't
// have a match for the requested symbol.
template <class Arc>
void PhiCompose(const Fst<Arc> &fst1, const Fst<Arc> &fst2,
typename Arc::Label phi_label, MutableFst<Arc> *fst);
// PropagateFinal propagates final-probs through
// "phi" transitions (note that here, phi_label may
// be epsilon if you want). If you have a backoff LM
// with special symbols ("phi") on the backoff arcs
// instead of epsilon, you may use PhiCompose to compose
// with it, but this won't do the right thing w.r.t.
// final probabilities. You should first call PropagateFinal
// on the FST with phi's i it (fst2 in PhiCompose above),
// to fix this. If a state does not have a final-prob,
// but has a phi transition, it makes the state's final-prob
// (phi-prob * final-prob-of-dest-state), and does this
// recursively i.e. follows phi transitions on the dest state
// first. It behaves as if there were a super-final state
// with a special symbol leading to it, from each currently
// final state. Note that this may not behave as desired
// if there are epsilons in your FST; it might be better
// to remove those before calling this function.
template <class Arc>
void PropagateFinal(typename Arc::Label phi_label, MutableFst<Arc> *fst);
// PhiCompose is a version of composition where
// the right hand FST (fst2) has speciall "rho transitions"
// which are taken whenever no normal transition matches; these
// transitions will be rewritten with whatever symbol was on
// the first FST.
template <class Arc>
void RhoCompose(const Fst<Arc> &fst1, const Fst<Arc> &fst2,
typename Arc::Label rho_label, MutableFst<Arc> *fst);
/** This function returns true if, in the semiring of the FST, the sum (within
the semiring) of all the arcs out of each state in the FST is one, to within
delta. After MakeStochasticFst, this should be true (for a connected FST).
@param fst [in] the FST that we are testing.
@param delta [in] the tolerance to within which we test equality to 1.
@param min_sum [out] if non, NULL, contents will be set to the minimum sum
of weights.
@param max_sum [out] if non, NULL, contents will be set to the maximum sum
of weights.
@return Returns true if the FST is stochastic, and false otherwise.
*/
template <class Arc>
bool IsStochasticFst(const Fst<Arc> &fst,
float delta = kDelta, // kDelta = 1.0/1024.0 by default.
typename Arc::Weight *min_sum = NULL,
typename Arc::Weight *max_sum = NULL);
// IsStochasticFstInLog makes sure it's stochastic after casting to log.
inline bool IsStochasticFstInLog(
const Fst<StdArc> &fst,
float delta = kDelta, // kDelta = 1.0/1024.0 by default.
StdArc::Weight *min_sum = NULL, StdArc::Weight *max_sum = NULL);
} // end namespace fst
#include "fstext/fstext-utils-inl.h"
#endif // KALDI_FSTEXT_FSTEXT_UTILS_H_
| [
"zhangjunyi8@huawei.com"
] | zhangjunyi8@huawei.com |
fcae4defd81adfdd35f36763e9d736df398de215 | 282a1e76409c0246eec75fb2c891a81f097e54ff | /src/linalg.hpp | 492ffe8f0c9b8d3eb38b431117f92e168180c0d1 | [] | no_license | JackZhouSz/cip | 714c8fb53d455deaf2098057a98a5c03f63e33de | 5d52a47dfe10557fab2924b76e635eccadec2d14 | refs/heads/master | 2023-03-24T16:23:36.231911 | 2020-07-29T21:46:25 | 2020-07-29T21:46:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,672 | hpp | #include <iostream>
#include <cassert>
#include <stdexcept>
#include <complex>
#include <gsl/gsl_poly.h>
#ifdef __CUDA_ARCH__
# ifdef assert
# undef assert
# endif
# define assert (void)
#endif
// Disclaimer: this is optimized for usability, not speed
// Note: everything is row-major (i.e. Vector represents a row in a matrix)
namespace detail
{
#ifdef __CUDA_ARCH__
template<class T>
__device__ void swap(T &a, T &b)
{
T c = a;
a = b;
b = c;
}
#else
using std::swap;
#endif
}
// Vector<T,N> -------------------------------------------------------
template <class T, int N>
std::vector<T> Vector<T,N>::to_vector() const
{
return std::vector<T>(&m_data[0], &m_data[0]+size());
}
template <class T, int N>
HOSTDEV
const T &Vector<T,N>::operator[](int i) const
{
assert(i >= 0 && i < size());
return m_data[i];
}
template <class T, int N>
HOSTDEV
T &Vector<T,N>::operator[](int i)
{
assert(i >= 0 && i < size());
return m_data[i];
}
template <class T, int N>
HOSTDEV
Vector<T,N> &operator+=(Vector<T,N> &lhs, const Vector<T,N> &rhs)
{
#pragma unroll
for(int j=0; j<N; ++j)
lhs[j] += rhs[j];
return lhs;
}
template <class T, int N>
HOSTDEV
Vector<T,N> operator+(const Vector<T,N> &a, const Vector<T,N> &b)
{
Vector<T,N> r(a);
return r += b;
}
template <class T, int N>
HOSTDEV
Vector<T,N> &operator*=(Vector<T,N> &lhs, const T &rhs)
{
#pragma unroll
for(int j=0; j<lhs.size(); ++j)
lhs[j] *= rhs;
return lhs;
}
template <class T, int N>
HOSTDEV
Vector<T,N> operator*(const Vector<T,N> &a, const T &b)
{
Vector<T,N> r(a);
return r *= b;
}
template <class T, int N>
HOSTDEV
Vector<T,N> operator*(const T &a, const Vector<T,N> &b)
{
return b*a;
}
template <class T, int N>
HOSTDEV
Vector<T,N> &operator/=(Vector<T,N> &lhs, const T &rhs)
{
#pragma unroll
for(int j=0; j<N; ++j)
lhs[j] /= rhs;
return lhs;
}
template <class T, int N>
HOSTDEV
Vector<T,N> operator/(const Vector<T,N> &a, const T &b)
{
Vector<T,N> r(a);
return r /= b;
}
template <class T, int N>
std::ostream &operator<<(std::ostream &out, const Vector<T,N> &v)
{
out << '[';
for(int i=0; i<v.size(); ++i)
{
out << v[i];
if(i < v.size()-1)
out << ',';
}
return out << ']';
}
template <class T, int N>
Vector<T,N> operator-(const Vector<T,N> &v)
{
Vector<T,N> r;
for(int i=0; i<N; ++i)
r[i] = -v[i];
return r;
}
// Matrix<T,M,N> -------------------------------------------------------
template <class T, int M, int N>
HOSTDEV const Vector<T,N> &Matrix<T,M,N>::operator[](int i) const
{
assert(i >= 0 && i < rows());
return m_data[i];
}
template <class T, int M, int N>
HOSTDEV Vector<T,N> &Matrix<T,M,N>::operator[](int i)
{
assert(i >= 0 && i < rows());
return m_data[i];
}
template <class T, int M, int N>
HOSTDEV
Vector<T,M> Matrix<T,M,N>::col(int j) const
{
Vector<T,M> c;
#pragma unroll
for(int i=0; i<rows(); ++i)
c[i] = m_data[i][j];
return c;
}
template <class T, int M, int N>
HOSTDEV
void Matrix<T,M,N>::set_col(int j, const Vector<T,M> &c)
{
#pragma unroll
for(int i=0; i<rows(); ++i)
m_data[i][j] = c[i];
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> operator*(const Matrix<T,M,N> &m, T val)
{
Matrix<T,M,N> r(m);
return r *= val;
}
template <class T, int M, int N>
std::ostream &operator<<(std::ostream &out, const Matrix<T,M,N> &m)
{
out << '[';
for(int i=0; i<m.rows(); ++i)
{
for(int j=0; j<m.cols(); ++j)
{
out << m[i][j];
if(j < m.cols()-1)
out << ',';
}
if(i < m.rows()-1)
out << ";\n";
}
return out << ']';
}
template <class T, int M, int N, int P>
HOSTDEV
Matrix<T,M,P> operator*(const Matrix<T,M,N> &a, const Matrix<T,N,P> &b)
{
Matrix<T,M,P> r;
#pragma unroll
for(int i=0; i<M; ++i)
{
#pragma unroll
for(int j=0; j<P; ++j)
{
r[i][j] = a[i][0]*b[0][j];
#pragma unroll
for(int k=1; k<N; ++k)
r[i][j] += a[i][k]*b[k][j];
}
}
return r;
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> &operator*=(Matrix<T,M,N> &lhs, T rhs)
{
#pragma unroll
for(int i=0; i<lhs.rows(); ++i)
#pragma unroll
for(int j=0; j<lhs.cols(); ++j)
lhs[i][j] *= rhs;
return lhs;
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> operator*(T val, const Matrix<T,M,N> &m)
{
return m * val;
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> &operator+=(Matrix<T,M,N> &lhs, const Matrix<T,M,N> &rhs)
{
#pragma unroll
for(int i=0; i<M; ++i)
#pragma unroll
for(int j=0; j<N; ++j)
lhs[i][j] += rhs[i][j];
return lhs;
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> operator+(const Matrix<T,M,N> &lhs, const Matrix<T,M,N> &rhs)
{
Matrix<T,M,N> r(lhs);
return r += rhs;
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> &operator-=(Matrix<T,M,N> &lhs, const Matrix<T,M,N> &rhs)
{
#pragma unroll
for(int i=0; i<M; ++i)
#pragma unroll
for(int j=0; j<N; ++j)
lhs[i][j] -= rhs[i][j];
return lhs;
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> operator-(const Matrix<T,M,N> &a, const Matrix<T,M,N> &b)
{
Matrix<T,M,N> r(a);
return r -= b;
}
template <class T, int M, int N>
HOSTDEV
Vector<T,N> operator*(const Vector<T,M> &v, const Matrix<T,M,N> &m)
{
Vector<T,N> r;
#pragma unroll
for(int j=0; j<m.cols(); ++j)
{
r[j] = v[0]*m[0][j];
#pragma unroll
for(int i=1; i<m.rows(); ++i)
r[j] += v[i]*m[i][j];
}
return r;
}
template <class T, int M, int N>
HOSTDEV
Vector<T,N> &operator*=(Vector<T,M> &v, const Matrix<T,M,N> &m)
{
return v = v*m;
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> &operator*=(Matrix<T,M,N> &lhs, const Matrix<T,N,N> &rhs)
{
return lhs = lhs*rhs;
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> operator-(const Matrix<T,M,N> &m)
{
Matrix<T,M,N> r;
for(int i=0; i<M; ++i)
for(int j=0; j<N; ++j)
r[i][j] = -m[i][j];
return r;
}
// Special matrices -------------------------------------------------------
template <class T, int N>
HOSTDEV
Vector<T,N> zeros()
{
Vector<T,N> v;
if(N>0)
{
#if __CUDA_ARCH__
#pragma unroll
for(int j=0; j<v.size(); ++j)
v[j] = T();
#else
std::fill(&v[0], &v[N-1]+1, T());
#endif
}
return v; // I'm hoping that RVO will kick in
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> zeros()
{
Matrix<T,M,N> mat;
if(M>0 && N>0)
{
#if __CUDA_ARCH__
#pragma unroll
for(int i=0; i<mat.rows(); ++i)
#pragma unroll
for(int j=0; j<mat.cols(); ++j)
mat[i][j] = T();
#else
std::fill(&mat[0][0], &mat[M-1][N-1]+1, T());
#endif
}
return mat; // I'm hoping that RVO will kick in
}
template <class T, int N>
HOSTDEV
Vector<T,N> ones()
{
Vector<T,N> v;
if(N>0)
{
#if __CUDA_ARCH__
#pragma unroll
for(int j=0; j<v.size(); ++j)
v[j] = T(1);
#else
std::fill(&v[0], &v[N-1]+1, T(1));
#endif
}
return v; // I'm hoping that RVO will kick in
}
template <class T, int M, int N>
HOSTDEV
Matrix<T,M,N> ones()
{
Matrix<T,M,N> mat;
if(M>0 && N>0)
{
#if __CUDA_ARCH__
#pragma unroll
for(int i=0; i<mat.rows(); ++i)
#pragma unroll
for(int j=0; j<mat.cols(); ++j)
mat[i][j] = T(1);
#else
std::fill(&mat[0][0], &mat[M-1][N-1]+1, T(1));
#endif
}
return mat; // I'm hoping that RVO will kick in
}
template <class T, int M, int N>
Matrix<T,M,N> identity()
{
Matrix<T,M,N> mat;
for(int i=0; i<M; ++i)
for(int j=0; j<N; ++j)
mat[i][j] = i==j ? 1 : 0;
return mat;
}
template <class T, int M>
Matrix<T,M,M> vander(const Vector<T,M> &v)
{
using std::pow;
Matrix<T,M,M> m;
for(int i=0; i<M; ++i)
for(int j=0; j<M; ++j)
m[i][j] = pow(v[j],i);
return m;
}
template <class T, int R>
Matrix<T,R,R> compan(const Vector<T,R> &a)
{
Matrix<T,R,R> m;
for(int i=0; i<R; ++i)
{
for(int j=0; j<R; ++j)
{
if(j == R-1)
m[i][j] = -a[i];
else
m[i][j] = j == i-1 ? 1 : 0;
}
}
return m;
}
// Basic operations ---------------------------------------------------
template <class T, int N>
HOSTDEV
T dot(const Vector<T,N> &a, const Vector<T,N> &b)
{
T d = a[0]+b[0];
#pragma unroll
for(int j=1; j<a.size(); ++j)
d += a[j]+b[j];
return d;
}
template <class T, int N>
HOSTDEV
Vector<T,N> reverse(const Vector<T,N> &a)
{
Vector<T,N> r;
#pragma unroll
for(int j=0; j<r.size(); ++j)
r[j] = a[a.size()-1-j];
return r;
}
// Transposition -----------------------------------------------------
template <class T, int M>
Matrix<T,M,M> &transp_inplace(Matrix<T,M,M> &m)
{
for(std::size_t i=0; i<m.rows(); ++i)
for(std::size_t j=i+1; j<m.cols(); ++j)
detail::swap(m[i][j], m[j][i]);
return m;
}
template <class T, int M, int N>
HOSTDEV Matrix<T,N,M> transp(const Matrix<T,M,N> &m)
{
Matrix<T,N,M> tm;
#pragma unroll
for(int i=0; i<m.rows(); ++i)
#pragma unroll
for(int j=0; j<m.cols(); ++j)
tm[j][i] = m[i][j];
return tm;
}
template <class T, int M, int N>
HOSTDEV Matrix<T,M,N> flip_rows(const Matrix<T,M,N> &m)
{
Matrix<T,M,N> f;
#pragma unroll
for(int i=0; i<m.rows(); ++i)
#pragma unroll
for(int j=0; j<m.cols(); ++j)
f[i][j] = m[M-1-i][j];
return f;
}
template <class T, int M, int N>
HOSTDEV Matrix<T,M,N> flip_cols(const Matrix<T,M,N> &m)
{
Matrix<T,M,N> f;
#pragma unroll
for(int i=0; i<m.rows(); ++i)
#pragma unroll
for(int j=0; j<m.cols(); ++j)
f[i][j] = m[i][N-1-j];
return f;
}
template <class T, int M, int N>
HOSTDEV Matrix<T,M,N> flip(const Matrix<T,M,N> &m)
{
Matrix<T,M,N> f;
#pragma unroll
for(int i=0; i<m.rows(); ++i)
#pragma unroll
for(int j=0; j<m.cols(); ++j)
f[i][j] = m[M-1-i][N-1-j];
return f;
}
// LU decomposition -----------------------------------------------------
template <class T, int M>
void lu_inplace(Matrix<T,M,M> &m, Vector<int,M> *p=NULL, T *d=NULL)
{
// Ref: Numerical Recipes in C++, 3rd ed, Chapter 2, pp. 52-53
// Crout's algorithm with implicit pivoting (based on partial pivoting)
// stores the implicit scaling of each row
Vector<double,M> vv;
// baca...
using std::max;
// Loop over rows to get the implicit scaling information
for(int i=0; i<vv.size(); ++i)
{
double big = 0;
for(int j=0; j<vv.size(); ++j)
big = max<double>(big,abs(m[i][j]));
if(big == 0)
throw std::runtime_error("Singular matrix in lu_into");
vv[i] = 1/big;
}
if(d)
*d = 1; // no row interchanges yet
for(int k=0; k<vv.size(); ++k)
{
// Initialize for the search for largest pivot element
double big = 0;
int imax=k;
for(int i=k; i<vv.size(); ++i)
{
// Is the figure of merit for the pivot better than the
// best so far?
double aux = vv[i]*abs(m[i][k]);
if(aux > big)
{
big = aux;
imax = i;
}
}
// Do we need to interchange rows?
if(k != imax)
{
// Do it
detail::swap(m[imax], m[k]);
if(d)
*d = -*d;
vv[imax] = vv[k]; // interchange the scale factor
}
if(p)
(*p)[k] = imax;
// If the pivot element is zero the matrix is singular (at least to
// the precision of the algorithm). For some applications on singular
// matrices, it is desirable to substitute EPSILON for zero
if(m[k][k] == T())
m[k][k] = 1e-20;
// Now, finally, divide by the pivot element
for(int i=k+1; i<vv.size(); ++i)
{
T aux;
aux = m[i][k] /= m[k][k];
for(int j=k+1; j<vv.size(); ++j)
m[i][j] -= aux*m[k][j];
}
}
}
template <class T, int M>
Matrix<T,M,M> lu(const Matrix<T,M,M> &m, Vector<int,M> *p, T *d=NULL)
{
Matrix<T,M,M> lu = m;
lu_inplace(lu, p, d);
return lu;
}
// Solve --------------------------------------------------------------
template <class T, int M>
void solve_inplace(const Matrix<T,M,M> &lu, const Vector<int,M> &p, Vector<T,M> &b)
{
// Ref: Numerical Recipes in C, 2nd ed, Chapter 2.3, p. 47
// We now do the forward substitution.
int ii=-1;
for(std::size_t i=0; i<M; ++i)
{
int ip = p[i];
T sum = b[ip];
b[ip] = b[i];
// When ii>=0, it will become the index of the first
// nonvanishing element of b.
if(ii>=0)
{
for(std::size_t j=ii; j<i; ++j)
sum -= lu[i][j]*b[j];
}
else if(sum != T())
ii = i;
b[i] = sum;
}
// Now to the back substitution
for(std::size_t i=M-1; (int)i>=0; --i)
{
T sum = b[i];
for(std::size_t j=i+1; j<M; ++j)
sum -= lu[i][j]*b[j];
b[i] = sum/lu[i][i];
}
}
template <class T, int M>
void solve_inplace(const Matrix<T,M,M> &m, Vector<T,M> &b)
{
Vector<int,M> p;
Matrix<T,M,M> LU = lu(m, &p);
solve_inplace(LU, p, b);
}
template <class T, int M>
Vector<T,M> solve(const Matrix<T,M,M> &lu, const Vector<int,M> &p, const Vector<T,M> &b)
{
Vector<T,M> x = b;
solve_inplace(lu, p, x);
return x;
}
template <class T, int M>
Vector<T,M> solve(const Matrix<T,M,M> &m, const Vector<T,M> &b)
{
Vector<int,M> p;
Matrix<T,M,M> LU = lu(m, &p);
return solve(LU, p, b);
}
// Determinant ---------------------------------------------------------------
template <class T>
T det(const Matrix<T,0,0> &m)
{
return 1; // surprising, isn't it?
}
template <class T>
T det(const Matrix<T,1,1> &m)
{
return m[0][0];
}
template <class T>
T det(const Matrix<T,2,2> &m)
{
return m[0][0]*m[1][1] - m[0][1]*m[1][0];
}
template <class T>
T det(const Matrix<T,3,3> &m)
{
return m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1]) +
m[0][1]*(m[1][2]*m[2][0] - m[1][0]*m[2][2]) +
m[0][2]*(m[1][0]*m[2][1] - m[1][1]*m[2][0]);
}
template <class T, int M>
T det(const Matrix<T,M,M> &m)
{
T d;
Matrix<T,M,M> LU = lu(m, (Vector<int,M> *)NULL, &d);
for(std::size_t i=0; i<M; ++i)
d *= LU[i][i];
return d;
}
// Matrix Inverse ------------------------------------------------------------
template <class T, int M>
void inv_lu(Matrix<T,M,M> &out, Matrix<T,M,M> &m)
{
// Ref: Numerical Recipes in C, 2nd ed, Chapter 2.3, p. 48
Vector<int,M> p;
lu_inplace(m, &p);
out = identity<T,M,M>();
for(int i=0; i<M; ++i)
solve_inplace(m, p, out[i]);
transp_inplace(out);
}
template <class T>
void inv_inplace(Matrix<T,1,1> &m)
{
m[0][0] = T(1)/m[0][0];
}
template <class T>
void inv_inplace(Matrix<T,2,2> &m)
{
T d = det(m);
detail::swap(m[0][0],m[1][1]);
m[0][0] /= d;
m[1][1] /= d;
m[0][1] = -m[0][1]/d;
m[1][0] = -m[1][0]/d;
}
template <class T, int M>
void inv_inplace(Matrix<T,M,M> &m)
{
Matrix<T,M,M> y;
inv_lu(y, m);
m = y;//std::move(y);
}
template <class T, int M>
Matrix<T,M,M> inv(Matrix<T,M,M> m)
{
inv_inplace(m);
return m;
}
// other --------------------------------
template <class T, int R>
Matrix<T,R,R> compan_pow(const Vector<T,R> &a, int p)
{
typedef std::complex<double> dcomplex;
Vector<double,R+1> da;
for(int i=0; i<R; ++i)
da[i] = a[i];
da[R] = 1;
Vector<dcomplex,R> r;
gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc(R+1);
gsl_poly_complex_solve((const double *)&da, R+1, w, (double *)&r);
gsl_poly_complex_workspace_free(w);
Matrix<dcomplex,R,R> S = vander(r), D;
for(int i=0; i<R; ++i)
for(int j=0; j<R; ++j)
D[i][j] = i==j ? pow(r[i],p) : 0;
D = S*D*inv(S);
Matrix<T,R,R> C;
for(int i=0; i<R; ++i)
{
for(int j=0; j<R; ++j)
{
assert(std::abs(imag(D[i][j])) <= 1e-6);
C[i][j] = real(D[i][j]);
}
}
return C;
}
| [
"rodolfo@rodlima.net"
] | rodolfo@rodlima.net |
b1b72972f42461e38b6e24451828548f3ba89d10 | 5d5baef098c65be072a7ce12899d320847e8636d | /Game Spy Player/MainFrm.cpp | 37a45da1720bba561946d01756fd5b18241a9301 | [] | no_license | OlafvdSpek/xcc | e43bfdaf2fbac4c413fc7855ddf378b6d7975024 | 76adf95fc048d8c1143b3bcc8e777f870245680d | refs/heads/master | 2023-03-23T13:10:33.983570 | 2023-03-12T08:30:29 | 2023-03-12T08:30:29 | 44,600,393 | 44 | 18 | null | 2016-02-17T17:16:10 | 2015-10-20T10:59:00 | C++ | UTF-8 | C++ | false | false | 963 | cpp | #include "stdafx.h"
#include "MainFrm.h"
IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
};
CMainFrame::CMainFrame()
{
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CMDIFrameWnd::PreCreateWindow(cs) )
return FALSE;
cs.style = WS_OVERLAPPED | WS_CAPTION | FWS_ADDTOTITLE
| WS_THICKFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_MAXIMIZE;
return TRUE;
}
| [
"olafvdspek@108d0302-aaf7-b7c6-26e7-3e45b3cf5337"
] | olafvdspek@108d0302-aaf7-b7c6-26e7-3e45b3cf5337 |
65cf3b80f504edd20284499e59337a15fcc7d2de | 5244457901fcbb99141c8278a7ea763e0359a650 | /series0/linear_regression/main.cpp | b5e8f5fe0e6d90ee38cd9ca99bf64e7cb4874749 | [
"MIT"
] | permissive | westernmagic/NumPDE | c7fda74292ffcacff8cb00198be927d05410ca04 | 98786723b0944d48202f32bc8b9a0185835e03e8 | refs/heads/master | 2021-01-20T10:55:35.957309 | 2017-05-29T10:40:29 | 2017-05-29T10:40:29 | 85,193,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | #include <Eigen/Dense>
#include <iostream>
int main(int argc, char **argv) {
// Declare Eigen vector type for doubles
using vector_t = Eigen::VectorXd;
// Initialize Eigen vector containing body weight in Kg(X)
vector_t X(15);
X << 2, 2.2, 2.4, 2.2, 2.6, 2.2, 2.4, 2.4, 2.5, 2.7, 2.6, 2.2,
2.5, 2.5, 2.5;
// Initialize Eigen vector containing heart weight in g (Y)
vector_t Y(15);
Y << 6.5, 7.2, 7.3, 7.6, 7.7, 7.9, 7.9, 7.9, 7.9, 8.0, 8.3, 8.5,
8.6, 8.8, 8.8;
// TODO: Initialize Eigen Matrix A
Eigen::MatrixXd A(15, 2);
// (write your solution here)
// Create LHS = A'*A
Eigen::MatrixXd LHS = A.transpose() * A;
// TODO: Create RHS = A'*Y
// (write your solution here)
// TODO: Solve system and output coefficients b_0 and b_1
// (write your solution here)
return 0;
}
| [
"mswoj61@gmail.com"
] | mswoj61@gmail.com |
9ab29df6e15f4f449ee81a8854a90be5c11fb158 | be3ae64c34c8d0e40bb23a6369715862562fade5 | /CaffeEval/main.h | 84821a313a43217e8e6502f4abf260c96d3bac61 | [] | no_license | techmatt/LucidFlow | 361b1fd99fb240b805ef588940f6624864998b5a | 3fe419a6e7e905682b726b162a477af9cbc311e5 | refs/heads/master | 2021-01-10T02:51:27.409241 | 2016-01-13T20:08:07 | 2016-01-13T20:08:07 | 48,936,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | h |
#include "mLibInclude.h"
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <stdint.h>
#include <sys/stat.h>
#include <direct.h>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include "boost/algorithm/string.hpp"
#include "caffe/caffe.hpp"
#include "caffe/util/signal_handler.h"
using namespace caffe; // NOLINT(build/namespaces)
using namespace google;
#include "../common/constants.h"
#include "../common/patient.h"
#include "util.h"
#include "networkProcessor.h"
| [
"techmatt@gmail.com"
] | techmatt@gmail.com |
f915e9862145fb2a99a4927ae26ec8fcdb64fd27 | 14f6a5983122e5ac0113406756ad5c46d50e7141 | /trabalho1.ino | 47c0a820f469f97fba7b1aa942d7d3479448cbb1 | [] | no_license | erdrborges/automacaoArduino | fc5ff52aa878b61eedc4bec108b21f01992b4021 | 5ce3c3e921333463075fc80a54aa4340219176f3 | refs/heads/master | 2020-07-27T19:45:37.487034 | 2019-09-18T02:28:36 | 2019-09-18T02:28:36 | 209,199,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,809 | ino | #include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#define FIREBASE_HOST "homesweethome-fc94e.firebaseio.com"
#define FIREBASE_AUTH "KRlR0KVAckwhhrsFLVzbgDSvfm4lMHHGBhfIC2lV"
#define WIFI_SSID "ifdoce"
#define WIFI_PASSWORD "10tifsul"
//#define LED_AZUL 3
//#define LED_VERMELHO 16
void autenticaFirebase(){
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
void conectaWifi(){
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("\nconnecting");
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("Connect: ");
Serial.println(WiFi.localIP());
autenticaFirebase();
}
void setup() {
Serial.begin(9600);
// pinMode(LED_AZUL, OUTPUT);
// pinMode(LED_VERMELHO, OUTPUT);
conectaWifi();
}
void loop() {
if(WiFi.status() == WL_CONNECTED){
if(Firebase.success()){
FirebaseObject corredor = Firebase.get("casa/corredor");
FirebaseObject cozinha = Firebase.get("casa/cozinha");
FirebaseObject garagem = Firebase.get("casa/garagem");
FirebaseObject living = Firebase.get("casa/living");
FirebaseObject quarto1 = Firebase.get("casa/quarto1(suite");
FirebaseObject quarto2 = Firebase.get("casa/quarto2");
FirebaseObject quarto3 = Firebase.get("casa/quarto3");
FirebaseObject varanda = Firebase.get("casa/varanda");
//segmento de código para o corredor
if(corredor.getBool("/lamp_bath")){
Serial.print("\nLâmpada do banheiro acessa.");
}else{
Serial.print("\nLâmpada do banheiro apagada.");
}
if(corredor.getBool("/lamp_cor")){
Serial.print("\nLâmpada do corredor acessa.");
}else{
Serial.print("\nLâmpada do corredor acessa.");
}
//fim do segmento
//segmento de código para o conjunto cozinha
if(cozinha.getBool("/lamp_kit")){
Serial.print("\nLâmpada da cozinha acessa.");
}else{
Serial.print("\nLâmpada da cozinha apagada.");
}
if(cozinha.getBool("/lamp_laundry")){
Serial.print("\nLâmpada da lavanderia acessa.");
}else{
Serial.print("\nLâmpada da lavanderia desligada.");
}
//fim do segmento
//segmento de código para a garagem
if(garagem.getBool("/gate_garage")){
Serial.print("\nPortão da garagem aberto.");
}else{
Serial.print("\nPortão da garagem fechado.");
}
if(garagem.getBool("/lamp_garage")){
Serial.print("\nLâmpada da garagem acesa.");
}else{
Serial.print("\nLâmpada da garagem apagada.");
}
//fim do segmento
//segmento de código para o conjunto living
if(living.getBool("/lamp_dining")){
Serial.print("\nLâmpada da sala de jantar acesa.");
}else{
Serial.print("\nLâmpada da sala de jantar apagada.");
}
if(living.getBool("/lamp_hall")){
Serial.print("\nLâmpada do hall de entrada acesa.");
}else{
Serial.print("\nLâmpada do hall de entrada apagada.");
}
if(living.getBool("/lamp_living")){
Serial.print("\nLâmpada da sala de estar acesa.");
}else{
Serial.print("\nLâmpada da sala de estar apagada.");
}
//fim do segmento
//segmento de código para o quarto1(suite)
if(quarto1.getBool("/ar_bed")){
Serial.print("\nAr condicionado do Quarto 1 ligado.");
}else{
Serial.print("\nAr condicionado do Quarto 1 desligado.");
}
if(quarto1.getBool("/lamp_bed")){
Serial.print("\nLâmpada do Quarto 1 acessa.");
}else{
Serial.print("\nLâmpada do Quarto 1 apagada.");
}
if(quarto1.getBool("/lamp_closet")){
Serial.print("\nLâmpada do closed do Quarto 1 acesa.");
}else{
Serial.print("\nLâmpada do closed do Quarto 1 apagada.");
}
if(quarto1.getBool("/lamp_wc")){
Serial.print("\nLâmpada do banheiro do Quarto 1 acesa.");
}else{
Serial.print("\nLâmpada do banheiro do Quarto 1 apagada.");
}
//fim do segmento
//segmento de código para o quarto2
if(quarto2.getBool("/ar_bed")){
Serial.print("\nAr condicionado do Quarto 2 ligado.");
}else{
Serial.print("\nAr condicionado do Quarto 2 desligado.");
}
if(quarto2.getBool("/lamp_bed")){
Serial.print("\nLâmpada do Quarto 2 acesa.");
}else{
Serial.print("\nLâmpada do Quarto 2 apagada");
}
//fim do segmento
//segmento de código para o quarto3
if(quarto3.getBool("/ar_bed")){
Serial.print("\nAr condicionado do Quarto 3 ligado.");
}else{
Serial.print("\nAr condicionado do Quarto 3 desligado.");
}
if(quarto3.getBool("/lamp_bed")){
Serial.print("\nLâmpada do Quarto 3 acesa.");
}else{
Serial.print("\nLâmpada do Quarto 3 apagada.");
}
//fim do segmento
//segmento de código para a varanda
if(varanda.getBool("/lamp_balc_hall")){
Serial.print("\nLâmpada da varanda do hall acesa.");
}else{
Serial.print("\nLâmpada da varanda do hall apagada.");
}
if(varanda.getBool("/lamp_balc_liv")){
Serial.print("\nLâmpada da varanda da sala acesa.");
}else{
Serial.print("\nLâmpada da varanda da sala apagada.");
}
if(varanda.getBool("/lamp_balc_laundry")){
Serial.print("\nLâmpada da Saída da Lavanderia acessa.");
}else{
Serial.print("\nLâmpada da Saída da Lavanderia apagada.");
}
//Serial.println("Autenticado no Firebase");
}else{
Serial.println("Erro na autenticação com o Firebase");
}
}else{
conectaWifi();
}
delay(500);
}
| [
"erdrborges@gmail.com"
] | erdrborges@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.